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
// Copyright (c) 2018-2020 Ivaylo Petrov
//
// Licensed under the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.
//
// Author: Ivaylo Petrov <ivajloip@gmail.com>

use super::maccommands::*;

macro_rules! impl_mac_cmd_creator_boilerplate {
    ($type:ident, $cid:expr) => {
        impl Default for $type {
            fn default() -> Self {
                Self {}
            }
        }

        impl $type {
            /// Creates a new instance of the class.
            pub fn new() -> Self {
                Default::default()
            }

            /// Returns the serialized version of the class as bytes.
            pub fn build(&self) -> &[u8] {
                &[$cid]
            }
        }

        impl_mac_cmd_payload!($type);
    };

    ($type:ident, $cid:expr, $len:expr) => {
        impl Default for $type {
            fn default() -> Self {
                let data = [0; $len];
                Self { data }
            }
        }

        impl $type {
            /// Creates a new instance of the class.
            pub fn new() -> Self {
                let mut data = [0; $len];
                data[0] = $cid;
                Self { data: data }
            }

            /// Returns the serialized version of the class as bytes.
            pub fn build(&self) -> &[u8] {
                &self.data[..]
            }
        }

        impl_mac_cmd_payload!($type);
    };
}

macro_rules! impl_mac_cmd_payload {
    ($type:ident) => {
        impl SerializableMacCommand for $type {
            /// Bytes of the SerializableMacCommand without the cid.
            fn payload_bytes(&self) -> &[u8] {
                &self.build()[1..]
            }

            /// The cid of the SerializableMacCommand.
            fn cid(&self) -> u8 {
                self.build()[0]
            }

            /// Length of the SerializableMacCommand without the cid.
            fn payload_len(&self) -> usize {
                self.build().len() - 1
            }
        }
    };
}

/// LinkCheckReqCreator serves for creating LinkCheckReq MacCommand.
///
/// # Examples
///
/// ```
/// let mut creator = lorawan::maccommandcreator::LinkCheckReqCreator::new();
/// let res = creator.build();
/// ```
pub struct LinkCheckReqCreator {}

impl_mac_cmd_creator_boilerplate!(LinkCheckReqCreator, 0x02);

/// LinkCheckAnsCreator serves for creating LinkCheckAns MacCommand.
///
/// # Examples
///
/// ```
/// let mut creator = lorawan::maccommandcreator::LinkCheckAnsCreator::new();
/// let res = creator.set_margin(253).set_gateway_count(254).build();
/// ```
pub struct LinkCheckAnsCreator {
    data: [u8; 3],
}

impl_mac_cmd_creator_boilerplate!(LinkCheckAnsCreator, 0x02, 3);

impl LinkCheckAnsCreator {
    /// Sets the margin of the LinkCheckAns to the provided value.
    ///
    /// # Argument
    ///
    /// * margin - margin  in  dB. The value is relative to the demodulation floor. The value 255
    /// is reserved.
    pub fn set_margin(&mut self, margin: u8) -> &mut Self {
        self.data[1] = margin;

        self
    }

    /// Sets the gateway count of the LinkCheckAns to the provided value.
    ///
    /// # Argument
    ///
    /// * gateway_count - the number of gateways that received the LinkCheckReq.
    pub fn set_gateway_count(&mut self, gw_cnt: u8) -> &mut Self {
        self.data[2] = gw_cnt;

        self
    }
}

/// LinkADRReqCreator serves for creating LinkADRReq MacCommand.
///
/// # Examples
///
/// ```
/// let mut creator = lorawan::maccommandcreator::LinkADRReqCreator::new();
/// let channel_mask_bytes = [0xc7, 0x0b];
/// let res = creator
///     .set_data_rate(0x05)
///     .unwrap()
///     .set_tx_power(0x03)
///     .unwrap()
///     .set_channel_mask(channel_mask_bytes)
///     .set_redundancy(0x37)
///     .build();
/// ```
pub struct LinkADRReqCreator {
    data: [u8; 5],
}

