forked from sagneessens/RN2483
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmac.go
771 lines (633 loc) · 20.6 KB
/
mac.go
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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
// The MIT License (MIT)
//
// Copyright © 2017 Sven Agneessens <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package rn2483
import (
"encoding/hex"
"errors"
"fmt"
"strconv"
"strings"
"time"
)
var (
ErrNotJoined = errors.New("Not joined")
ErrInvalidPort = errors.New("Invalid port number")
ErrZeroBytes = errors.New("Trying to send zero bytes")
ErrTimeout = errors.New("Timeout")
ErrInvalidHexData = errors.New("Invalid hex data")
ErrGeneral = errors.New("General error")
ErrMacTx = errors.New("Mac tx error")
ErrMacResume = errors.New("Mac resume error")
ErrMacReset = errors.New("Mac reset error")
ErrMacPause = errors.New("Mac pause error")
ErrInvalidBand = errors.New("Invalid band selected (433 or 868)")
ErrInvalidParameter = errors.New("Invalid parameter")
)
type receiveCallback func(port uint8, data []byte)
// MacReset will automatically reset the software LoRaWAN stack and initilize
// it with the parameters for the selected band.
func MacReset(band uint16) error {
if band != 433 && band != 868 {
WARN.Println("mac reset error: invalid band selected (433 or 868)")
return errors.Join(ErrMacReset, ErrInvalidBand)
}
err := serialWrite(fmt.Sprintf("mac reset %v", band))
if err != nil {
WARN.Println("mac reset error:", err)
return errors.Join(ErrMacReset, err)
}
n, answer := serialRead()
if n == 0 || string(sanitize(answer)) == invalidParameter {
WARN.Println("mac reset error: invalid parameter")
return errors.Join(ErrMacReset, ErrInvalidParameter)
}
//state.macPaused = false
return nil
}
// MacPause will pause the LoRaWAN stack functionality to allow transceiver (radio) configuration.
// The length is the time in milliseconds the stack will be paused, with a maximum of 4294967295
// (max of uint32), is returned as an uint32.
func MacPause() (uint32, error) {
err := serialWrite("mac pause")
if err != nil {
WARN.Println("mac pause error:", err)
return 0, errors.Join(ErrMacPause, err)
}
n, answer := serialRead()
if n == 0 || string(sanitize(answer)) == invalidParameter {
WARN.Println("mac pause error: invalid parameter")
return 0, errors.Join(ErrMacPause, ErrInvalidParameter)
}
value, err := strconv.ParseUint(string(sanitize(answer)), 10, 32)
if err != nil {
WARN.Println("mac pause error:", err)
return 0, errors.Join(ErrMacPause, err)
}
//state.macPaused = true
//state.macPausedEnd = time.Now().Add(time.Duration(value) * time.Millisecond)
return uint32(value), nil
}
// MacResume will resume the LoRaWAN stack functionality, in order to continue normal
// functionality after being paused.
func MacResume() error {
err := serialWrite("mac resume")
if err != nil {
WARN.Println("mac resume error:", err)
return errors.Join(ErrMacResume, err)
}
n, answer := serialRead()
if n == 0 || string(sanitize(answer)) == invalidParameter {
return errors.Join(err, ErrInvalidParameter)
}
//state.macPaused = false
return nil
}
// The length is passed in milliseconds.
//func isMacPaused(length int) bool {
// // An offset of 100 milliseconds is added to ensure we have enough
// // time left over
// d := time.Duration(length)*time.Millisecond + time.Duration(100)
//
// if state.macPaused {
// return time.Now().Add(d).Before(state.macPausedEnd)
// }
//
// return false
//}
// MacJoin will join the configured network with the given mode.
func MacJoin(mode string) bool {
if mode != OTAA && mode != ABP {
WARN.Println("mac join error: invalid mode (OTAA or ABP)")
return false
}
err := serialWrite(fmt.Sprintf("mac join %s", mode))
if err != nil {
WARN.Println("mac join error:", err)
return false
}
n, answer := serialRead()
if n == 0 || string(sanitize(answer)) != "ok" {
WARN.Println("mac join error:", string(sanitize(answer)))
return false
}
tick := time.Tick(time.Second)
timeout := time.After(time.Second * 15)
for {
select {
case <-timeout:
return false
case <-tick:
n, answer = serialRead()
if n != 0 {
if string(sanitize(answer)) != "accepted" {
WARN.Println("mac join error:", string(sanitize(answer)))
return false
}
return true
}
}
}
}
// MacTX will transmit the given data on the given port. The transmission can
// either be confirmed (if the boolean is set), meaning that the server will
// response with an acknowledgement. If no acknowledgement is received, the
// message will be retransmitted by the number indicated by the MacSetRetx
// command. The port number has to be a value in the range of [1,223].
// The receiveCallback function passed is responsible to handle the received
// answer from the server. If no answers are expected, nil can be passed as the
// callback argument.
func MacTx(confirmed bool, port uint8, data []byte, callback receiveCallback) error {
if port < 1 || port > 223 {
WARN.Printf("mac tx error: invalid port number (%v)", port)
return ErrInvalidPort
}
if len(data) == 0 {
WARN.Println("mac tx error: trying to send zero bytes")
return ErrZeroBytes
}
uplinkType := UNCONFIRMED
if confirmed {
uplinkType = CONFIRMED
}
err := serialWrite(fmt.Sprintf("mac tx %s %v %X", uplinkType, port, data))
if err != nil {
WARN.Println("mac tx error:", err)
return err
}
n, answer := serialRead()
if n == 0 || string(sanitize(answer)) != "ok" {
s := string(sanitize(answer))
WARN.Println("mac tx error:", s)
if s == "not_joined" {
return ErrNotJoined
} else {
return errors.Join(ErrMacTx, errors.New(s))
}
}
timeout := time.After(time.Second * 15)
tick := time.Tick(time.Second)
for {
select {
case <-timeout:
WARN.Println("timed out")
return ErrTimeout
case <-tick:
n, answer = serialRead()
s := string(sanitize(answer))
if n != 0 {
if s == "mac_err" || s == "invalid_data_len" {
WARN.Printf("mac tx error: %s", s)
return errors.Join(ErrMacTx, errors.New(s))
} else if s == "not_joined" {
WARN.Printf("mac tx error: %s", s)
return ErrNotJoined
} else if s == "mac_tx_ok" {
return nil
} else if strings.HasPrefix(s, "mac_rx") {
if callback != nil {
params := strings.Split(s, " ")
port, err := strconv.ParseInt(params[1], 10, 8)
if err != nil {
WARN.Printf("mac_rx invalid port: %s", params[1])
return ErrInvalidPort
}
decoded, err := hex.DecodeString(params[2])
if err != nil {
WARN.Printf("mac_rx invalid hex data: %s", params[2])
return nil
}
callback(uint8(port), []byte(decoded))
}
return nil
} else {
return ErrGeneral
}
}
}
}
}
func MacGetStatus() string {
err := serialWrite("mac get status")
if err != nil {
WARN.Println("mac get status error:", err)
return "00000000"
}
n, answer := serialRead()
fmt.Println("Mac status: " + string(sanitize(answer)))
if n != 0 {
return string(sanitize(answer))
}
return "00000000"
}
// MacGetDeviceAddress will return the current end device address of the module.
// The address is represented as a 4-byte hexadecimal number and returned as a string.
// The default value of 00000000 will be returned in case of an error.
func MacGetDeviceAddress() string {
err := serialWrite("mac get devaddr")
if err != nil {
WARN.Println("mac get devaddr error:", err)
return "00000000"
}
n, answer := serialRead()
if n != 0 {
return string(sanitize(answer))
}
return "00000000"
}
// MacSetDeviceAddress will configure the module with a network device address.
// The address is a 4-byte hexadecimal value given as a string.
func MacSetDeviceAddress(address string) error {
if len(address) != 8 {
return errors.New("invalid address length")
}
err := serialWrite(fmt.Sprintf("mac set devaddr %s", address))
if err != nil {
return errors.Join(err, errors.New("could not set device address"))
}
n, answer := serialRead()
if n == 0 || string(sanitize(answer)) == invalidParameter {
return errors.New("could not set device address: invalid parameter")
}
return nil
}
// MacGetDeviceEUI will return the current end device EUI of the module.
// The EUI is represented as a 8-byte hexadecimal number and returned as a string.
// The default value of 0000000000000000 will be returned in case of an error.
func MacGetDeviceEUI() string {
err := serialWrite("mac get deveui")
if err != nil {
WARN.Println("mac get deveui error:", err)
return "0000000000000000"
}
n, answer := serialRead()
if n != 0 {
return string(sanitize(answer))
}
return "0000000000000000"
}
// MacSetDeviceEUI will configure the module with a network device EUI.
// The EUI is a 8-byte hexadecimal value given as a string.
func MacSetDeviceEUI(eui string) error {
if len(eui) != 16 {
return errors.New("invalid eui length")
}
err := serialWrite(fmt.Sprintf("mac set deveui %s", eui))
if err != nil {
return errors.Join(err, errors.New("could not set device eui"))
}
n, answer := serialRead()
if n == 0 || string(sanitize(answer)) == invalidParameter {
return errors.New("could not set device eui: invalid parameter")
}
return nil
}
// MacGetApplicationEUI will return the current configured application EUI.
// The EUI is represented as a 8-byte hexadecimal number and returned as a string.
// The default value of 0000000000000000 will be returned in case of an error.
func MacGetApplicationEUI() string {
err := serialWrite("mac get appeui")
if err != nil {
WARN.Println("mac get appeui error:", err)
return "0000000000000000"
}
n, answer := serialRead()
if n != 0 {
return string(sanitize(answer))
}
return "0000000000000000"
}
// MacSetApplicationEUI will configure the module with a network application EUI.
// The EUI is a 8-byte hexadecimal value given as a string.
func MacSetApplicationEUI(eui string) error {
if len(eui) != 16 {
return errors.New("invalid eui length")
}
err := serialWrite(fmt.Sprintf("mac set appeui %s", eui))
if err != nil {
return errors.Join(err, errors.New("could not set application eui"))
}
n, answer := serialRead()
if n == 0 || string(sanitize(answer)) == invalidParameter {
return errors.New("could not set application eui: invalid parameter")
}
return nil
}
// MacSetNetworkSessionKey will configure the module with a network session key.
// The key is a 16-byte hexadecimal value given as a string.
func MacSetNetworkSessionKey(key string) error {
if len(key) != 32 {
return errors.New("invalid key length")
}
err := serialWrite(fmt.Sprintf("mac set nwkskey %s", key))
if err != nil {
return errors.Join(err, errors.New("could not set network session key"))
}
n, answer := serialRead()
if n == 0 || string(sanitize(answer)) == invalidParameter {
return errors.New("could not set network session key: invalid parameter")
}
return nil
}
// MacSetApplicationSessionKey will configure the module with an application session key.
// The key is a 16-byte hexadecimal value given as a string.
func MacSetApplicationSessionKey(key string) error {
if len(key) != 32 {
return errors.New("invalid key length")
}
err := serialWrite(fmt.Sprintf("mac set appskey %s", key))
if err != nil {
return errors.Join(err, errors.New("could not set application session key"))
}
n, answer := serialRead()
if n == 0 || string(sanitize(answer)) == invalidParameter {
return errors.New("could not set application session key: invalid parameter")
}
return nil
}
// MacSetApplicationKey will configure the module with an application key.
// The key is a 16-byte hexadecimal value given as a string.
func MacSetApplicationKey(key string) error {
if len(key) != 32 {
return errors.New("invalid key length")
}
err := serialWrite(fmt.Sprintf("mac set appkey %s", key))
if err != nil {
return errors.Join(err, errors.New("could not set application key"))
}
n, answer := serialRead()
if n == 0 || string(sanitize(answer)) == invalidParameter {
return errors.New("could not set application key: invalid parameter")
}
return nil
}
// MacGetDataRate will return the current data rate.
// The data rate is a number in the range of [0-5],
// with 0 = SF12BW125 and 5 = SF7BW125.
func MacGetDataRate() uint8 {
err := serialWrite("mac get dr")
if err != nil {
WARN.Println("mac get dr error:", err)
return 0
}
n, answer := serialRead()
if n != 0 {
dr, err := strconv.ParseUint(string(sanitize(answer)), 10, 8)
if err != nil {
WARN.Println("mac get dr uint conversion error:", err)
return 0
}
return uint8(dr)
}
return 0
}
// MacSetDataRate will configure the data rate for the next transmission.
// The data rate has to be in the range of [0-5],
// with 0 = SF12BW125 and 5 = SF7BW125.
func MacSetDataRate(dr uint8) error {
if dr > 5 {
return errors.New("invalid data rate")
}
err := serialWrite(fmt.Sprintf("mac set dr %v", dr))
if err != nil {
return errors.Join(err, errors.New("could not set data rate"))
}
n, answer := serialRead()
if n == 0 || string(sanitize(answer)) == invalidParameter {
return errors.New("could not set data rate: invalid parameter")
}
return nil
}
// MacGetPowerIndex will return the current power index.
// The power index is a number in the range of [0-5],
// with 0 = 20 dBm (if available), 1 = 14 dBm, 2 = 11 dBm,
// 3 = 8 dBm, 4 = 5dBm and 5 = 2 dBm.
func MacGetPowerIndex() uint8 {
err := serialWrite("mac get pwridx")
if err != nil {
WARN.Println("mac get pwridx error:", err)
return 1
}
n, answer := serialRead()
if n != 0 {
pwr, err := strconv.ParseUint(string(sanitize(answer)), 10, 8)
if err != nil {
WARN.Println("mac get pwridx uint conversion error:", err)
return 1
}
return uint8(pwr)
}
return 1
}
// MacSetPowerIndex will configure the power index for the next transmission.
// The index has to be in the range of [1-5] for 868 MHz and [0-5] for 433 MHz.
func MacSetPowerIndex(index uint8) error {
if index > 5 {
return errors.New("invalid power index")
}
err := serialWrite(fmt.Sprintf("mac set pwridx %v", index))
if err != nil {
return errors.Join(err, errors.New("could not set power index"))
}
n, answer := serialRead()
if n == 0 || string(sanitize(answer)) == invalidParameter {
return errors.New("could not set power index: invalid parameter")
}
return nil
}
// MacGetADR will return the state of the adpative data rate mechanism.
func MacGetADR() bool {
err := serialWrite("mac get adr")
if err != nil {
WARN.Println("mac get adr error:", err)
return false
}
n, answer := serialRead()
if n == 0 {
WARN.Println("mac get adr error: no answer")
return false
}
if string(sanitize(answer)) == "on" {
return true
}
return false
}
// MacSetADR will set the adaptive data rate.
func MacSetADR(adr bool) error {
var state = "off"
if adr {
state = "on"
}
err := serialWrite(fmt.Sprintf("mac set adr %s", state))
if err != nil {
return errors.Join(err, errors.New("could not set adaptive data rate"))
}
n, answer := serialRead()
if n == 0 || string(sanitize(answer)) == invalidParameter {
return errors.New("could not set adaptive data rate: invalid parameter")
}
return nil
}
// MacSetLinkCheck will set the time interval for the link check process to be triggered.
func MacSetLinkCheck(interval uint16) error {
err := serialWrite(fmt.Sprintf("mac set linkchk %v", interval))
if err != nil {
return errors.Join(err, errors.New("could not set link check"))
}
n, answer := serialRead()
if n == 0 || string(sanitize(answer)) == invalidParameter {
return errors.New("could not set link check: invalid parameter")
}
return nil
}
//TODO: implement mac get status
// MacGetChannelFrequency will return the frequency on the requested channelID.
// This frequency is returned in Hz.
// The channelID has to be in the range of [0-15].
func MacGetChannelFrequency(channelID uint8) uint32 {
if channelID > 15 {
WARN.Println("mac get ch freq error: invalid channel")
return 0
}
err := serialWrite(fmt.Sprintf("mac get ch freq %v", channelID))
if err != nil {
WARN.Println("mac get ch freq error:", err)
return 0
}
n, answer := serialRead()
if n != 0 {
value, err := strconv.ParseUint(string(sanitize(answer)), 10, 32)
if err != nil {
WARN.Println("mac get ch freq uint conversion error:", err)
return 0
}
return uint32(value)
}
return 0
}
// MacSetChannelFrequency will set the frequency on the given channel id.
// The default channels (0-2) cannot be modified.
// The applicable range for the channel id is [3-15].
// The frequency has to be given in Hz.
func MacSetChannelFrequency(channelID uint8, frequency uint32) error {
if channelID < 3 || channelID > 15 {
return errors.New("invalid channel id")
}
if frequency < 433050000 || (frequency > 434790000 && frequency < 863000000) || frequency > 870000000 {
return errors.New("invalid frequency")
}
err := serialWrite(fmt.Sprintf("mac set ch freq %v %v", channelID, frequency))
if err != nil {
return errors.Join(err, errors.New("could not set channel frequency"))
}
n, answer := serialRead()
if n == 0 || string(sanitize(answer)) == invalidParameter {
return errors.New("could not set channel frequency: invalid parameter")
}
return nil
}
// MacGetChannelDutyCycle will return the duty cycle on the requested channelID.
// The duty cycle will be returned as a percentage.
// The channelID has to be in the range of [0-15].
func MacGetChannelDutyCycle(channelID uint8) float32 {
if channelID > 15 {
WARN.Println("mac get ch dcycle error: invalid channel")
return 0
}
err := serialWrite(fmt.Sprintf("mac get ch dcycle %v", channelID))
if err != nil {
WARN.Println("mac get ch dcycle error:", err)
return 0
}
n, answer := serialRead()
if n != 0 {
value, err := strconv.ParseUint(string(sanitize(answer)), 10, 16)
if err != nil {
WARN.Println("mac get ch dcycle uint conversion error:", err)
return 0
}
return 100 / float32(value+1)
}
return 0
}
// MacSetChannelDutyCycle will set the duty cycle used on the given channel id.
// The applicable range for the channel id is [0-15].
// The duty cycle can be given as a percentage.
func MacSetChannelDutyCycle(channelID uint8, dcycle float32) error {
if channelID > 15 {
return errors.New("invalid channel id")
}
value := uint64((100 / dcycle) - 1)
if value > uint64(^uint16(0)) {
value = uint64(^uint16(0))
}
err := serialWrite(fmt.Sprintf("mac set ch dcycle %v %v", channelID, uint16(value)))
if err != nil {
return errors.Join(err, errors.New("could not set channel duty cycle"))
}
n, answer := serialRead()
if n == 0 || string(sanitize(answer)) == invalidParameter {
return errors.New("could not set channel duty cycle: invalid parameter")
}
return nil
}
// MacGetChannelStatus will return if the given channelID is currently enabled for use.
// The channelID has to be in the range of [0-15].
func MacGetChannelStatus(channelID uint8) bool {
if channelID > 15 {
WARN.Println("mac get ch status error: invalid channel")
return false
}
err := serialWrite(fmt.Sprintf("mac get ch status %v", channelID))
if err != nil {
WARN.Println("mac get ch status error:", err)
return false
}
n, answer := serialRead()
if n == 0 {
WARN.Println("mac get ch status error: no answer")
return false
}
if string(sanitize(answer)) == "on" {
return true
}
return false
}
// MacSetChannelStatus will set the operation on the given channel id.
// The applicable range for the channel id is [0-15].
func MacSetChannelStatus(channelID uint8, status bool) error {
var state = "off"
if status {
state = "on"
}
if channelID > 15 {
return errors.New("invalid channel id")
}
err := serialWrite(fmt.Sprintf("mac set ch dcycle %v %s", channelID, state))
if err != nil {
return errors.Join(err, errors.New("could not set channel status"))
}
n, answer := serialRead()
if n == 0 || string(sanitize(answer)) == invalidParameter {
return errors.New("could not set channel status: invalid parameter")
}
return nil
}