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
#![no_std]
use core::convert::TryFrom;
use core::marker::PhantomData;
use core::fmt::Debug;
use log::{trace, debug, warn};
use embedded_hal::spi::{Mode as SpiMode, Phase, Polarity};
use embedded_hal::spi::blocking::{Transfer, Write, Transactional};
use embedded_hal::delay::blocking::{DelayMs, DelayUs};
use embedded_hal::digital::blocking::{InputPin, OutputPin};
use driver_pal::{wrapper::Wrapper as SpiWrapper, Error as WrapError};
use radio::{Power as _, State as _};
pub mod base;
pub mod device;
use device::{regs, Channel, Interrupts, Config, Modem, ModemMode, PaConfig, PacketInfo, State};
pub mod fsk;
pub mod lora;
pub mod prelude;
pub const SPI_MODE: SpiMode = SpiMode {
polarity: Polarity::IdleLow,
phase: Phase::CaptureOnFirstTransition,
};
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Mode {
Unconfigured,
LoRa,
FskOok,
}
pub struct Sx127x<Base, CommsError, PinError, DelayError> {
hal: Base,
_ce: PhantomData<CommsError>,
_pe: PhantomData<PinError>,
_de: PhantomData<DelayError>,
mode: Mode,
config: Config,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Error<CommsError, PinError, DelayError> {
Comms(CommsError),
Pin(PinError),
Delay(DelayError),
InvalidConfiguration,
Aborted,
InvalidResponse,
Timeout,
Crc,
BufferSize,
InvalidDevice(u8),
}
impl<CommsError, PinError, DelayError> From<WrapError<CommsError, PinError, DelayError>> for Error<CommsError, PinError, DelayError> {
fn from(e: WrapError<CommsError, PinError, DelayError>) -> Self {
match e {
WrapError::Spi(e) => Error::Comms(e),
WrapError::Pin(e) => Error::Pin(e),
WrapError::Delay(e) => Error::Delay(e),
WrapError::Aborted => Error::Aborted,
}
}
}
#[derive(Clone, PartialEq, Debug)]
pub struct Settings {
pub xtal_freq: u32,
}
impl Default for Settings {
fn default() -> Self {
Self {
xtal_freq: 32000000,
}
}
}
pub type Sx127xSpi<Spi, SpiError, CsPin, BusyPin, ReadyPin, SdnPin, PinError, Delay, DelayError> = Sx127x<SpiWrapper<Spi, CsPin, BusyPin, ReadyPin, SdnPin, Delay>, SpiError, PinError, DelayError>;
impl<Spi, SpiError, CsPin, BusyPin, ReadyPin, ResetPin, PinError, Delay, DelayError>
Sx127x<SpiWrapper<Spi, CsPin, BusyPin, ReadyPin, ResetPin, Delay>, SpiError, PinError, DelayError>
where
Spi: Transfer<u8, Error = SpiError> + Write<u8, Error = SpiError> + Transactional<u8, Error = SpiError>,
CsPin: OutputPin<Error = PinError>,
BusyPin: InputPin<Error = PinError>,
ReadyPin: InputPin<Error = PinError>,
ResetPin: OutputPin<Error = PinError>,
Delay: DelayMs<u32, Error = DelayError> + DelayUs<u32, Error = DelayError>,
SpiError: Debug + Sync + Send + 'static,
PinError: Debug + Sync + Send + 'static,
DelayError: Debug + Sync + Send + 'static,
{
pub fn spi(
spi: Spi,
cs: CsPin,
busy: BusyPin,
ready: ReadyPin,
reset: ResetPin,
delay: Delay,
config: &Config,
) -> Result<Self, Error<SpiError, PinError, DelayError>> {
let hal = SpiWrapper::new(spi, cs, reset, busy, ready, delay);
Self::new(hal, config)
}
}
impl<Base, CommsError, PinError, DelayError> Sx127x<Base, CommsError, PinError, DelayError>
where
Base: base::Base<CommsError, PinError, DelayError>,
CommsError: Debug + Sync + Send + 'static,
PinError: Debug + Sync + Send + 'static,
DelayError: Debug + Sync + Send + 'static,
{
pub fn new(hal: Base, config: &Config) -> Result<Self, Error<CommsError, PinError, DelayError>> {
let mut sx127x = Self::build(hal, config.clone());
sx127x.hal.reset()?;
let version = sx127x.silicon_version()?;
if version != 0x12 {
return Err(Error::InvalidDevice(version));
}
sx127x.rf_chain_calibration()?;
sx127x.set_state(State::Sleep)?;
for (modem, reg, val) in device::REGISTERS_INIT {
sx127x.set_modem(*modem)?;
sx127x.write_reg(*reg, *val)?;
}
sx127x.configure(config)?;
Ok(sx127x)
}
pub fn reset(&mut self) -> Result<(), Error<CommsError, PinError, DelayError>> {
self.hal.reset()?;
self.rf_chain_calibration()?;
self.set_state(State::Sleep)?;
for (modem, reg, val) in device::REGISTERS_INIT {
self.set_modem(*modem)?;
self.write_reg(*reg, *val)?;
}
Ok(())
}
pub fn configure(&mut self, config: &Config) -> Result<(), Error<CommsError, PinError, DelayError>> {
match (&config.modem, &config.channel) {
(Modem::LoRa(lora_modem), Channel::LoRa(lora_channel)) => {
self.lora_configure(lora_modem, lora_channel)?;
}
(Modem::FskOok(fsk_modem), Channel::FskOok(fsk_channel)) => {
self.fsk_configure(fsk_modem, fsk_channel)?;
}
_ => panic!("Invalid configuration, mismatch between Modem ({:?}) and Channel ({:?} modes", &config.modem, &config.channel),
}
self.configure_pa(&config.pa_config)?;
self.config = config.clone();
Ok(())
}
pub fn silicon_version(&mut self) -> Result<u8, Error<CommsError, PinError, DelayError>> {
self.read_reg(regs::Common::VERSION)
}
pub(crate) fn configure_pa(
&mut self,
pa_config: &PaConfig,
) -> Result<(), Error<CommsError, PinError, DelayError>> {
use device::*;
match pa_config.output {
PaSelect::Rfo(max) => {
self.update_reg(
regs::Common::PACONFIG,
PASELECT_MASK | MAXPOWER_MASK,
PASELECT_RFO | ((max << MAXPOWER_SHIFT) & MAXPOWER_MASK),
)?;
}
PaSelect::Boost => {
self.update_reg(regs::Common::PACONFIG, PASELECT_MASK, PASELECT_PA_BOOST)?;
}
}
self.set_power(pa_config.power)?;
Ok(())
}
pub(crate) fn set_state_checked(
&mut self,
state: State,
) -> Result<(), Error<CommsError, PinError, DelayError>> {
trace!("Set state to: {:?} (0x{:02x})", state, state as u8);
self.set_state(state)?;
let mut ticks = 0;
loop {
let s = self.get_state()?;
trace!("Received: {:?}", s);
if state == s {
break;
}
if ticks >= self.config.timeout_ms {
warn!("Set state timeout");
return Err(Error::Timeout)
}
self.hal.delay_ms(1).map_err(Error::Delay)?;
ticks += 1;
}
Ok(())
}
pub(crate) fn freq_to_channel_index(&self, freq: u32) -> u32 {
let step = (self.config.xtal_freq as f32) / (2u32.pow(19) as f32);
let ch = (freq as f32) / step;
ch as u32
}
pub(crate) fn channel_index_to_freq(&self, ch: u32) -> u32 {
let step = (self.config.xtal_freq as f32) / (2u32.pow(19) as f32);
let freq = (ch as f32) * step;
freq as u32
}
pub(crate) fn set_modem(
&mut self,
modem: ModemMode,
) -> Result<(), Error<CommsError, PinError, DelayError>> {
match modem {
ModemMode::Standard => {
self.set_state(State::Sleep)?;
self.update_reg(
regs::Common::OPMODE,
device::OPMODE_LONGRANGEMODE_MASK | device::OPMODE_MODULATION_MASK,
device::LongRangeMode::Off as u8 | device::ModulationType::Fsk as u8,
)?;
}
ModemMode::LoRa => {
self.set_state(State::Sleep)?;
self.update_reg(
regs::Common::OPMODE,
device::OPMODE_LONGRANGEMODE_MASK,
device::LongRangeMode::On as u8,
)?;
}
}
Ok(())
}
pub(crate) fn set_frequency(&mut self, freq: u32) -> Result<(), Error<CommsError, PinError, DelayError>> {
let channel = self.freq_to_channel_index(freq);
let outgoing = [
(channel >> 16) as u8,
(channel >> 8) as u8,
(channel >> 0) as u8,
];
debug!("Set channel to index: {:?} (freq: {:?})", channel, freq);
self.hal.write_regs(regs::Common::FRFMSB as u8, &outgoing)?;
Ok(())
}
pub(crate) fn get_frequency(&mut self) -> Result<u32, Error<CommsError, PinError, DelayError>> {
let mut incoming = [0u8; 3];
self.hal
.read_regs(regs::Common::FRFMSB as u8, &mut incoming)?;
let ch = (incoming[0] as u32) << 16 | (incoming[1] as u32) << 8 | (incoming[2] as u32) << 0;
let freq = self.channel_index_to_freq(ch);
Ok(freq)
}
pub(crate) fn rf_chain_calibration(&mut self) -> Result<(), Error<CommsError, PinError, DelayError>> {
debug!("Running calibration");
let frequency = self.get_frequency()?;
let pa_config = self.read_reg(regs::Common::PACONFIG)?;
self.write_reg(regs::Common::PACONFIG, 0x00)?;
self.update_reg(
regs::Fsk::IMAGECAL,
regs::RF_IMAGECAL_IMAGECAL_MASK as u8,
regs::RF_IMAGECAL_IMAGECAL_START as u8,
)?;
while self.read_reg(regs::Fsk::IMAGECAL)? & (regs::RF_IMAGECAL_IMAGECAL_RUNNING as u8) != 0
{
}
self.set_frequency(868e6 as u32)?;
self.update_reg(
regs::Fsk::IMAGECAL,
regs::RF_IMAGECAL_IMAGECAL_MASK as u8,
regs::RF_IMAGECAL_IMAGECAL_START as u8,
)?;
while self.read_reg(regs::Fsk::IMAGECAL)? & (regs::RF_IMAGECAL_IMAGECAL_RUNNING as u8) != 0
{
}
self.set_frequency(frequency)?;
self.write_reg(regs::Common::PACONFIG, pa_config)?;
debug!("Calibration done");
Ok(())
}
}
impl<Base, CommsError, PinError, DelayError> Sx127x<Base, CommsError, PinError, DelayError>
where
Base: base::Base<CommsError, PinError, DelayError>,
CommsError: Debug + Sync + Send + 'static,
PinError: Debug + Sync + Send + 'static,
DelayError: Debug + Sync + Send + 'static,
{
pub(crate) fn build(hal: Base, config: Config) -> Self {
Sx127x {
hal,
config,
mode: Mode::Unconfigured,
_ce: PhantomData,
_pe: PhantomData,
_de: PhantomData,
}
}
}
impl<Base, CommsError, PinError, DelayError> DelayMs<u32> for Sx127x<Base, CommsError, PinError, DelayError>
where
Base: base::Base<CommsError, PinError, DelayError>,
CommsError: Debug + Sync + Send + 'static,
PinError: Debug + Sync + Send + 'static,
DelayError: Debug + Sync + Send + 'static,
{
type Error = Error<CommsError, PinError, DelayError>;
fn delay_ms(&mut self, t: u32) -> Result<(), Error<CommsError, PinError, DelayError>> {
self.hal.delay_ms(t).map_err(Error::Delay)
}
}
impl<Base, CommsError, PinError, DelayError> Sx127x<Base, CommsError, PinError, DelayError>
where
Base: base::Base<CommsError, PinError, DelayError>,
CommsError: Debug + Sync + Send + 'static,
PinError: Debug + Sync + Send + 'static,
DelayError: Debug + Sync + Send + 'static,
{
pub fn read_reg<R>(&mut self, reg: R) -> Result<u8, Error<CommsError, PinError, DelayError>>
where
R: Copy + Clone + Debug + Into<u8>,
{
let value = self.hal.read_reg(reg.into())?;
trace!("Read reg: {:?} (0x{:02x}): 0x{:02x}", reg, reg.into(), value);
Ok(value)
}
pub fn write_reg<R>(&mut self, reg: R, value: u8) -> Result<(), Error<CommsError, PinError, DelayError>>
where
R: Copy + Clone + Debug + Into<u8>,
{
trace!("Write reg: {:?} (0x{:02x}): 0x{:02x}", reg, reg.into(), value);
self.hal.write_reg(reg.into(), value)
}
pub fn update_reg<R>(
&mut self,
reg: R,
mask: u8,
value: u8,
) -> Result<u8, Error<CommsError, PinError, DelayError>>
where
R: Copy + Clone + Debug + Into<u8>,
{
trace!("Update reg: {:?} (0x{:02x}): 0x{:02x} (0x{:02x})", reg, reg.into(), value, mask);
self.hal.update_reg(reg.into(), mask, value)
}
}
impl<Base, CommsError, PinError, DelayError> radio::State for Sx127x<Base, CommsError, PinError, DelayError>
where
Base: base::Base<CommsError, PinError, DelayError>,
CommsError: Debug + Sync + Send + 'static,
PinError: Debug + Sync + Send + 'static,
DelayError: Debug + Sync + Send + 'static,
{
type State = State;
type Error = Error<CommsError, PinError, DelayError>;
fn get_state(&mut self) -> Result<Self::State, Self::Error> {
let state = self.read_reg(regs::Common::OPMODE)?;
let state = State::try_from(state & device::OPMODE_STATE_MASK)
.map_err(|_| Error::InvalidResponse)?;
Ok(state)
}
fn set_state(&mut self, state: Self::State) -> Result<(), Self::Error> {
self.update_reg(regs::Common::OPMODE, device::OPMODE_STATE_MASK, state as u8)?;
Ok(())
}
}
impl<Base, CommsError, PinError, DelayError> radio::Power for Sx127x<Base, CommsError, PinError, DelayError>
where
Base: base::Base<CommsError, PinError, DelayError>,
CommsError: Debug + Sync + Send + 'static,
PinError: Debug + Sync + Send + 'static,
DelayError: Debug + Sync + Send + 'static,
{
type Error = Error<CommsError, PinError, DelayError>;
fn set_power(&mut self, power: i8) -> Result<(), Error<CommsError, PinError, DelayError>> {
use device::*;
let power = core::cmp::max(power, 0);
let config = self.read_reg(regs::Common::PACONFIG)?;
match config & PASELECT_MASK {
PASELECT_RFO => {
let max = ((config & MAXPOWER_MASK) >> MAXPOWER_SHIFT) as i8;
let power = core::cmp::min(power, 17i8);
let value = power - max + 15;
let v = self.update_reg(regs::Common::PACONFIG, OUTPUTPOWER_MASK, value as u8)?;
debug!("Updated RFO PA_CONFIG for: {} dBm to: {:b}", power, v);
}
PASELECT_PA_BOOST => {
let power = core::cmp::min(power, 20i8);
let value = power - 17 + 15;
self.update_reg(regs::Common::PACONFIG, OUTPUTPOWER_MASK, value as u8)?;
let pa_dac_enable = if power > 17 {
PADAC_20DBM_ON
} else {
PADAC_20DBM_OFF
};
let v = self.update_reg(regs::Common::PADAC, PADAC_MASK, pa_dac_enable)?;
debug!("Updated BOOST PA_CONFIG for: {} dBm to: {:b}", power, v);
}
_ => (),
}
Ok(())
}
}
impl<Base, CommsError, PinError, DelayError> radio::Interrupts for Sx127x<Base, CommsError, PinError, DelayError>
where
Base: base::Base<CommsError, PinError, DelayError>,
CommsError: Debug + Sync + Send + 'static,
PinError: Debug + Sync + Send + 'static,
DelayError: Debug + Sync + Send + 'static,
{
type Irq = Interrupts;
type Error = Error<CommsError, PinError, DelayError>;
fn get_interrupts(&mut self, clear: bool) -> Result<Self::Irq, Self::Error> {
match self.mode {
Mode::LoRa => Ok(Interrupts::LoRa(self.lora_get_interrupts(clear)?)),
Mode::FskOok => Ok(Interrupts::FskOok(self.fsk_get_interrupts(clear)?)),
_ => Err(Error::InvalidConfiguration),
}
}
}
impl<Base, CommsError, PinError, DelayError> radio::Channel for Sx127x<Base, CommsError, PinError, DelayError>
where
Base: base::Base<CommsError, PinError, DelayError>,
CommsError: Debug + Sync + Send + 'static,
PinError: Debug + Sync + Send + 'static,
DelayError: Debug + Sync + Send + 'static,
{
type Channel = Channel;
type Error = Error<CommsError, PinError, DelayError>;
fn set_channel(&mut self, channel: &Self::Channel) -> Result<(), Error<CommsError, PinError, DelayError>> {
match (self.mode, channel) {
(Mode::LoRa, Channel::LoRa(channel)) => self.lora_set_channel(channel),
(Mode::FskOok, Channel::FskOok(channel)) => self.fsk_set_channel(channel),
_ => Err(Error::InvalidConfiguration),
}
}
}
impl<Base, CommsError, PinError, DelayError> radio::Transmit for Sx127x<Base, CommsError, PinError, DelayError>
where
Base: base::Base<CommsError, PinError, DelayError>,
CommsError: Debug + Sync + Send + 'static,
PinError: Debug + Sync + Send + 'static,
DelayError: Debug + Sync + Send + 'static,
{
type Error = Error<CommsError, PinError, DelayError>;
fn start_transmit(&mut self, data: &[u8]) -> Result<(), Self::Error> {
match self.mode {
Mode::LoRa => self.lora_start_transmit(data),
Mode::FskOok => self.fsk_start_transmit(data),
_ => Err(Error::InvalidConfiguration),
}
}
fn check_transmit(&mut self) -> Result<bool, Error<CommsError, PinError, DelayError>> {
match self.mode {
Mode::LoRa => self.lora_check_transmit(),
Mode::FskOok => self.fsk_check_transmit(),
_ => Err(Error::InvalidConfiguration),
}
}
}
impl<Base, CommsError, PinError, DelayError> radio::Receive for Sx127x<Base, CommsError, PinError, DelayError>
where
Base: base::Base<CommsError, PinError, DelayError>,
CommsError: Debug + Sync + Send + 'static,
PinError: Debug + Sync + Send + 'static,
DelayError: Debug + Sync + Send + 'static,
{
type Info = PacketInfo;
type Error = Error<CommsError, PinError, DelayError>;
fn start_receive(&mut self) -> Result<(), Self::Error> {
match self.mode {
Mode::LoRa => self.lora_start_receive(),
Mode::FskOok => self.fsk_start_receive(),
_ => Err(Error::InvalidConfiguration),
}
}
fn check_receive(&mut self, restart: bool) -> Result<bool, Self::Error> {
match self.mode {
Mode::LoRa => self.lora_check_receive(restart),
Mode::FskOok => self.fsk_check_receive(restart),
_ => Err(Error::InvalidConfiguration),
}
}
fn get_received(
&mut self,
info: &mut Self::Info,
data: &mut [u8],
) -> Result<usize, Self::Error> {
match self.mode {
Mode::LoRa => self.lora_get_received(info, data),
Mode::FskOok => self.fsk_get_received(info, data),
_ => Err(Error::InvalidConfiguration),
}
}
}
impl<Base, CommsError, PinError, DelayError> radio::Rssi for Sx127x<Base, CommsError, PinError, DelayError>
where
Base: base::Base<CommsError, PinError, DelayError>,
CommsError: Debug + Sync + Send + 'static,
PinError: Debug + Sync + Send + 'static,
DelayError: Debug + Sync + Send + 'static,
{
type Error = Error<CommsError, PinError, DelayError>;
fn poll_rssi(&mut self) -> Result<i16, Error<CommsError, PinError, DelayError>> {
match self.mode {
Mode::LoRa => self.lora_poll_rssi(),
Mode::FskOok => self.fsk_poll_rssi(),
_ => Err(Error::InvalidConfiguration),
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}