impl_mac_cmd_creator_boilerplate!(LinkADRReqCreator, 0x03, 5);

impl LinkADRReqCreator {
    /// Sets the data rate of the LinkADRReq to the provided value.
    ///
    /// # Argument
    ///
    /// * data_rate - data rate index of the ADR request. The value must be between 0 and 15.
    pub fn set_data_rate(&mut self, data_rate: u8) -> Result<&mut Self, &str> {
        if data_rate > 0x0f {
            return Err("data_rate out of range");
        }
        self.data[1] &= 0x0f;
        self.data[1] |= data_rate << 4;

        Ok(self)
    }

    /// Sets the tx power of the LinkADRReq to the provided value.
    ///
    /// # Argument
    ///
    /// * tx_power - TX power index. The value must be between 0 and 15.
    pub fn set_tx_power(&mut self, tx_power: u8) -> Result<&mut Self, &str> {
        if tx_power > 0x0f {
            return Err("tx_power out of range");
        }
        self.data[1] &= 0xf0;
        self.data[1] |= tx_power & 0x0f;

        Ok(self)
    }

    /// Sets the channel mask of the LinkADRReq to the provided value.
    ///
    /// # Argument
    ///
    /// * channel_mask - instance of maccommands::ChannelMask or anything that can be converted
    /// into it.
    pub fn set_channel_mask<T: Into<ChannelMask>>(
        &mut self,
        channel_mask: T,
    ) -> &mut Self {
        let converted = channel_mask.into();
        self.data[2] = converted.as_ref()[0];
        self.data[3] = converted.as_ref()[1];

        self
    }

    /// Sets the redundancy of the LinkADRReq to the provided value.
    ///
    /// # Argument
    ///
    /// * redundancy - instance of maccommands::Redundancy or anything that can be converted
    /// into it.
    pub fn set_redundancy<T: Into<Redundancy>>(&mut self, redundancy: T) -> &mut Self {
        let converted = redundancy.into();
        self.data[4] = converted.raw_value();

        self
    }
}

/// LinkADRAnsCreator serves for creating LinkADRAns MacCommand.
///
/// # Examples
///
/// ```
/// let mut creator = lorawan::maccommandcreator::LinkADRAnsCreator::new();
/// let res = creator
///     .set_channel_mask_ack(true)
///     .set_data_rate_ack(true)
///     .set_tx_power_ack(true)
///     .build();
/// ```
pub struct LinkADRAnsCreator {
    data: [u8; 2],
}

impl_mac_cmd_creator_boilerplate!(LinkADRAnsCreator, 0x03, 2);

impl LinkADRAnsCreator {
    /// Sets the channel mask acknowledgement of the LinkADRAns to the provided value.
    ///
    /// # Argument
    ///
    /// * ack - true meaning that the channel mask was acceptable or false otherwise.
    pub fn set_channel_mask_ack(&mut self, ack: bool) -> &mut Self {
        self.data[1] &= 0xfe;
        self.data[1] |= ack as u8;

        self
    }

    /// Sets the data rate acknowledgement of the LinkADRAns to the provided value.
    ///
    /// # Argument
    ///
    /// * ack - true meaning that the data rate was acceptable or false otherwise.
    pub fn set_data_rate_ack(&mut self, ack: bool) -> &mut Self {
        self.data[1] &= 0xfd;
        self.data[1] |= (ack as u8) << 1;

        self
    }

    /// Sets the tx power acknowledgement of the LinkADRAns to the provided value.
    ///
    /// # Argument
    ///
    /// * ack - true meaning that the tx power was acceptable or false otherwise.
    pub fn set_tx_power_ack(&mut self, ack: bool) -> &mut Self {
        self.data[1] &= 0xfb;
        self.data[1] |= (ack as u8) << 2;

        self
    }
}

