-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpacketradio.py
1455 lines (1044 loc) · 52 KB
/
packetradio.py
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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""packetradio, module for use with the RFM69HCW packet radio
created Dec 19, 2016 OM
work in progress - Mar 21, 2018
work in progress - Jan 18, 2020"""
"""
Copyright 2017, 2018, 2019, 2020 Owain Martin
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import time, spidev, sys, threading
import RPi.GPIO as IO
class Radio:
def __init__(self, spi_port, spi_cs):
"""__init__, initialize radio object, setting GPIO pins"""
# spi setup
self.spi=spidev.SpiDev()
self.spi.open(spi_port,spi_cs)
self.spi.max_speed_hz = 4000000
# set register list dictionary
self.registerList=[]
# need to add in any registers I didn't deal with.....
self.registerList.append({'name' : 'RegOpMode', 'address' : 0x01, 'value' : 0x04})
self.registerList.append({'name' : 'RegDataModul', 'address' : 0x02, 'value' : 0x00})
self.registerList.append({'name' : 'RegBitRateMsb', 'address' : 0x03, 'value' : 0x1A})
self.registerList.append({'name' : 'RegBitRateLsb', 'address' : 0x04, 'value' : 0x0B})
self.registerList.append({'name' : 'RegFdevMsb', 'address' : 0x05, 'value' : 0x00})
self.registerList.append({'name' : 'RegFdevLsb', 'address' : 0x06, 'value' : 0x62})
self.registerList.append({'name' : 'RegFrfMsb', 'address' : 0x07, 'value' : 0x6E})
self.registerList.append({'name' : 'RegFrfMid', 'address' : 0x08, 'value' : 0x10})
self.registerList.append({'name' : 'RegFrfLsb', 'address' : 0x09, 'value' : 0x00})
self.registerList.append({'name' : 'RegAfcCtrl', 'address' : 0x0B, 'value' : 0x00})
self.registerList.append({'name' : 'RegPaLevel', 'address' : 0x11, 'value' : 0x52})
self.registerList.append({'name' : 'RegPaRamp', 'address' : 0x12, 'value' : 0x09})
self.registerList.append({'name' : 'RegOcp', 'address' : 0x13, 'value' : 0x1A})
self.registerList.append({'name' : 'RegLna', 'address' : 0x18, 'value' : 0x08})
self.registerList.append({'name' : 'RegRxBw', 'address' : 0x19, 'value' : 0x55})
self.registerList.append({'name' : 'RegAfcBw', 'address' : 0x1A, 'value' : 0x55})
self.registerList.append({'name' : 'RegAfcFei', 'address' : 0x1E, 'value' : 0x14})
self.registerList.append({'name' : 'RegDioMapping1', 'address' : 0x25, 'value' : 0x40})
self.registerList.append({'name' : 'RegDioMapping2', 'address' : 0x26, 'value' : 0x07})
self.registerList.append({'name' : 'RegRssiThresh', 'address' : 0x29, 'value' : 0x8C})
self.registerList.append({'name' : 'RegRxTimeout1', 'address' : 0x2A, 'value' : 0x00})
self.registerList.append({'name' : 'RegRxTimeout2', 'address' : 0x2B, 'value' : 0x00})
self.registerList.append({'name' : 'RegPreambleMsb', 'address' : 0x2C, 'value' : 0x00})
self.registerList.append({'name' : 'RegPreambleLsb', 'address' : 0x2D, 'value' : 0x02})
self.registerList.append({'name' : 'RegSyncConfig', 'address' : 0x2E, 'value' : 0x92})
self.registerList.append({'name' : 'RegSyncValue1', 'address' : 0x2F, 'value' : 0xE4})
self.registerList.append({'name' : 'RegSyncValue2', 'address' : 0x30, 'value' : 0x7C})
self.registerList.append({'name' : 'RegSyncValue3', 'address' : 0x31, 'value' : 0xB2})
self.registerList.append({'name' : 'RegSyncValue4', 'address' : 0x32, 'value' : 0x00})
self.registerList.append({'name' : 'RegSyncValue5', 'address' : 0x33, 'value' : 0x00})
self.registerList.append({'name' : 'RegSyncValue6', 'address' : 0x34, 'value' : 0x00})
self.registerList.append({'name' : 'RegSyncValue7', 'address' : 0x35, 'value' : 0x00})
self.registerList.append({'name' : 'RegSyncValue8', 'address' : 0x36, 'value' : 0x00})
self.registerList.append({'name' : 'RegPacketConfig1', 'address' : 0x37, 'value' : 0x14})
self.registerList.append({'name' : 'RegPayloadLength', 'address' : 0x38, 'value' : 0x40})
self.registerList.append({'name' : 'RegFifoThresh', 'address' : 0x3C, 'value' : 0x80})
self.registerList.append({'name' : 'RegPacketConfig2', 'address' : 0x3D, 'value' : 0x03})
self.registerList.append({'name' : 'RegTestPa1', 'address' : 0x5A, 'value' : 0x55})
self.registerList.append({'name' : 'RegTestPa2', 'address' : 0x5C, 'value' : 0x70})
self.registerList.append({'name' : 'RegTestDagc', 'address' : 0x6F, 'value' : 0x30})
self.registerList.append({'name' : 'RegTestAfc', 'address' : 0x71, 'value' : 0x00})
# Node and Broadcast Address registers
self.registerList.append({'name' : 'RegNodeAdrs', 'address' : 0x39, 'value' : 0x05})
self.registerList.append({'name' : 'RegBroadcastAdrs', 'address' : 0x3A, 'value' : 0x07})
# AES Encryption registers
self.registerList.append({'name' : 'RegAESKey1', 'address' : 0x3E, 'value' : 0x51})
self.registerList.append({'name' : 'RegAESKey2', 'address' : 0x3F, 'value' : 0x2C})
self.registerList.append({'name' : 'RegAESKey3', 'address' : 0x40, 'value' : 0xA4})
self.registerList.append({'name' : 'RegAESKey4', 'address' : 0x41, 'value' : 0xA7})
self.registerList.append({'name' : 'RegAESKey5', 'address' : 0x42, 'value' : 0xB4})
self.registerList.append({'name' : 'RegAESKey6', 'address' : 0x43, 'value' : 0xD4})
self.registerList.append({'name' : 'RegAESKey7', 'address' : 0x44, 'value' : 0xA4})
self.registerList.append({'name' : 'RegAESKey8', 'address' : 0x45, 'value' : 0xAE})
self.registerList.append({'name' : 'RegAESKey9', 'address' : 0x46, 'value' : 0xA4})
self.registerList.append({'name' : 'RegAESKey10', 'address' : 0x47, 'value' : 0xF4})
self.registerList.append({'name' : 'RegAESKey11', 'address' : 0x48, 'value' : 0xA3})
self.registerList.append({'name' : 'RegAESKey12', 'address' : 0x49, 'value' : 0xD4})
self.registerList.append({'name' : 'RegAESKey13', 'address' : 0x4A, 'value' : 0xA6})
self.registerList.append({'name' : 'RegAESKey14', 'address' : 0x4B, 'value' : 0x44})
self.registerList.append({'name' : 'RegAESKey15', 'address' : 0x4C, 'value' : 0x72})
self.registerList.append({'name' : 'RegAESKey16', 'address' : 0x4D, 'value' : 0x29})
for reg in self.registerList:
self.single_access_write(reg['address'], reg['value'])
time.sleep(0.01) # time delay required or freq doesn't set correctly
# for testing print register contents
"""for reg in self.registerList:
print(hex(reg['address']),' ',hex(self.single_access_read(reg['address'])))"""
self.temperatureOffset = 0
self.receiveData=[] # list to place received data
self.receiveTimeout = 0 # timeout value for the receiver
self.intPin = 0 # interrupt pin used
self.sendAck = 0 # ack pattern for when returning an acknowledgment
self.receiveAck = 0 # ack pattern for when asking for an acknowledgment back
self.packetFormat = 'fixed' # packet format, fixed, variable or unlimited
return
#----------------- module interal use functions ---------------------
def single_access_write(self, reg=0x01, regValue=0x0):
"""single_access_write, function to write to a single data register
of the RFM69HCW
Default register to write to is RegOpMode"""
dataTransfer=self.spi.xfer2([(1<<7)+reg,regValue])
return
def single_access_read(self, reg=0x00):
"""single_access_read, function to read a single data register
of the RFM69HCW
Default register to read is fifo"""
dataTransfer=self.spi.xfer2([(0<<7)+reg,0])
return dataTransfer[1]
def read_all_registers(self):
"""read_all_registers, function to read all the registers"""
for register in range(0,80):
print(hex(register),hex(self.single_access_read(register)))
for reg in self.registerList:
print(reg['name'],hex(reg['value']))
return
def variable_length_write(self, reg=0x0, length=1, regValues=[]):
"""variable_length_write, function to write multiple consecutive
bytes of data to the radio on a single spi transaction"""
# do I need the length variable for anything!!!???
writeData=[(1<<7)+reg]
writeData.extend(regValues)
dataTransfer=self.spi.xfer2(writeData)
return
def fifo_write(self, fifoData, addressOn=False, address=0, fromAddress=0, ack=False, ackPattern=0, packetLength=64):
"""fifo_write, function to write data to the radio fifo register,
this will be the data that gets transmitted by the radio
fifoData contains a string that will be converted to a bytearray for transmitting
packetLength is the packet length to be transmitted"""
if type(fifoData) == type('a string'):
fifoData=bytearray(fifoData, encoding = "utf-8")
if ack == True:
try:
ackPattern = int(ackPattern)
fifoData.insert(0,ackPattern) # acknowledge Pattern
except:
for i in range(len(ackPattern)-1,-1,-1):
#fifoData.insert(0,ackPattern[i]) # does not work with Python3 - acknowledge Pattern
fifoData = ackPattern.encode('UTF-8') + fifoData # acknowledge Pattern
if fromAddress != 0:
fifoData.insert(0,fromAddress) # from address byte
if addressOn==True:
fifoData.insert(0,address) # address byte
if self.packetFormat == 'variable':
lengthByte = len(fifoData)
fifoData.insert(0,lengthByte) # length byte
# check fifoData length, if less than packetLength, add spaces for padding
# until fifoData length is equal to packetLength
if self.packetFormat == 'fixed':
if len(fifoData)<packetLength:
for i in range(len(fifoData),packetLength):
#fifoData.append(' ') # does not work with Python3
fifoData = fifoData + ' '.encode('UTF-8')
# check fifoData length, if greater than packetLength, remove excess data
# until fifoData length is equal to packetLength
if len(fifoData)>packetLength:
fifoData=fifoData[0:packetLength]
# write data to fifo register
self.variable_length_write(0x0,len(fifoData),fifoData) #(0x0,packetLength,fifoData)
return
def fifo_read(self):
"""fifo_read, function to read data from the radio fifo register,
this will be the data that was received by the radio"""
fifoData=bytearray()
# check FifoNotEmpty flag in RegIrqFlags2 0x28
# read data until fifo is empty
while (self.single_access_read(0x28) & 0b01000000)==64:
fifoData.append(self.single_access_read())
return fifoData
def transmit_packet(self):
"""transmit_packet, function to transmit a single packet of data that
has been preloaded into fifo and put the radio into standby mode upon
completion"""
# put radio into transmit mode
self.set_operating_mode('transmit')
#self.single_access_write(0x01,0x0C) # 0b00001100 - transmit mode
# check that the packet has been sent
count=0
while (self.single_access_read(0x28) & 0b00001000)!=8:
count+=1
if count == 100:
break
time.sleep(0.01) # was 0.025
# put radio back into standby mode
self.set_operating_mode('standby')
#self.single_access_write(0x01,0x04) # 0b0000100 - standby mode
return
def send_ack(self,addr):
"""send_ack, function to send back an acknowledgement"""
# put radio into standby mode
self.set_operating_mode('standby')
# get fromAddress (i.e. radio nodeAddress) from register list
for reg in self.registerList:
if reg['name'] == 'RegNodeAdrs':
fromAddr =reg['value']
break
# transmit ACK
self.transmit('ACK ACK ACK ACK ACK',addressOn=True, toAddress=addr,fromAddress=fromAddr,
ack=True, ackPattern=self.sendAck, packetLength=64)
# put radio back into receive mode
self.set_operating_mode('receive')
return
def receive_ack(self,toAddress,intType = 'hw'):
"""receive_ack, function to check for an acknowledgement
back, requires hw interrupt"""
success = False
intPin = self.intPin
def check_ack(data):
"""check_address, function to check the ack is from the correct
address and check the ack is the correct value"""
if self.packetFormat == 'fixed':
if len(data)<3:
return False
sendAckByte = data[2]
toAddressByte = data[1]
else: # packetFormat = 'variable'
if len(data)<4:
return False
sendAckByte = data[3]
toAddressByte = data[2]
if sendAckByte == self.sendAck and toAddressByte == toAddress:
return True
else:
return False
# put radio into receive mode
self.set_operating_mode('receive')
if self.packetFormat == 'fixed':
hwTimeout = 500
swTimeout = 0.5
else:
hwTimeout = 2000
swTimeout = 2
if intType == 'hw': # hardware interrupt section
channel = IO.wait_for_edge(intPin,IO.RISING, timeout=hwTimeout) # have got 200 working as well
if channel is not None:
ack = self.fifo_read()
if check_ack(ack):
success = True
else: # software interrupt section
timerStart = time.time()
while time.time()<=(timerStart+swTimeout) and success == False:
# check for received data via payload ready flag
while (self.single_access_read(0x28) & 0b00000100)==4:
ack = self.fifo_read()
if check_ack(ack):
success = True
break
time.sleep(0.01)
# put radio back into standby mode
self.set_operating_mode('standby')
return success
#----------- user transmit/ receive and auxillary functions ----------------
def transmit_with_ack(self, txData,toAddress=0, intType = 'hw',retry=0, packetLength=64):
"""transmit_with_ack, function to transmit data and retry if no acknowledgement
is receive in return for each packet sent"""
success = 0 # variable to keep track of the number of packets successfully sent
failed = 0 # variable to keep track of the number of packets that failed to send
addressOn=True
# look up fromAddress
for reg in self.registerList:
if reg['name'] == 'RegNodeAdrs':
fromAddress =reg['value']
break
# send message, wait for acknowledgement and resend 'retry'
# number of times if required
for message in txData:
trys = 0
messageLength = len(message)
while trys <=retry:
self.transmit(message,addressOn, toAddress, fromAddress,ack=True,
ackPattern=self.receiveAck, packetLength=packetLength)
ackSuccess = self.receive_ack(toAddress, intType)
if ackSuccess == True:
success+=1
break
else:
trys+=1
if len(message) > messageLength:
message = message[(len(message)-messageLength):] # not sure why message changes but it comes back with from/to addresses added
else:
failed+=1
return success, failed
def transmit(self, txData1, addressOn=False, toAddress=0,fromAddress=None, ack=False, ackPattern=0, packetLength=64):
"""transmit, user function to transmit data """
if fromAddress == None:
# look up fromAddress
for reg in self.registerList:
if reg['name'] == 'RegNodeAdrs':
fromAddress =reg['value']
break
self.fifo_write(txData1, addressOn, toAddress, fromAddress, ack, ackPattern, packetLength)
self.transmit_packet()
return
def receive(self,timeout=999, background=False):
"""receive, user function to put the radio into receive
mode"""
# set timeout value, a value of -1 will let the receiver run
# indefinately
self.receiveTimeout=timeout
def receive_thread():
"""receive_thread, internal function for putting the radio into receive mode, this
can be threaded to move the receive function into the background"""
# put radio into receive mode
self.set_operating_mode('receive')
#self.single_access_write(0x01,0x10) # 0b00010000 - receive mode
timerStart=time.time()
while time.time()<=(timerStart+self.receiveTimeout) or self.receiveTimeout == -1:
# check for received data via payload ready flag
while (self.single_access_read(0x28) & 0b00000100)==4:
self.receiveData.append(self.fifo_read())
time.sleep(0.1)
# put radio back into standby mode
self.set_operating_mode('standby')
#self.single_access_write(0x01,0x04) # 0b0000100 - standby mode
return self.receiveData
# check whether or not the receive function is to be put into the background
# (threaded) or stay in the foreground (inline)
if background == True:
receiveLoop=threading.Thread(name='receive_thread',target=receive_thread)
receiveLoop.start()
return
else:
receive_thread()
return self.receiveData
def receive_hw_int(self):
"""receive_hw_int, function to put the radio into receive mode,
waiting for a hardware interrupt to proceed. Function will exit on
timer expiring - self.receiveTimeout sets timer"""
timeStart=time.time()
# put radio into receive mode
self.set_operating_mode('receive')
# add interrupt event detect and check for event
# should interrupt on payload ready
intPin = self.intPin
IO.add_event_detect(intPin,IO.RISING)
while (timeStart+self.receiveTimeout)>time.time() or self.receiveTimeout == -1:
if IO.event_detected(intPin):
IO.remove_event_detect(intPin)
data = self.fifo_read()
if len(data)>3: # check to ensure data is at least 3 bytes long
self.receiveData.append(data)
# insert call back function here when I get to it
if self.packetFormat == 'fixed':
if int(data[2]) == self.receiveAck: # send ACK back if ACK request received
self.send_ack(data[1])
else: # packet format = 'variable'
if int(data[3]) == self.receiveAck: # send ACK back if ACK request received
self.send_ack(data[2])
IO.add_event_detect(intPin,IO.RISING)
else:
#time.sleep(0.001)
time.sleep(0.01)
# put radio back into standby mode and remove interrupt event detect
self.set_operating_mode('standby')
IO.remove_event_detect(intPin)
return
def receive_sw_int(self):
"""receive_sw_int, function to put the radio into receive mode,
waiting for a softwaree interrupt to proceed. Function will exit on
timer expiring - self.receiveTimeout sets timer"""
timeStart=time.time()
# put radio into receive mode
self.set_operating_mode('receive')
# check for software interrupt event
# should interrupt on payload ready
intPin = self.intPin
while (timeStart+self.receiveTimeout)>time.time() or self.receiveTimeout == -1:
# check for received data via payload ready flag
while (self.single_access_read(0x28) & 0b00000100)==4:
data = self.fifo_read()
if len(data)>3: # check to ensure data is at least 3 bytes long
self.receiveData.append(data)
# insert call back function here when I get to it
if self.packetFormat == 'fixed':
if int(data[2]) == self.receiveAck: # send ACK back if ACK request received
self.send_ack(data[1])
else: # packet format = 'variable'
if int(data[3]) == self.receiveAck: # send ACK back if ACK request received
self.send_ack(data[2])
#time.sleep(0.001)
time.sleep(0.01)
self.set_operating_mode('standby')
return
def receive_timeout(self, time=0):
"""receive_timeout, function to set the radio objects receiveTimeout variable"""
self.receiveTimeout = int(time)
return
def last_rssi(self):
"""last_rssi, user function to get the last rssi value
mesaured by the radio receiver"""
lastRssi=-self.single_access_read(0x24)/2
return lastRssi
def temperature(self):
"""temperature, user function to get the temperature reading from the
radio's temperature sensor
registers 0x4E and 0x4F relate to the temperature sensor"""
# radio has to be in either Stand by or freq synth mode to take temperature
writeData=0b1001 # bit sequence required to start taking temp reading
self.single_access_write(reg=0x4E, regValue=writeData)
while self.single_access_read(reg=0x4E)==5: # 5 = 0b101
pass
tempSensorValue=self.single_access_read(reg=0x4F)
# using tempSensorValue of 150 equaling 20 degrees
# and tempSensor range from -40 to 85 degrees
temperature=-40+((210+self.temperatureOffset)-tempSensorValue)
return temperature
#------------ user functions to set the radios parameters and registers --------------
def set_acks(self, receiveAck=0, sendAck=0):
"""set_acks, function to set the radio objects sendAck and receive ack variables"""
self.sendAck = sendAck # ack pattern for when returning an acknowledgment
self.receiveAck = receiveAck # ack pattern for when asking for an acknowledgment back
return
def set_address_filtering(self, mode='none'):
"""set_address_filtering, user function to set the addressing
filtering mode; none (none), node address match (node), either node or broadcast
address match (both)"""
if mode == 'node':
addressBits = 0b01
elif mode == 'both':
addressBits = 0b10
else:
addressBits = 0b00
regPacketConfig = self.single_access_read(0x37)
regPacketConfig = regPacketConfig & 0b11111001
regPacketConfig = regPacketConfig | (addressBits<<1)
self.set_register_by_name('RegPacketConfig1', regPacketConfig)
return
def set_afc(self, afcLowBetaOn='Standard', afcOffset=0, dccFreq=4, rxBW=10.4, autoclearOn='off', autoOn='on'):
"""set_afc, user function to set the parameters for automatic
frequency correction, this will set 4 different registers, RegAfcCtrl,
RegAfcBw and RegAfcFei, RegTestAfc"""
#------ RegAfcCtrl and RegTestAfc Section ----------
if afcLowBetaOn == 'Improved':
self.set_register_by_name('RegAfcCtrl', 0x20)
afcOffsetReg = afcOffset/488
self.set_register_by_name('RegTestAfc', afcOffsetReg)
else: # afcLowBetaOn = Standard
self.set_register_by_name('RegAfcCtrl', 0x00)
#-------- RegAfcBw Section ----------
dccFreqOptions = [(16,0b000),(8,0b001),(4,0b010),(2,0b011),
(1,0b100),(0.5,0b101),(0.25,0b110),(0.125,0b111)]
dccBits = 0b010 # default value if a correct match is not found
for dcc in dccFreqOptions:
if dcc[0] == dccFreq:
dccBits = dcc[1]
rxBwOptions = [(2.6,0b10111),(3.1,0b01111),(3.9,0b00111),(5.2,0b10110),
(6.3,0b01110),(7.8,0b00110),(10.4,0b10101),(12.5,0b01101),
(15.6,0b00101),(20.8,0b10100),(25,0b01100),(31.3,0b00100),
(41.7,0b10011),(50.0,0b01011),(62.5,0b00011),(83.3,0b10010),
(100.0,0b01010),(125.0,0b00010),(166.7,0b10001),(200.0,0b01001),
(250.0,0b00001),(333.3,0b10000),(400.0,0b01000),(500.0,0b00000)]
bwBits = 0b10101 # default value if a correct match is not found
for bw in rxBwOptions:
if bw[0] == rxBW:
bwBits = bw[1]
afcBwReg = (dccBits<<5)+bwBits
self.set_register_by_name('RegAfcBw', afcBwReg)
#--------- RegAfcFei Section ------------
if autoclearOn == 'off':
autoclearBits = 0b0
else:
autoclearBits = 0b1
if autoOn == 'on':
autoOnBits = 0b1
else:
autoOnBits = 0b0
afcFeiReg=(autoclearBits<<3) + (autoOnBits<<2)
self.set_register_by_name('RegAfcFei', afcFeiReg)
return
def set_auto_rx_restart(self, autoRestartOn='on', interPacketDelay=0x0):
"""set_auto_rx_restart, user function to enable/disable
the automatic Rx restart (RSSI phase) feature of the radio
and set the InterPacketRxDelay"""
if autoRestartOn == 'off':
autoRestartOnBit = 0b0
else: # autoRestartOn = on
autoRestartOnBit = 0b1
if interPacketDelay < 0 or interPacketDelay > 15:
interPacketDelay = 0
regPacketConfig = self.single_access_read(0x3D)
regPacketConfig = regPacketConfig & 0b00001101
regPacketConfig = regPacketConfig | (interPacketDelay<<4) + (autoRestartOnBit<<1)
self.set_register_by_name('RegPacketConfig2', regPacketConfig)
return
def set_bitrate(self,bitrate):
"""set_bitrate, user function to change the radio
transmission bitrate"""
bitrate=int(32000000/bitrate)
msb = (bitrate & 0xFF00)>>8
lsb = bitrate & 0xFF
self.variable_length_write(0x03, 2,[msb,lsb])
for reg in self.registerList:
if reg['name'] == 'RegBitRateMsb':
reg['value']= msb
elif reg['name'] == 'RegBitRateLsb':
reg['value']= lsb
else:
pass
return
def set_broadcast_address(self, address=0x07):
"""set_broadcast_address, user function to set the broadcast
address of the current radio"""
address = address & 0xFF # check to ensure address is only 8 bits long
self.set_register_by_name('RegBroadcastAdrs', address)
return
def set_checksum(self, crcOn='on', autoClearFifo='on'):
"""set_checksum, user function to enable a checksum
calculation function."""
if crcOn == 'off':
crcOnBit = 0b0
else:
crcOnBit = 0b1
if autoClearFifo == 'off':
autoClearBit = 0b1
else:
autoClearBit = 0b0
regPacketConfig = self.single_access_read(0x37)
regPacketConfig = regPacketConfig & 0b11100111
regPacketConfig = regPacketConfig | ((crcOnBit<<4)+(autoClearBit<<3))
self.set_register_by_name('RegPacketConfig1', regPacketConfig)
return
def set_data_mode(self, dataMode='packet', modulationType='FSK', modShaping='none', bitSynchOn='on'):
"""set_data_mode, function to set the data mode parameters"""
if dataMode == 'continuous':
if bitSynchOn == 'off':
dataModeBits = 0b11
else: # bitSynchOn = on
dataModeBits = 0b10
else: # dataMode = packet
dataModeBits = 0b00
if modulationType == 'OOK':
modTypeBits = 0b01
if modShaping == 1:
modShapingBits = 0b01 # filtering with fcutoff = BR
elif modShaping == 2:
modShapingBits = 0b10 # filtering with fcutoff = 2*BR
else: # modShaping = none
modShapingBits = 0b00
else: # modulationType = FSK
modTypeBits = 0b00
if modShaping == 1:
modShapingBits = 0b01 # Guassian filter, BT = 1
elif modShaping == 0.5:
modShapingBits = 0b10 # Gaussian filter, BT = 0.5
elif modShaping == 0.3:
modShapingBits = 0b11 # Gaussian filter, BT = 0.3
else: # modShaping = none
modShapingBits = 0b00
regDataMode = (dataModeBits<<5) + (modTypeBits<<3) + modShapingBits
self.set_register_by_name('RegDataModul', regDataMode)
return
def set_dc_free_encoding(self, encodingType='none'):
"""set_dc_free_encoding, user function to enable/disable
DC free encoding, 3 choices - none, manchester or whitening"""
if encodingType == 'manchester':
encodingBits = 0b01
elif encodingType == 'whitening':
encodingBits = 0b10
else : # encodingType = none
encodingBits = 0b00
regPacketConfig = self.single_access_read(0x37)
regPacketConfig = regPacketConfig & 0b10011111
regPacketConfig = regPacketConfig | (encodingBits<<5)
self.set_register_by_name('RegPacketConfig1', regPacketConfig)
return
def set_dio(self, dio0=0, dio1=0, dio2=0, dio3=0, dio4=0, dio5=0, clkOut='off'):
"""set_dio, user function to map the DIO (digital I/O) pins of
the radio as well as set the clock output frequency if used"""
dioList = [dio0, dio1, dio2, dio3, dio4, dio5]
# check to ensure dio entered is a valid dio mapping value
# i.e. within 0 (0b00) to 3 (0b11)
for i in range(0,6):
if dioList[i] < 0 or dioList[i] > 3:
dioList[i] = 0
# set clock output bits
if clkOut == 1:
clkOutBits = 0b000 # FXOSC
elif clkOut == 2:
clkOutBits = 0b001 # FXOSC/2
elif clkOut == 4:
clkOutBits = 0b010 # FXOSC/4
elif clkOut == 8:
clkOutBits = 0b011 # FXOSC/8
elif clkOut == 16:
clkOutBits = 0b100 # FXOSC/16
elif clkOut == 32:
clkOutBits = 0b101 # FXOSC/32
elif clkOut == 'auto':
clkOutBits = 0b110 # RC(autmatically enabled)
else: # clkOut = off
clkOutBits = 0b111 # Off
regDio1 = (dioList[0]<<6) + (dioList[1]<<4) + (dioList[2]<<2) + dioList[3]
regDio2 = (dioList[4]<<6) + (dioList[5]<<4) + clkOutBits
self.set_register_by_name('RegDioMapping1', regDio1)
self.set_register_by_name('RegDioMapping2', regDio2)
return
def set_encryption(self, aesOn='on', aesKeyList=[]):
"""set_encryption, user function to enable/disable AES encryption
and set the 16 AES encyption key registers. If aesKeyList is left empty
the AES key registers will be left as is"""
#---- RegPacketConfig2 section (AES enable/disable -------
if aesOn == 'off':
aesOnBit = 0b0
else: # aesOn = on
aesOnBit = 0b1
regPacketConfig = self.single_access_read(0x3D)
regPacketConfig = regPacketConfig & 0b11111110
regPacketConfig = regPacketConfig | aesOnBit
self.set_register_by_name('RegPacketConfig2', regPacketConfig)
#-----RegAesKey1 through 16 section -------------
if len(aesKeyList)>0: # if aesKeyList is empty, leave values as is
# Check length of aesKeyList and add or delete items as
# required to make the length 16
while len(aesKeyList) !=16:
if len(aesKeyList) < 16:
aesKeyList.append(0xB3)
else:
aesKeyList.pop()
self.variable_length_write(0x3E, 13, aesKeyList)
regAddrs=0x3E
for i in range(0,16):
for reg in self.registerList:
if reg['address'] == regAddrs:
reg['value']= aesKeyList[i]
regAddrs+=1
return
def set_fifo_threshold(self, txStartCond='FifoLevel', threshold=20):
"""set_fifo_threshold, user function to define the condition
to start packet transmission and set the Fifo threshold used to
trigger the FifoLevel interrupt"""
if txStartCond == 'FifoLevel':
txStartBit = 0b0
else: #TxStartCond = FifoNotEmpty
txStartBit = 0b1
if abs(threshold) > 66: # ensure threshold isn't bigger than the Fifo (66 bytes)
threshold = 66
regFifoThresh = (txStartBit<<7)+threshold
self.set_register_by_name('RegFifoThresh', regFifoThresh)
return
def set_frequency(self,frequency):
"""set_frequency, user function to change the radio
frequency"""
frequency=int(frequency/61.03515625)
msb = (frequency & 0xFF0000)>>16
mid = (frequency & 0xFF00)>>8
lsb = frequency & 0xFF
self.variable_length_write(0x07, 3,[msb,mid,lsb])
for reg in self.registerList:
if reg['name'] == 'RegFrfMsb':
reg['value']= msb
elif reg['name'] == 'RegFrfMid':
reg['value']= mid
elif reg['name'] == 'RegFrfLsb':
reg['value']= lsb
else:
pass
return
def set_frequency_deviation(self,fDev):
"""set_frequency_deviation, user function to change the radio
transmission frequency deviation"""
fDev=int(fDev/61.03515625)
msb = (fDev & 0xFF00)>>8
lsb = fDev & 0xFF
self.variable_length_write(0x05, 2,[msb,lsb])
for reg in self.registerList:
if reg['name'] == 'RegFdevMsb':
reg['value']= msb
elif reg['name'] == 'RegFdevLsb':
reg['value']= lsb
else:
pass
return
def set_interrupt_pin(self, intPin=0):
"""set_interrupt_pin, function to set the radio objects intPin variable"""
self.intPin = intPin # interrupt pin used
return
def set_lna(self, autoOn='on', gainSelect='G1', inputZ=50):
"""set_lna, user function to set the parameters for the
receiver's LNA (low noise amplifier)"""
if inputZ == 50:
zBit = 0b0
else: # inputZ = 200
zBit = 0b1
gainOptions =[('G1',0b001),('G2',0b010),('G3',0b011),('G4',0b100),
('G5',0b101),('G6',0b110)]
gainBits = 0b001 # default value if a correct match is not found
if autoOn == 'off':
for gain in gainOptions:
if gain[0] == gainSelect:
gainBits = gain[1]
lnaReg = (zBit<<7)+ gainBits
else:
lnaReg = zBit<<7
self.set_register_by_name('RegLna', lnaReg)
return
def set_mode_sequencer(self, sequencer='on'):
"""set_mode_sequencer, user function to enable/disable the
radio's automatic sequencer"""
if sequencer == 'off':
sequencerBit= 0b1
else: # sequencer = 'on'
sequencerBit = 0b0
regOpMode = self.single_access_read(0x01)
regOpMode = regOpMode & 0b01111111
regOpMode = regOpMode | (sequencerBit<<7)
self.set_register_by_name('RegOpMode', regOpMode)
return
def set_node_address(self, address=0x05):
"""set_node_address, user function to set the node address
of the current radio"""
address = address & 0xFF # check to ensure address is only 8 bits long
self.set_register_by_name('RegNodeAdrs', address)
return
def set_OCP(self, ocpOn='on', ocpMax=95):