adafruit-circuitpython-rfm 1.0.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
adafruit_rfm/rfm69.py ADDED
@@ -0,0 +1,651 @@
1
+ # SPDX-FileCopyrightText: 2024 Jerry Needell for Adafruit Industries
2
+ #
3
+ # SPDX-License-Identifier: MIT
4
+
5
+ """
6
+ `adafruit_rfm.rfm69`
7
+ ====================================================
8
+
9
+ CircuitPython RFM69 packet radio module. This supports sending and
10
+ receiving of packets with RFM69 series radios (433/915Mhz).
11
+
12
+ .. warning:: This is NOT for LoRa radios!
13
+
14
+ .. note:: This is a 'best effort' at receiving data using pure Python code. You might lose packets
15
+ if they're sent too quickly for the board to process them.
16
+
17
+ * Author(s): Jerry Needell
18
+ """
19
+
20
+ import time
21
+
22
+ from micropython import const
23
+
24
+ from adafruit_rfm.rfm_common import RFMSPI, ticks_diff
25
+
26
+ HAS_SUPERVISOR = False
27
+
28
+ try:
29
+ import supervisor
30
+
31
+ if hasattr(supervisor, "ticks_ms"):
32
+ HAS_SUPERVISOR = True
33
+ except ImportError:
34
+ pass
35
+
36
+ try:
37
+ from typing import Optional
38
+
39
+ import busio
40
+ import digitalio
41
+ from circuitpython_typing import ReadableBuffer
42
+
43
+ except ImportError:
44
+ pass
45
+
46
+
47
+ __version__ = "1.0.4"
48
+ __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_RFM.git"
49
+
50
+
51
+ # Internal constants:
52
+ _RF69_REG_00_FIFO = const(0x00)
53
+ _RF69_REG_01_OP_MODE = const(0x01)
54
+ _RF69_REG_02_DATA_MOD = const(0x02)
55
+ _RF69_REG_03_BITRATE_MSB = const(0x03)
56
+ _RF69_REG_04_BITRATE_LSB = const(0x04)
57
+ _RF69_REG_05_FDEV_MSB = const(0x05)
58
+ _RF69_REG_06_FDEV_LSB = const(0x06)
59
+ _RF69_REG_07_FRF_MSB = const(0x07)
60
+ _RF69_REG_08_FRF_MID = const(0x08)
61
+ _RF69_REG_09_FRF_LSB = const(0x09)
62
+ _RF69_REG_10_VERSION = const(0x10)
63
+ _RF69_REG_11_PA_LEVEL = const(0x11)
64
+ _RF69_REG_13_OCP = const(0x13)
65
+ _RF69_REG_19_RX_BW = const(0x19)
66
+ _RF69_REG_1A_AFC_BW = const(0x1A)
67
+ _RF69_REG_1B_OOK_PEAK = const(0x1B)
68
+ _RF69_REG_1C_OOK_AVG = const(0x1C)
69
+ _RF69_REG_1D_OOK_FIX = const(0x1D)
70
+ _RF69_REG_24_RSSI_VALUE = const(0x24)
71
+ _RF69_REG_25_DIO_MAPPING1 = const(0x25)
72
+ _RF69_REG_27_IRQ_FLAGS1 = const(0x27)
73
+ _RF69_REG_28_IRQ_FLAGS2 = const(0x28)
74
+ _RF69_REG_2C_PREAMBLE_MSB = const(0x2C)
75
+ _RF69_REG_2D_PREAMBLE_LSB = const(0x2D)
76
+ _RF69_REG_2E_SYNC_CONFIG = const(0x2E)
77
+ _RF69_REG_2F_SYNC_VALUE1 = const(0x2F)
78
+ _RF69_REG_39_NODE_ADDR = const(0x39)
79
+ _RF69_REG_3A_BROADCAST_ADDR = const(0x3A)
80
+ _RF69_REG_37_PACKET_CONFIG1 = const(0x37)
81
+ _RF69_REG_3C_FIFO_THRESH = const(0x3C)
82
+ _RF69_REG_3D_PACKET_CONFIG2 = const(0x3D)
83
+ _RF69_REG_3E_AES_KEY1 = const(0x3E)
84
+ _RF69_REG_4E_TEMP1 = const(0x4E)
85
+ _RF69_REG_4F_TEMP2 = const(0x4F)
86
+ _RF69_REG_5A_TEST_PA1 = const(0x5A)
87
+ _RF69_REG_5C_TEST_PA2 = const(0x5C)
88
+ _RF69_REG_6F_TEST_DAGC = const(0x6F)
89
+
90
+ _TEST_PA1_NORMAL = const(0x55)
91
+ _TEST_PA1_BOOST = const(0x5D)
92
+ _TEST_PA2_NORMAL = const(0x70)
93
+ _TEST_PA2_BOOST = const(0x7C)
94
+ _OCP_NORMAL = const(0x1A)
95
+ _OCP_HIGH_POWER = const(0x0F)
96
+
97
+ # The crystal oscillator frequency and frequency synthesizer step size.
98
+ # See the datasheet for details of this calculation.
99
+ _FXOSC = 32000000.0
100
+ _FSTEP = _FXOSC / 524288
101
+
102
+ # RadioHead specific compatibility constants.
103
+ _RH_BROADCAST_ADDRESS = const(0xFF)
104
+ # The acknowledgement bit in the FLAGS
105
+ # The top 4 bits of the flags are reserved for RadioHead. The lower 4 bits are reserved
106
+ # for application layer use.
107
+ _RH_FLAGS_ACK = const(0x80)
108
+ _RH_FLAGS_RETRY = const(0x40)
109
+
110
+ # User facing constants:
111
+ SLEEP_MODE = 0b000
112
+ STANDBY_MODE = 0b001
113
+ FS_MODE = 0b010
114
+ TX_MODE = 0b011
115
+ RX_MODE = 0b100
116
+
117
+
118
+ # pylint: disable=too-many-instance-attributes
119
+ # pylint: disable=too-many-public-methods
120
+ class RFM69(RFMSPI):
121
+ """Interface to a RFM69 series packet radio. Allows simple sending and
122
+ receiving of wireless data at supported frequencies of the radio
123
+ (433/915mhz).
124
+
125
+ :param busio.SPI spi: The SPI bus connected to the chip. Ensure SCK, MOSI, and MISO are
126
+ connected.
127
+ :param ~digitalio.DigitalInOut cs: A DigitalInOut object connected to the chip's CS/chip select
128
+ line.
129
+ :param ~digitalio.DigitalInOut reset: A DigitalInOut object connected to the chip's RST/reset
130
+ line.
131
+ :param int frequency: The center frequency to configure for radio transmission and reception.
132
+ Must be a frequency supported by your hardware (i.e. either 433 or 915mhz).
133
+ :param bytes sync_word: A byte string up to 8 bytes long which represents the syncronization
134
+ word used by received and transmitted packets. Read the datasheet for a full understanding
135
+ of this value! However by default the library will set a value that matches the RadioHead
136
+ Arduino library.
137
+ :param int preamble_length: The number of bytes to pre-pend to a data packet as a preamble.
138
+ This is by default 4 to match the RadioHead library.
139
+ :param bytes encryption_key: A 16 byte long string that represents the AES encryption key to use
140
+ when encrypting and decrypting packets. Both the transmitter and receiver MUST have the
141
+ same key value! By default no encryption key is set or used.
142
+ :param bool high_power: Indicate if the chip is a high power variant that supports boosted
143
+ transmission power. The default is True as it supports the common RFM69HCW modules sold by
144
+ Adafruit.
145
+
146
+ Remember this library makes a best effort at receiving packets with pure Python code. Trying
147
+ to receive packets too quickly will result in lost data so limit yourself to simple scenarios
148
+ of sending and receiving single packets at a time.
149
+
150
+ Also note this library defaults to be compatible with RadioHead Arduino library communication.
151
+ This means the library sets up the radio modulation to match RadioHead's default of GFSK
152
+ encoding, 250kbit/s bitrate, and 250khz frequency deviation. To change this requires explicitly
153
+ setting the radio's bitrate and encoding register bits.
154
+ Read the datasheet and study the init function to see an example of this--advanced users only!
155
+ Advanced RadioHead features like address/node specific packets or "reliable datagram" delivery
156
+ are supported however due to the limitations noted, "reliable datagram" is still subject to
157
+ missed packets.
158
+ """
159
+
160
+ # Control bits from the registers of the chip:
161
+ data_mode = RFMSPI.RegisterBits(_RF69_REG_02_DATA_MOD, offset=5, bits=2)
162
+ modulation_type = RFMSPI.RegisterBits(_RF69_REG_02_DATA_MOD, offset=3, bits=2)
163
+ modulation_shaping = RFMSPI.RegisterBits(_RF69_REG_02_DATA_MOD, offset=0, bits=2)
164
+ temp_start = RFMSPI.RegisterBits(_RF69_REG_4E_TEMP1, offset=3)
165
+ temp_running = RFMSPI.RegisterBits(_RF69_REG_4E_TEMP1, offset=2)
166
+ sync_on = RFMSPI.RegisterBits(_RF69_REG_2E_SYNC_CONFIG, offset=7)
167
+ sync_size = RFMSPI.RegisterBits(_RF69_REG_2E_SYNC_CONFIG, offset=3, bits=3)
168
+ aes_on = RFMSPI.RegisterBits(_RF69_REG_3D_PACKET_CONFIG2, offset=0)
169
+ pa_0_on = RFMSPI.RegisterBits(_RF69_REG_11_PA_LEVEL, offset=7)
170
+ pa_1_on = RFMSPI.RegisterBits(_RF69_REG_11_PA_LEVEL, offset=6)
171
+ pa_2_on = RFMSPI.RegisterBits(_RF69_REG_11_PA_LEVEL, offset=5)
172
+ output_power = RFMSPI.RegisterBits(_RF69_REG_11_PA_LEVEL, offset=0, bits=5)
173
+ rx_bw_dcc_freq = RFMSPI.RegisterBits(_RF69_REG_19_RX_BW, offset=5, bits=3)
174
+ rx_bw_mantissa = RFMSPI.RegisterBits(_RF69_REG_19_RX_BW, offset=3, bits=2)
175
+ rx_bw_exponent = RFMSPI.RegisterBits(_RF69_REG_19_RX_BW, offset=0, bits=3)
176
+ afc_bw_dcc_freq = RFMSPI.RegisterBits(_RF69_REG_1A_AFC_BW, offset=5, bits=3)
177
+ afc_bw_mantissa = RFMSPI.RegisterBits(_RF69_REG_1A_AFC_BW, offset=3, bits=2)
178
+ afc_bw_exponent = RFMSPI.RegisterBits(_RF69_REG_1A_AFC_BW, offset=0, bits=3)
179
+ packet_format = RFMSPI.RegisterBits(_RF69_REG_37_PACKET_CONFIG1, offset=7, bits=1)
180
+ dc_free = RFMSPI.RegisterBits(_RF69_REG_37_PACKET_CONFIG1, offset=5, bits=2)
181
+ crc_on = RFMSPI.RegisterBits(_RF69_REG_37_PACKET_CONFIG1, offset=4, bits=1)
182
+ crc_auto_clear_off = RFMSPI.RegisterBits(_RF69_REG_37_PACKET_CONFIG1, offset=3, bits=1)
183
+ address_filter = RFMSPI.RegisterBits(_RF69_REG_37_PACKET_CONFIG1, offset=1, bits=2)
184
+ mode_ready = RFMSPI.RegisterBits(_RF69_REG_27_IRQ_FLAGS1, offset=7)
185
+ dio_0_mapping = RFMSPI.RegisterBits(_RF69_REG_25_DIO_MAPPING1, offset=6, bits=2)
186
+ ook_thresh_type = RFMSPI.RegisterBits(_RF69_REG_1B_OOK_PEAK, offset=6, bits=2)
187
+ ook_thresh_step = RFMSPI.RegisterBits(_RF69_REG_1B_OOK_PEAK, offset=5, bits=3)
188
+ ook_peak_thresh_dec = RFMSPI.RegisterBits(_RF69_REG_1B_OOK_PEAK, offset=0, bits=3)
189
+ ook_average_thresh_filt = RFMSPI.RegisterBits(_RF69_REG_1C_OOK_AVG, offset=6, bits=2)
190
+
191
+ # pylint: disable=too-many-statements
192
+ # pylint: disable=too-many-arguments
193
+ def __init__( # noqa: PLR0913
194
+ self,
195
+ spi: busio.SPI,
196
+ cs: digitalio.DigitalInOut,
197
+ rst: digitalio.DigitalInOut,
198
+ frequency: int,
199
+ *,
200
+ sync_word: bytes = b"\x2d\xd4",
201
+ preamble_length: int = 4,
202
+ encryption_key: Optional[bytes] = None,
203
+ high_power: bool = True,
204
+ baudrate: int = 2000000,
205
+ crc: bool = True,
206
+ ) -> None:
207
+ super().__init__(spi, cs, baudrate=baudrate)
208
+
209
+ self.module = "RFM69"
210
+ self.max_packet_length = 60
211
+ self.high_power = high_power
212
+ # Device support SPI mode 0 (polarity & phase = 0) up to a max of 10mhz.
213
+ # self._device = spidev.SPIDevice(spi, cs, baudrate=baudrate, polarity=0, phase=0)
214
+ # Setup reset as a digital output that's low.
215
+ self._rst = rst
216
+ self._rst.switch_to_output(value=False)
217
+ self.reset() # Reset the chip.
218
+ # Check the version of the chip.
219
+ version = self.read_u8(_RF69_REG_10_VERSION)
220
+ if version not in (0x23, 0x24):
221
+ raise RuntimeError("Invalid RFM69 version, check wiring! ID found:", hex(version))
222
+ self.idle() # Enter idle state.
223
+ # Setup the chip in a similar way to the RadioHead RFM69 library.
224
+ # Set FIFO TX condition to not empty and the default FIFO threshold to 15.
225
+ self.write_u8(_RF69_REG_3C_FIFO_THRESH, 0b10001111)
226
+ # Configure low beta off.
227
+ self.write_u8(_RF69_REG_6F_TEST_DAGC, 0x30)
228
+ # Set the syncronization word.
229
+ self.sync_word = sync_word
230
+ self.preamble_length = preamble_length # Set the preamble length.
231
+ self.frequency_mhz = frequency # Set frequency.
232
+ self.encryption_key = encryption_key # Set encryption key.
233
+ # Configure modulation for RadioHead library GFSK_Rb250Fd250 mode
234
+ # by default. Users with advanced knowledge can manually reconfigure
235
+ # for any other mode (consulting the datasheet is absolutely
236
+ # necessary!).
237
+ self.modulation_shaping = 0b01 # Gaussian filter, BT=1.0
238
+ self.bitrate = 250000 # 250kbs
239
+ self.frequency_deviation = 250000 # 250khz
240
+ self.rx_bw_dcc_freq = 0b111 # RxBw register = 0xE0
241
+ self.rx_bw_mantissa = 0b00
242
+ self.rx_bw_exponent = 0b000
243
+ self.afc_bw_dcc_freq = 0b111 # AfcBw register = 0xE0
244
+ self.afc_bw_mantissa = 0b00
245
+ self.afc_bw_exponent = 0b000
246
+ self.packet_format = 1 # Variable length.
247
+ self.dc_free = 0b10 # Whitening
248
+ # Set transmit power to 13 dBm, a safe value any module supports.
249
+ self._tx_power = None
250
+ self.tx_power = 13
251
+ # Default to enable CRC checking on incoming packets.
252
+ self.enable_crc = crc
253
+ self.snr = None
254
+
255
+ def reset(self) -> None:
256
+ """Perform a reset of the chip."""
257
+ # See section 7.2.2 of the datasheet for reset description.
258
+ self._rst.value = True
259
+ time.sleep(0.0001) # 100 us
260
+ self._rst.value = False
261
+ time.sleep(0.005) # 5 ms
262
+
263
+ def disable_boost(self) -> None:
264
+ """Disable preamp boost."""
265
+ if self.high_power:
266
+ self.write_u8(_RF69_REG_5A_TEST_PA1, _TEST_PA1_NORMAL)
267
+ self.write_u8(_RF69_REG_5C_TEST_PA2, _TEST_PA2_NORMAL)
268
+ self.write_u8(_RF69_REG_13_OCP, _OCP_NORMAL)
269
+
270
+ def idle(self) -> None:
271
+ """Enter idle standby mode (switching off high power amplifiers if necessary)."""
272
+ # Like RadioHead library, turn off high power boost if enabled.
273
+ self.disable_boost()
274
+ self.operation_mode = STANDBY_MODE
275
+
276
+ def sleep(self) -> None:
277
+ """Enter sleep mode."""
278
+ self.operation_mode = SLEEP_MODE
279
+
280
+ def listen(self) -> None:
281
+ """Listen for packets to be received by the chip. Use :py:func:`receive` to listen, wait
282
+ and retrieve packets as they're available.
283
+ """
284
+ # Like RadioHead library, turn off high power boost if enabled.
285
+ self.disable_boost()
286
+ # Enable payload ready interrupt for D0 line.
287
+ self.dio_0_mapping = 0b01
288
+ # Enter RX mode (will clear FIFO!).
289
+ self.operation_mode = RX_MODE
290
+
291
+ def transmit(self) -> None:
292
+ """Transmit a packet which is queued in the FIFO. This is a low level function for
293
+ entering transmit mode and more. For generating and transmitting a packet of data use
294
+ :py:func:`send` instead.
295
+ """
296
+ # Like RadioHead library, turn on high power boost if needed.
297
+ if self.high_power and (self._tx_power >= 18):
298
+ self.write_u8(_RF69_REG_5A_TEST_PA1, _TEST_PA1_BOOST)
299
+ self.write_u8(_RF69_REG_5C_TEST_PA2, _TEST_PA2_BOOST)
300
+ self.write_u8(_RF69_REG_13_OCP, _OCP_HIGH_POWER)
301
+ # Enable packet sent interrupt for D0 line.
302
+ self.dio_0_mapping = 0b00
303
+ # Enter TX mode (will clear FIFO!).
304
+ self.operation_mode = TX_MODE
305
+
306
+ @property
307
+ def temperature(self) -> float:
308
+ """The internal temperature of the chip in degrees Celsius. Be warned this is not
309
+ calibrated or very accurate.
310
+
311
+ .. warning:: Reading this will STOP any receiving/sending that might be happening!
312
+ """
313
+ # Start a measurement then poll the measurement finished bit.
314
+ self.temp_start = 1
315
+ while self.temp_running > 0:
316
+ pass
317
+ # Grab the temperature value and convert it to Celsius.
318
+ # This uses the same observed value formula from the Radiohead library.
319
+ temp = self.read_u8(_RF69_REG_4F_TEMP2)
320
+ return 166.0 - temp
321
+
322
+ @property
323
+ def operation_mode(self) -> int:
324
+ """The operation mode value. Unless you're manually controlling the chip you shouldn't
325
+ change the operation_mode with this property as other side-effects are required for
326
+ changing logical modes--use :py:func:`idle`, :py:func:`sleep`, :py:func:`transmit`,
327
+ :py:func:`listen` instead to signal intent for explicit logical modes.
328
+ """
329
+ op_mode = self.read_u8(_RF69_REG_01_OP_MODE)
330
+ return (op_mode >> 2) & 0b111
331
+
332
+ @operation_mode.setter
333
+ def operation_mode(self, val: int) -> None:
334
+ assert 0 <= val <= 4
335
+ # Set the mode bits inside the operation mode register.
336
+ op_mode = self.read_u8(_RF69_REG_01_OP_MODE)
337
+ op_mode &= 0b11100011
338
+ op_mode |= val << 2
339
+ self.write_u8(_RF69_REG_01_OP_MODE, op_mode)
340
+ # Wait for mode to change by polling interrupt bit.
341
+ if HAS_SUPERVISOR:
342
+ start = supervisor.ticks_ms()
343
+ while not self.mode_ready:
344
+ if ticks_diff(supervisor.ticks_ms(), start) >= 1000:
345
+ raise TimeoutError("Operation Mode failed to set.")
346
+ else:
347
+ start = time.monotonic()
348
+ while not self.mode_ready:
349
+ if time.monotonic() - start >= 1:
350
+ raise TimeoutError("Operation Mode failed to set.")
351
+
352
+ @property
353
+ def sync_word(self) -> bytearray:
354
+ """The synchronization word value. This is a byte string up to 8 bytes long (64 bits)
355
+ which indicates the synchronization word for transmitted and received packets. Any
356
+ received packet which does not include this sync word will be ignored. The default value
357
+ is 0x2D, 0xD4 which matches the RadioHead RFM69 library. Setting a value of None will
358
+ disable synchronization word matching entirely.
359
+ """
360
+ # Handle when sync word is disabled..
361
+ if not self.sync_on:
362
+ return None
363
+ # Sync word is not disabled so read the current value.
364
+ sync_word_length = self.sync_size + 1 # Sync word size is offset by 1
365
+ # according to datasheet.
366
+ sync_word = bytearray(sync_word_length)
367
+ self.read_into(_RF69_REG_2F_SYNC_VALUE1, sync_word)
368
+ return sync_word
369
+
370
+ @sync_word.setter
371
+ def sync_word(self, val: Optional[bytearray]) -> None:
372
+ # Handle disabling sync word when None value is set.
373
+ if val is None:
374
+ self.sync_on = 0
375
+ else:
376
+ # Check sync word is at most 8 bytes.
377
+ assert 1 <= len(val) <= 8
378
+ # Update the value, size and turn on the sync word.
379
+ self.write_from(_RF69_REG_2F_SYNC_VALUE1, val)
380
+ self.sync_size = len(val) - 1 # Again sync word size is offset by
381
+ # 1 according to datasheet.
382
+ self.sync_on = 1
383
+
384
+ @property
385
+ def preamble_length(self) -> int:
386
+ """The length of the preamble for sent and received packets, an unsigned 16-bit value.
387
+ Received packets must match this length or they are ignored! Set to 4 to match the
388
+ RadioHead RFM69 library.
389
+ """
390
+ msb = self.read_u8(_RF69_REG_2C_PREAMBLE_MSB)
391
+ lsb = self.read_u8(_RF69_REG_2D_PREAMBLE_LSB)
392
+ return ((msb << 8) | lsb) & 0xFFFF
393
+
394
+ @preamble_length.setter
395
+ def preamble_length(self, val: int) -> None:
396
+ assert 0 <= val <= 65535
397
+ self.write_u8(_RF69_REG_2C_PREAMBLE_MSB, (val >> 8) & 0xFF)
398
+ self.write_u8(_RF69_REG_2D_PREAMBLE_LSB, val & 0xFF)
399
+
400
+ @property
401
+ def frequency_mhz(self) -> float:
402
+ """The frequency of the radio in Megahertz. Only the allowed values for your radio must be
403
+ specified (i.e. 433 vs. 915 mhz)!
404
+ """
405
+ # FRF register is computed from the frequency following the datasheet.
406
+ # See section 6.2 and FRF register description.
407
+ # Read bytes of FRF register and assemble into a 24-bit unsigned value.
408
+ msb = self.read_u8(_RF69_REG_07_FRF_MSB)
409
+ mid = self.read_u8(_RF69_REG_08_FRF_MID)
410
+ lsb = self.read_u8(_RF69_REG_09_FRF_LSB)
411
+ frf = ((msb << 16) | (mid << 8) | lsb) & 0xFFFFFF
412
+ frequency = (frf * _FSTEP) / 1000000.0
413
+ return frequency
414
+
415
+ @frequency_mhz.setter
416
+ def frequency_mhz(self, val: float) -> None:
417
+ assert 290 <= val <= 1020
418
+ # Calculate FRF register 24-bit value using section 6.2 of the datasheet.
419
+ frf = int((val * 1000000.0) / _FSTEP) & 0xFFFFFF
420
+ # Extract byte values and update registers.
421
+ msb = frf >> 16
422
+ mid = (frf >> 8) & 0xFF
423
+ lsb = frf & 0xFF
424
+ self.write_u8(_RF69_REG_07_FRF_MSB, msb)
425
+ self.write_u8(_RF69_REG_08_FRF_MID, mid)
426
+ self.write_u8(_RF69_REG_09_FRF_LSB, lsb)
427
+
428
+ @property
429
+ def encryption_key(self) -> bytearray:
430
+ """The AES encryption key used to encrypt and decrypt packets by the chip. This can be set
431
+ to None to disable encryption (the default), otherwise it must be a 16 byte long byte
432
+ string which defines the key (both the transmitter and receiver must use the same key
433
+ value).
434
+ """
435
+ # Handle if encryption is disabled.
436
+ if self.aes_on == 0:
437
+ return None
438
+ # Encryption is enabled so read the key and return it.
439
+ key = bytearray(16)
440
+ self.read_into(_RF69_REG_3E_AES_KEY1, key)
441
+ return key
442
+
443
+ @encryption_key.setter
444
+ def encryption_key(self, val: bytearray) -> None:
445
+ # Handle if unsetting the encryption key (None value).
446
+ if val is None:
447
+ self.aes_on = 0
448
+ else:
449
+ # Set the encryption key and enable encryption.
450
+ assert len(val) == 16
451
+ self.write_from(_RF69_REG_3E_AES_KEY1, val)
452
+ self.aes_on = 1
453
+
454
+ @property
455
+ def tx_power(self) -> int:
456
+ """The transmit power in dBm. Can be set to a value from -2 to 20 for high power devices
457
+ (RFM69HCW, high_power=True) or -18 to 13 for low power devices. Only integer power
458
+ levels are actually set (i.e. 12.5 will result in a value of 12 dBm).
459
+ """
460
+ # Follow table 10 truth table from the datasheet for determining power
461
+ # level from the individual PA level bits and output power register.
462
+ pa0 = self.pa_0_on
463
+ pa1 = self.pa_1_on
464
+ pa2 = self.pa_2_on
465
+ current_output_power = self.output_power
466
+ if pa0 and not pa1 and not pa2:
467
+ # -18 to 13 dBm range
468
+ return -18 + current_output_power
469
+ if not pa0 and pa1 and not pa2:
470
+ # -2 to 13 dBm range
471
+ return -18 + current_output_power
472
+ if not pa0 and pa1 and pa2 and self.high_power and self._tx_power < 18:
473
+ # 2 to 17 dBm range
474
+ return -14 + current_output_power
475
+ if not pa0 and pa1 and pa2 and self.high_power and self._tx_power >= 18:
476
+ # 5 to 20 dBm range
477
+ return -11 + current_output_power
478
+ raise RuntimeError("Power amps state unknown!")
479
+
480
+ @tx_power.setter
481
+ def tx_power(self, val: float):
482
+ val = int(val)
483
+ # Determine power amplifier and output power values depending on
484
+ # high power state and requested power.
485
+ pa_0_on = pa_1_on = pa_2_on = 0
486
+ output_power = 0
487
+ if self.high_power:
488
+ # Handle high power mode.
489
+ assert -2 <= val <= 20
490
+ pa_1_on = 1
491
+ if val <= 13:
492
+ output_power = val + 18
493
+ elif 13 < val <= 17:
494
+ pa_2_on = 1
495
+ output_power = val + 14
496
+ else: # power >= 18 dBm
497
+ # Note this also needs PA boost enabled separately!
498
+ pa_2_on = 1
499
+ output_power = val + 11
500
+ else:
501
+ # Handle non-high power mode.
502
+ assert -18 <= val <= 13
503
+ # Enable only power amplifier 0 and set output power.
504
+ pa_0_on = 1
505
+ output_power = val + 18
506
+ # Set power amplifiers and output power as computed above.
507
+ self.pa_0_on = pa_0_on
508
+ self.pa_1_on = pa_1_on
509
+ self.pa_2_on = pa_2_on
510
+ self.output_power = output_power
511
+ self._tx_power = val
512
+
513
+ @property
514
+ def rssi(self) -> float:
515
+ """The received strength indicator (in dBm).
516
+ May be inaccuate if not read immediatey. last_rssi contains the value read immediately
517
+ receipt of the last packet.
518
+ """
519
+ # Read RSSI register and convert to value using formula in datasheet.
520
+ return -self.read_u8(_RF69_REG_24_RSSI_VALUE) / 2.0
521
+
522
+ @property
523
+ def bitrate(self) -> float:
524
+ """The modulation bitrate in bits/second (or chip rate if Manchester encoding is enabled).
525
+ Can be a value from ~489 to 32mbit/s, but see the datasheet for the exact supported
526
+ values.
527
+ """
528
+ msb = self.read_u8(_RF69_REG_03_BITRATE_MSB)
529
+ lsb = self.read_u8(_RF69_REG_04_BITRATE_LSB)
530
+ return _FXOSC / ((msb << 8) | lsb)
531
+
532
+ @bitrate.setter
533
+ def bitrate(self, val: float) -> None:
534
+ assert (_FXOSC / 65535) <= val <= 32000000.0
535
+ # Round up to the next closest bit-rate value with addition of 0.5.
536
+ bitrate = int((_FXOSC / val) + 0.5) & 0xFFFF
537
+ self.write_u8(_RF69_REG_03_BITRATE_MSB, bitrate >> 8)
538
+ self.write_u8(_RF69_REG_04_BITRATE_LSB, bitrate & 0xFF)
539
+
540
+ @property
541
+ def frequency_deviation(self) -> float:
542
+ """The frequency deviation in Hertz."""
543
+ msb = self.read_u8(_RF69_REG_05_FDEV_MSB)
544
+ lsb = self.read_u8(_RF69_REG_06_FDEV_LSB)
545
+ return _FSTEP * ((msb << 8) | lsb)
546
+
547
+ @frequency_deviation.setter
548
+ def frequency_deviation(self, val: float) -> None:
549
+ assert 0 <= val <= (_FSTEP * 16383) # fdev is a 14-bit unsigned value
550
+ # Round up to the next closest integer value with addition of 0.5.
551
+ fdev = int((val / _FSTEP) + 0.5) & 0x3FFF
552
+ self.write_u8(_RF69_REG_05_FDEV_MSB, fdev >> 8)
553
+ self.write_u8(_RF69_REG_06_FDEV_LSB, fdev & 0xFF)
554
+
555
+ @property
556
+ def enable_crc(self) -> bool:
557
+ """Set to True to enable hardware CRC checking of incoming packets.
558
+ Incoming packets that fail the CRC check are not processed. Set to
559
+ False to disable CRC checking and process all incoming packets."""
560
+ return self.crc_on
561
+
562
+ @enable_crc.setter
563
+ def enable_crc(self, val: bool) -> None:
564
+ # Optionally enable CRC checking on incoming packets.
565
+ if val:
566
+ self.crc_on = 1
567
+ else:
568
+ self.crc_on = 0
569
+
570
+ @property
571
+ def crc_error(self) -> bool:
572
+ """crc status"""
573
+ return (self.read_u8(_RF69_REG_28_IRQ_FLAGS2) & 0x2) >> 1
574
+
575
+ @property
576
+ def enable_address_filter(self) -> bool:
577
+ """Set to True to enable address filtering.
578
+ Incoming packets that do no match the node address or broadcast address
579
+ will be ignored."""
580
+ return self.address_filter
581
+
582
+ @enable_address_filter.setter
583
+ def enable_address_filter(self, val: bool) -> None:
584
+ # Enable address filtering on incoming packets.
585
+ if val:
586
+ self.address_filter = 2 # accept node address or broadcast address
587
+ else:
588
+ self.address_filter = 0
589
+
590
+ @property
591
+ def fsk_node_address(self) -> int:
592
+ """Node Address for Address Filtering"""
593
+ return self.read_u8(_RF69_REG_39_NODE_ADDR)
594
+
595
+ @fsk_node_address.setter
596
+ def fsk_node_address(self, val: int) -> None:
597
+ assert 0 <= val <= 255
598
+ self.write_u8(_RF69_REG_39_NODE_ADDR, val)
599
+
600
+ @property
601
+ def fsk_broadcast_address(self) -> int:
602
+ """Node Address for Address Filtering"""
603
+ return self.read_u8(_RF69_REG_3A_BROADCAST_ADDR)
604
+
605
+ @fsk_broadcast_address.setter
606
+ def fsk_broadcast_address(self, val: int) -> None:
607
+ assert 0 <= val <= 255
608
+ self.write_u8(_RF69_REG_3A_BROADCAST_ADDR, val)
609
+
610
+ @property
611
+ def ook_fixed_threshold(self) -> int:
612
+ """Fixed threshold for data slicer in OOK mode"""
613
+ return self.read_u8(_RF69_REG_1D_OOK_FIX)
614
+
615
+ @ook_fixed_threshold.setter
616
+ def ook_fixed_threshold(self, val: int) -> None:
617
+ assert 0 <= val <= 255
618
+ self.write_u8(_RF69_REG_1D_OOK_FIX, val)
619
+
620
+ def packet_sent(self) -> bool:
621
+ """Transmit status"""
622
+ return (self.read_u8(_RF69_REG_28_IRQ_FLAGS2) & 0x8) >> 3
623
+
624
+ def payload_ready(self) -> bool:
625
+ """Receive status"""
626
+ return (self.read_u8(_RF69_REG_28_IRQ_FLAGS2) & 0x4) >> 2
627
+
628
+ def clear_interrupt(self) -> None:
629
+ """Clear interrupt flags"""
630
+ self.write_u8(_RF69_REG_27_IRQ_FLAGS1, 0xFF)
631
+ self.write_u8(_RF69_REG_28_IRQ_FLAGS2, 0xFF)
632
+
633
+ def fill_fifo(self, payload: ReadableBuffer) -> None:
634
+ """Write the payload to the FIFO."""
635
+ complete_payload = bytearray(1) # prepend packet length to payload
636
+ complete_payload[0] = len(payload)
637
+ # put the payload lengthe in the beginning of the packet for RFM69
638
+ complete_payload = complete_payload + payload
639
+ # Write payload to transmit fifo
640
+ self.write_from(_RF69_REG_00_FIFO, complete_payload)
641
+
642
+ def read_fifo(self) -> Optional[bytearray]:
643
+ """Read the packet from the FIFO."""
644
+ # Read the length of the FIFO.
645
+ fifo_length = self.read_u8(_RF69_REG_00_FIFO)
646
+ packet = None # return None if FIFO empty
647
+ if fifo_length > 0: # read and clear the FIFO if anything in it
648
+ packet = bytearray(fifo_length)
649
+ # read the packet
650
+ self.read_into(_RF69_REG_00_FIFO, packet, fifo_length)
651
+ return packet