/// DutyCycleReqCreator serves for creating DutyCycleReq MacCommand.
///
/// # Examples
///
/// ```
/// let mut creator = lorawan::maccommandcreator::DutyCycleReqCreator::new();
/// let res = creator.set_max_duty_cycle(0x0f).unwrap().build();
/// ```
pub struct DutyCycleReqCreator {
    data: [u8; 2],
}

impl_mac_cmd_creator_boilerplate!(DutyCycleReqCreator, 0x04, 2);

impl DutyCycleReqCreator {
    /// Sets the max duty cycle of the DutyCycleReq to the provided value.
    ///
    /// # Argument
    ///
    /// * max_duty_cycle - the value used to determine the aggregated duty cycle using the formula
    /// `1 / (2 ** max_duty_cycle)`.
    pub fn set_max_duty_cycle(&mut self, max_duty_cycle: u8) -> Result<&mut Self, &str> {
        self.data[1] = max_duty_cycle;

        Ok(self)
    }
}

/// DutyCycleAnsCreator serves for creating DutyCycleAns MacCommand.
///
/// # Examples
///
/// ```
/// let creator = lorawan::maccommandcreator::DutyCycleAnsCreator::new();
/// let res = creator.build();
/// ```
pub struct DutyCycleAnsCreator {}

impl_mac_cmd_creator_boilerplate!(DutyCycleAnsCreator, 0x04);

/// RXParamSetupReqCreator serves for creating RXParamSetupReq MacCommand.
///
/// # Examples
///
/// ```
/// let mut creator = lorawan::maccommandcreator::RXParamSetupReqCreator::new();
/// let res = creator
///     .set_dl_settings(0xcd)
///     .set_frequency(&[0x12, 0x34, 0x56])
///     .build();
/// ```
pub struct RXParamSetupReqCreator {
    data: [u8; 5],
}

impl_mac_cmd_creator_boilerplate!(RXParamSetupReqCreator, 0x05, 5);

impl RXParamSetupReqCreator {
    /// Sets the DLSettings of the RXParamSetupReq to the provided value.
    ///
    /// # Argument
    ///
    /// * dl_settings - instance of maccommands::DLSettings or anything that can be converted
    /// into it.
    pub fn set_dl_settings<T: Into<DLSettings>>(
        &mut self,
        dl_settings: T,
    ) -> &mut Self {
        let converted = dl_settings.into();
        self.data[1] = converted.raw_value();

        self
    }

    /// Sets the frequency of the RXParamSetupReq to the provided value.
    ///
    /// # Argument
    ///
    /// * frequency - instance of maccommands::Frequency or anything that can be converted
    /// into it.
    pub fn set_frequency<'a, T: Into<Frequency<'a>>>(
        &mut self,
        frequency: T,
    ) -> &mut Self {
        let converted = frequency.into();
        self.data[2..5].copy_from_slice(converted.as_ref());

        self
    }
}

/// RXParamSetupAnsCreator serves for creating RXParamSetupAns MacCommand.
///
/// # Examples
///
/// ```
/// let mut creator = lorawan::maccommandcreator::RXParamSetupAnsCreator::new();
/// let res = creator
///     .set_channel_ack(true)
///     .set_rx2_data_rate_ack(true)
///     .set_rx1_data_rate_offset_ack(true)
///     .build();
/// ```
pub struct RXParamSetupAnsCreator {
    data: [u8; 2],
}

impl_mac_cmd_creator_boilerplate!(RXParamSetupAnsCreator, 0x05, 2);

impl RXParamSetupAnsCreator {
    /// Sets the channel acknowledgement of the RXParamSetupAns to the provided value.
    ///
    /// # Argument
    ///
    /// * ack - true meaning that the channel was acceptable or false otherwise.
    pub fn set_channel_ack(&mut self, ack: bool) -> &mut Self {
        self.data[1] &= 0xfe;
        self.data[1] |= ack as u8;

        self
    }

    /// Sets the rx2 data rate acknowledgement of the RXParamSetupAns to the provided value.
    ///
    /// # Argument
    ///
    /// * ack - true meaning that the rx2 data rate was acceptable or false otherwise.
    pub fn set_rx2_data_rate_ack(&mut self, ack: bool) -> &mut Self {
        self.data[1] &= 0xfd;
        self.data[1] |= (ack as u8) << 1;

        self
    }

    /// Sets the rx1 data rate offset acknowledgement of the RXParamSetupAns to the provided value.
    ///
    /// # Argument
    ///
    /// * ack - true meaning that the rx1 data rate offset was acceptable or false otherwise.
    pub fn set_rx1_data_rate_offset_ack(&mut self, ack: bool) -> &mut Self {
        self.data[1] &= 0xfb;
        self.data[1] |= (ack as u8) << 2;

        self
    }
}

/// DevStatusReqCreator serves for creating DevStatusReq MacCommand.
///
/// # Examples
///
/// ```
/// let creator = lorawan::maccommandcreator::DevStatusReqCreator::new();
/// let res = creator.build();
/// ```
pub struct DevStatusReqCreator {}

impl_mac_cmd_creator_boilerplate!(DevStatusReqCreator, 0x06);

/// DevStatusAnsCreator serves for creating DevStatusAns MacCommand.
///
/// # Examples
///
/// ```
/// let mut creator = lorawan::maccommandcreator::DevStatusAnsCreator::new();
/// let res = creator.set_battery(0xfe).set_margin(-32).unwrap().build();
/// ```
pub struct DevStatusAnsCreator {
    data: [u8; 3],
}

impl_mac_cmd_creator_boilerplate!(DevStatusAnsCreator, 0x06, 3);

impl DevStatusAnsCreator {
    /// Sets the battery of the DevStatusAns to the provided value.
    ///
    /// # Argument
    ///
    /// * battery - the value to be used as the battery level. 0 means external enery source,
    /// 1 and 254 are the smallest and biggest values of normal battery reading, while 255
    /// indicates that the device failed to measure its battery level.
    pub fn set_battery(&mut self, battery: u8) -> &mut Self {
        self.data[1] = battery;

        self
    }

    /// Sets the margin of the DevStatusAns to the provided value.
    ///
    /// # Argument
    ///
    /// * margin - the value to be used as margin.
    pub fn set_margin(&mut self, margin: i8) -> Result<&mut Self, &str> {
        if margin < -32 || margin > 31 {
            return Err("margin out of range");
        }
        self.data[2] = ((margin << 2) as u8) >> 2;

        Ok(self)
    }
}

/// NewChannelReqCreator serves for creating NewChannelReq MacCommand.
///
/// # Examples
///
/// ```
/// let mut creator = lorawan::maccommandcreator::NewChannelReqCreator::new();
/// let res = creator
///     .set_channel_index(0x0f)
///     .set_frequency(&[0x12, 0x34, 0x56])
///     .set_data_rate_range(0x53)
///     .build();
/// ```
pub struct NewChannelReqCreator {
    data: [u8; 6],
}

impl_mac_cmd_creator_boilerplate!(NewChannelReqCreator, 0x07, 6);

impl NewChannelReqCreator {
    /// Sets the channel index of the NewChannelReq to the provided value.
    ///
    /// # Argument
    ///
    /// * channel_index - the value to be used as channel_index.
    pub fn set_channel_index(&mut self, channel_index: u8) -> &mut Self {
        self.data[1] = channel_index;

        self
    }

    /// Sets the frequency of the NewChannelReq to the provided value.
    ///
    /// # Argument
    ///
    /// * frequency - instance of maccommands::Frequency or anything that can be converted
    /// into it.
    pub fn set_frequency<'a, T: Into<Frequency<'a>>>(
        &mut self,
        frequency: T,
    ) -> &mut Self {
        let converted = frequency.into();
        self.data[2..5].copy_from_slice(converted.as_ref());

        self
    }

    /// Sets the data rate range of the NewChannelReq to the provided value.
    ///
    /// # Argument
    ///
    /// * data_rate_range - instance of maccommands::DataRateRange or anything that can be converted
    /// into it.
    pub fn set_data_rate_range<T: Into<DataRateRange>>(
        &mut self,
        data_rate_range: T,
    ) -> &mut Self {
        self.data[5] = data_rate_range.into().raw_value();

        self
    }
}

/// NewChannelAnsCreator serves for creating NewChannelAns MacCommand.
///
/// # Examples
///
/// ```
/// let mut creator = lorawan::maccommandcreator::NewChannelAnsCreator::new();
/// let res = creator
///     .set_channel_frequency_ack(true)
///     .set_data_rate_range_ack(true)
///     .build();
/// ```
pub struct NewChannelAnsCreator {
    data: [u8; 2],
}

impl_mac_cmd_creator_boilerplate!(NewChannelAnsCreator, 0x07, 2);

impl NewChannelAnsCreator {
    /// Sets the channel frequency acknowledgement of the NewChannelAns to the provided value.
    ///
    /// # Argument
    ///
    /// * ack - true meaning that the channel frequency was acceptable or false otherwise.
    pub fn set_channel_frequency_ack(&mut self, ack: bool) -> &mut Self {
        self.data[1] &= 0xfe;
        self.data[1] |= ack as u8;

        self
    }

    /// Sets the data rate range acknowledgement of the NewChannelAns to the provided value.
    ///
    /// # Argument
    ///
    /// * ack - true meaning that the data rate range was acceptable or false otherwise.
    pub fn set_data_rate_range_ack(&mut self, ack: bool) -> &mut Self {
        self.data[1] &= 0xfd;
        self.data[1] |= (ack as u8) << 1;

        self
    }
}

/// RXTimingSetupReqCreator serves for creating RXTimingSetupReq MacCommand.
///
/// # Examples
///
/// ```
/// let mut creator = lorawan::maccommandcreator::RXTimingSetupReqCreator::new();
/// let res = creator.set_delay(0x0f).unwrap().build();
/// ```
pub struct RXTimingSetupReqCreator {
    data: [u8; 2],
}

impl_mac_cmd_creator_boilerplate!(RXTimingSetupReqCreator, 0x08, 2);

impl RXTimingSetupReqCreator {
    /// Sets the delay of the RXTimingSetupReq to the provided value.
    ///
    /// # Argument
    ///
    /// * delay - the value to be used as delay.
    pub fn set_delay(&mut self, delay: u8) -> Result<&mut Self, &str> {
        if delay > 0x0f {
            return Err("delay out of range");
        }
        self.data[1] &= 0xf0;
        self.data[1] |= delay;

        Ok(self)
    }
}

/// RXTimingSetupAnsCreator serves for creating RXTimingSetupAns MacCommand.
///
/// # Examples
///
/// ```
/// let creator = lorawan::maccommandcreator::RXTimingSetupAnsCreator::new();
/// let res = creator.build();
/// ```
pub struct RXTimingSetupAnsCreator {}

impl_mac_cmd_creator_boilerplate!(RXTimingSetupAnsCreator, 0x08);

pub fn build_mac_commands<'a, 'b, 'c, T: AsMut<[u8]>>(
        cmds: &'a [&'b dyn SerializableMacCommand],
        mut out: T) -> Result<usize, &'c str> {
    let res = out.as_mut();
    if mac_commands_len(cmds) > res.len() {
        return Err("failed to serialize mac commands in provided buffer: too small");
    }
    let mut i = 0;
    for mc in cmds {
        res[i] = mc.cid();
        let l = mc.payload_len();
        res[i + 1..i+l + 1].copy_from_slice(mc.payload_bytes());
        i += l + 1;
    }
    Ok(i)
}