__init__.py 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  1. # python-cc1101 - Python Library to Transmit RF Signals via CC1101 Transceivers
  2. #
  3. # Copyright (C) 2020 Fabian Peter Hammerle <fabian@hammerle.me>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. import contextlib
  18. import datetime
  19. import enum
  20. import fcntl
  21. import logging
  22. import math
  23. import typing
  24. import warnings
  25. import spidev
  26. import cc1101._gpio
  27. from cc1101.addresses import (
  28. StrobeAddress,
  29. ConfigurationRegisterAddress,
  30. StatusRegisterAddress,
  31. PatableAddress,
  32. FIFORegisterAddress,
  33. )
  34. from cc1101.options import (
  35. GDOSignalSelection,
  36. ModulationFormat,
  37. PacketLengthMode,
  38. SyncMode,
  39. )
  40. _LOGGER = logging.getLogger(__name__)
  41. class Pin(enum.Enum):
  42. GDO0 = "GDO0"
  43. class _TransceiveMode(enum.IntEnum):
  44. """
  45. PKTCTRL0.PKT_FORMAT
  46. """
  47. FIFO = 0b00
  48. SYNCHRONOUS_SERIAL = 0b01
  49. RANDOM_TRANSMISSION = 0b10
  50. ASYNCHRONOUS_SERIAL = 0b11
  51. class MainRadioControlStateMachineState(enum.IntEnum):
  52. """
  53. MARCSTATE - Main Radio Control State Machine State
  54. """
  55. # see "Figure 13: Simplified State Diagram"
  56. # and "Figure 25: Complete Radio Control State Diagram"
  57. IDLE = 0x01
  58. STARTCAL = 0x08 # after IDLE
  59. BWBOOST = 0x09 # after STARTCAL
  60. FS_LOCK = 0x0A
  61. RX = 0x0D
  62. RXFIFO_OVERFLOW = 0x11
  63. TX = 0x13
  64. # TXFIFO_UNDERFLOW = 0x16
  65. class _ReceivedPacket: # unstable
  66. # "Table 31: Typical RSSI_offset Values"
  67. _RSSI_OFFSET_dB = 74
  68. def __init__(
  69. self,
  70. # *,
  71. payload: bytes,
  72. rssi_index: int, # byte
  73. checksum_valid: bool,
  74. link_quality_indicator: int, # 7bit
  75. ):
  76. self.payload = payload
  77. self._rssi_index = rssi_index
  78. assert 0 <= rssi_index < (1 << 8), rssi_index
  79. self.checksum_valid = checksum_valid
  80. self.link_quality_indicator = link_quality_indicator
  81. assert 0 <= link_quality_indicator < (1 << 7), link_quality_indicator
  82. @property
  83. def rssi_dbm(self) -> float:
  84. """
  85. Estimated Received Signal Strength Indicator (RSSI) in dBm
  86. see section "17.3 RSSI"
  87. """
  88. if self._rssi_index >= 128:
  89. return (self._rssi_index - 256) / 2 - self._RSSI_OFFSET_dB
  90. return self._rssi_index / 2 - self._RSSI_OFFSET_dB
  91. def __str__(self) -> str:
  92. return "{}(RSSI {:.0f}dBm, 0x{})".format(
  93. type(self).__name__, self.rssi_dbm, self.payload.hex()
  94. )
  95. def _format_patable(settings: typing.Iterable[int], insert_spaces: bool) -> str:
  96. # "Table 39: Optimum PATABLE Settings" uses hexadecimal digits
  97. # "0" for brevity
  98. settings_hex = tuple(map(lambda s: "0" if s == 0 else "0x{:x}".format(s), settings))
  99. if len(settings_hex) == 1:
  100. return "({},)".format(settings_hex[0])
  101. delimiter = ", " if insert_spaces else ","
  102. return "({})".format(delimiter.join(settings_hex))
  103. class CC1101:
  104. # pylint: disable=too-many-public-methods
  105. # > All transfers on the SPI interface are done
  106. # > most significant bit first.
  107. # > All transactions on the SPI interface start with
  108. # > a header byte containing a R/W bit, a access bit (B),
  109. # > and a 6-bit address (A5 - A0).
  110. # > [...]
  111. # > Table 45: SPI Address Space
  112. _WRITE_SINGLE_BYTE = 0x00
  113. # > Registers with consecutive addresses can be
  114. # > accessed in an efficient way by setting the
  115. # > burst bit (B) in the header byte. The address
  116. # > bits (A5 - A0) set the start address in an
  117. # > internal address counter. This counter is
  118. # > incremented by one each new byte [...]
  119. _WRITE_BURST = 0x40
  120. _READ_SINGLE_BYTE = 0x80
  121. _READ_BURST = 0xC0
  122. # 29.3 Status Register Details
  123. _SUPPORTED_PARTNUM = 0
  124. # > The two versions of the chip will behave the same.
  125. # https://e2e.ti.com/support/wireless-connectivity/sub-1-ghz/f/156/p/428028/1529544#1529544
  126. _SUPPORTED_VERSIONS = [
  127. 0x04, # https://github.com/fphammerle/python-cc1101/issues/15
  128. 0x14,
  129. ]
  130. _CRYSTAL_OSCILLATOR_FREQUENCY_HERTZ = 26e6
  131. # see "21 Frequency Programming"
  132. # > f_carrier = f_XOSC / 2**16 * (FREQ + CHAN * ((256 + CHANSPC_M) * 2**CHANSPC_E-2))
  133. _FREQUENCY_CONTROL_WORD_HERTZ_FACTOR = _CRYSTAL_OSCILLATOR_FREQUENCY_HERTZ / 2 ** 16
  134. # roughly estimated / tested with SDR receiver, docs specify:
  135. # > can [...] be programmed for operation at other frequencies
  136. # > in the 300-348 MHz, 387-464 MHz and 779-928 MHz bands.
  137. _TRANSMIT_MIN_FREQUENCY_HERTZ = 281.7e6
  138. # > The PATABLE is an 8-byte table that defines the PA control settings [...]
  139. _PATABLE_LENGTH_BYTES = 8
  140. def __init__(
  141. self, spi_bus: int = 0, spi_chip_select: int = 0, lock_spi_device: bool = False
  142. ) -> None:
  143. """
  144. lock_spi_device:
  145. When True, an advisory, exclusive lock will be set on the SPI device file
  146. non-blockingly via flock upon entering the context.
  147. If the SPI device file is already locked (e.g., by a different process),
  148. a BlockingIOError will be raised.
  149. The lock will be removed automatically, when leaving the context.
  150. The lock can optionally be released earlier by calling .unlock_spi_device().
  151. >>> transceiver = cc1101.CC1101(lock_spi_device=True)
  152. >>> # not locked
  153. >>> with transceiver:
  154. >>> # locked
  155. >>> # lock removed
  156. >>> with transceiver:
  157. >>> # locked
  158. >>> transceiver.unlock_spi_device()
  159. >>> # lock removed
  160. """
  161. self._spi = spidev.SpiDev()
  162. self._spi_bus = int(spi_bus)
  163. # > The BCM2835 core common to all Raspberry Pi devices has 3 SPI Controllers:
  164. # > SPI0, with two hardware chip selects, [...]
  165. # > SPI1, with three hardware chip selects, [...]
  166. # > SPI2, also with three hardware chip selects, is only usable on a Compute Module [...]
  167. # https://github.com/raspberrypi/documentation/blob/d41d69f8efa3667b1a8b01a669238b8bd113edc1/hardware/raspberrypi/spi/README.md#hardware
  168. # https://www.raspberrypi.org/documentation/hardware/raspberrypi/spi/README.md
  169. self._spi_chip_select = int(spi_chip_select)
  170. self._lock_spi_device = lock_spi_device
  171. @property
  172. def _spi_device_path(self) -> str:
  173. # https://github.com/doceme/py-spidev/blob/v3.4/spidev_module.c#L1286
  174. return "/dev/spidev{}.{}".format(self._spi_bus, self._spi_chip_select)
  175. @staticmethod
  176. def _log_chip_status_byte(chip_status: int) -> None:
  177. # see "10.1 Chip Status Byte" & "Table 23: Status Byte Summary"
  178. # > The command strobe registers are accessed by transferring
  179. # > a single header byte [...]. That is, only the R/W̄ bit,
  180. # > the burst access bit (set to 0), and the six address bits [...]
  181. # > The R/W̄ bit can be either one or zero and will determine how the
  182. # > FIFO_BYTES_AVAILABLE field in the status byte should be interpreted.
  183. _LOGGER.debug(
  184. "chip status byte: CHIP_RDYn=%d STATE=%s FIFO_BYTES_AVAILBLE=%d",
  185. chip_status >> 7,
  186. bin((chip_status >> 4) & 0b111),
  187. chip_status & 0b1111,
  188. )
  189. def _read_single_byte(
  190. self, register: typing.Union[ConfigurationRegisterAddress, FIFORegisterAddress]
  191. ) -> int:
  192. response = self._spi.xfer([register | self._READ_SINGLE_BYTE, 0])
  193. assert len(response) == 2, response
  194. self._log_chip_status_byte(response[0])
  195. return response[1]
  196. def _read_burst(
  197. self,
  198. start_register: typing.Union[
  199. ConfigurationRegisterAddress, PatableAddress, FIFORegisterAddress
  200. ],
  201. length: int,
  202. ) -> typing.List[int]:
  203. response = self._spi.xfer([start_register | self._READ_BURST] + [0] * length)
  204. assert len(response) == length + 1, response
  205. self._log_chip_status_byte(response[0])
  206. return response[1:]
  207. def _read_status_register(self, register: StatusRegisterAddress) -> int:
  208. # > For register addresses in the range 0x30-0x3D,
  209. # > the burst bit is used to select between
  210. # > status registers when burst bit is one, and
  211. # > between command strobes when burst bit is
  212. # > zero. [...]
  213. # > Because of this, burst access is not available
  214. # > for status registers and they must be accessed
  215. # > one at a time. The status registers can only be
  216. # > read.
  217. response = self._spi.xfer([register | self._READ_BURST, 0])
  218. assert len(response) == 2, response
  219. self._log_chip_status_byte(response[0])
  220. return response[1]
  221. def _command_strobe(self, register: StrobeAddress) -> None:
  222. # see "10.4 Command Strobes"
  223. _LOGGER.debug("sending command strobe 0x%02x", register)
  224. response = self._spi.xfer([register | self._WRITE_SINGLE_BYTE])
  225. assert len(response) == 1, response
  226. self._log_chip_status_byte(response[0])
  227. def _write_burst(
  228. self,
  229. start_register: typing.Union[
  230. ConfigurationRegisterAddress, PatableAddress, FIFORegisterAddress
  231. ],
  232. values: typing.List[int],
  233. ) -> None:
  234. _LOGGER.debug(
  235. "writing burst: start_register=0x%02x values=%s", start_register, values
  236. )
  237. response = self._spi.xfer([start_register | self._WRITE_BURST] + values)
  238. assert len(response) == len(values) + 1, response
  239. self._log_chip_status_byte(response[0])
  240. assert all(v == response[0] for v in response[1:]), response
  241. def _reset(self) -> None:
  242. self._command_strobe(StrobeAddress.SRES)
  243. @classmethod
  244. def _filter_bandwidth_floating_point_to_real(
  245. cls, mantissa: int, exponent: int
  246. ) -> float:
  247. """
  248. See "13 Receiver Channel Filter Bandwidth"
  249. """
  250. return cls._CRYSTAL_OSCILLATOR_FREQUENCY_HERTZ / (
  251. 8 * (4 + mantissa) * (2 ** exponent)
  252. )
  253. def _get_filter_bandwidth_hertz(self) -> float:
  254. """
  255. MDMCFG4.CHANBW_E & MDMCFG4.CHANBW_M
  256. > [...] decimation ratio for the delta-sigma ADC input stream
  257. > and thus the channel bandwidth.
  258. See "13 Receiver Channel Filter Bandwidth"
  259. """
  260. mdmcfg4 = self._read_single_byte(ConfigurationRegisterAddress.MDMCFG4)
  261. return self._filter_bandwidth_floating_point_to_real(
  262. exponent=mdmcfg4 >> 6, mantissa=(mdmcfg4 >> 4) & 0b11
  263. )
  264. def _set_filter_bandwidth(self, *, mantissa: int, exponent: int) -> None:
  265. """
  266. MDMCFG4.CHANBW_E & MDMCFG4.CHANBW_M
  267. """
  268. mdmcfg4 = self._read_single_byte(ConfigurationRegisterAddress.MDMCFG4)
  269. mdmcfg4 &= 0b00001111
  270. assert 0 <= exponent <= 0b11, exponent
  271. mdmcfg4 |= exponent << 6
  272. assert 0 <= mantissa <= 0b11, mantissa
  273. mdmcfg4 |= mantissa << 4
  274. self._write_burst(
  275. start_register=ConfigurationRegisterAddress.MDMCFG4, values=[mdmcfg4]
  276. )
  277. def _get_symbol_rate_exponent(self) -> int:
  278. """
  279. MDMCFG4.DRATE_E
  280. """
  281. return self._read_single_byte(ConfigurationRegisterAddress.MDMCFG4) & 0b00001111
  282. def _set_symbol_rate_exponent(self, exponent: int):
  283. mdmcfg4 = self._read_single_byte(ConfigurationRegisterAddress.MDMCFG4)
  284. mdmcfg4 &= 0b11110000
  285. mdmcfg4 |= exponent
  286. self._write_burst(
  287. start_register=ConfigurationRegisterAddress.MDMCFG4, values=[mdmcfg4]
  288. )
  289. def _get_symbol_rate_mantissa(self) -> int:
  290. """
  291. MDMCFG3.DRATE_M
  292. """
  293. return self._read_single_byte(ConfigurationRegisterAddress.MDMCFG3)
  294. def _set_symbol_rate_mantissa(self, mantissa: int) -> None:
  295. self._write_burst(
  296. start_register=ConfigurationRegisterAddress.MDMCFG3, values=[mantissa]
  297. )
  298. @classmethod
  299. def _symbol_rate_floating_point_to_real(cls, mantissa: int, exponent: int) -> float:
  300. # see "12 Data Rate Programming"
  301. return (
  302. (256 + mantissa)
  303. * (2 ** exponent)
  304. * cls._CRYSTAL_OSCILLATOR_FREQUENCY_HERTZ
  305. / (2 ** 28)
  306. )
  307. @classmethod
  308. def _symbol_rate_real_to_floating_point(cls, real: float) -> typing.Tuple[int, int]:
  309. # see "12 Data Rate Programming"
  310. assert real > 0, real
  311. exponent = math.floor(
  312. math.log2(real / cls._CRYSTAL_OSCILLATOR_FREQUENCY_HERTZ) + 20
  313. )
  314. mantissa = round(
  315. real * 2 ** 28 / cls._CRYSTAL_OSCILLATOR_FREQUENCY_HERTZ / 2 ** exponent
  316. - 256
  317. )
  318. if mantissa == 256:
  319. exponent += 1
  320. mantissa = 0
  321. assert 0 < exponent <= 2 ** 4, exponent
  322. assert mantissa <= 2 ** 8, mantissa
  323. return mantissa, exponent
  324. def get_symbol_rate_baud(self) -> float:
  325. return self._symbol_rate_floating_point_to_real(
  326. mantissa=self._get_symbol_rate_mantissa(),
  327. exponent=self._get_symbol_rate_exponent(),
  328. )
  329. def set_symbol_rate_baud(self, real: float) -> None:
  330. # > The data rate can be set from 0.6 kBaud to 500 kBaud [...]
  331. mantissa, exponent = self._symbol_rate_real_to_floating_point(real)
  332. self._set_symbol_rate_mantissa(mantissa)
  333. self._set_symbol_rate_exponent(exponent)
  334. def get_modulation_format(self) -> ModulationFormat:
  335. mdmcfg2 = self._read_single_byte(ConfigurationRegisterAddress.MDMCFG2)
  336. return ModulationFormat((mdmcfg2 >> 4) & 0b111)
  337. def _set_modulation_format(self, modulation_format: ModulationFormat) -> None:
  338. mdmcfg2 = self._read_single_byte(ConfigurationRegisterAddress.MDMCFG2)
  339. mdmcfg2 &= 0b10001111
  340. mdmcfg2 |= modulation_format << 4
  341. self._write_burst(ConfigurationRegisterAddress.MDMCFG2, [mdmcfg2])
  342. def enable_manchester_code(self) -> None:
  343. """
  344. MDMCFG2.MANCHESTER_EN
  345. Enable manchester encoding & decoding for the entire packet,
  346. including the preamble and synchronization word.
  347. """
  348. mdmcfg2 = self._read_single_byte(ConfigurationRegisterAddress.MDMCFG2)
  349. mdmcfg2 |= 0b1000
  350. self._write_burst(ConfigurationRegisterAddress.MDMCFG2, [mdmcfg2])
  351. def get_sync_mode(self) -> SyncMode:
  352. mdmcfg2 = self._read_single_byte(ConfigurationRegisterAddress.MDMCFG2)
  353. return SyncMode(mdmcfg2 & 0b11)
  354. def set_sync_mode(
  355. self,
  356. mode: SyncMode,
  357. *,
  358. _carrier_sense_threshold_enabled: typing.Optional[bool] = None # unstable
  359. ) -> None:
  360. """
  361. MDMCFG2.SYNC_MODE
  362. see "14.3 Byte Synchronization"
  363. Carrier Sense (CS) Threshold (when receiving packets, API unstable):
  364. > Carrier sense can be used as a sync word qualifier
  365. > that requires the signal level to be higher than the threshold
  366. > for a sync word > search to be performed [...]
  367. > CS can be used to avoid interference from other RF sources [...]
  368. True: enable, False: disable, None: keep current setting
  369. See "17.4 Carrier Sense (CS)"
  370. """
  371. mdmcfg2 = self._read_single_byte(ConfigurationRegisterAddress.MDMCFG2)
  372. mdmcfg2 &= 0b11111100
  373. mdmcfg2 |= mode
  374. if _carrier_sense_threshold_enabled is not None:
  375. if _carrier_sense_threshold_enabled:
  376. mdmcfg2 |= 0b00000100
  377. else:
  378. mdmcfg2 &= 0b11111011
  379. self._write_burst(ConfigurationRegisterAddress.MDMCFG2, [mdmcfg2])
  380. def get_preamble_length_bytes(self) -> int:
  381. """
  382. MDMCFG1.NUM_PREAMBLE
  383. Minimum number of preamble bytes to be transmitted.
  384. See "15.2 Packet Format"
  385. """
  386. index = (
  387. self._read_single_byte(ConfigurationRegisterAddress.MDMCFG1) >> 4
  388. ) & 0b111
  389. return 2 ** (index >> 1) * (2 + (index & 0b1))
  390. def _set_preamble_length_index(self, index: int) -> None:
  391. assert 0 <= index <= 0b111
  392. mdmcfg1 = self._read_single_byte(ConfigurationRegisterAddress.MDMCFG1)
  393. mdmcfg1 &= 0b10001111
  394. mdmcfg1 |= index << 4
  395. self._write_burst(ConfigurationRegisterAddress.MDMCFG1, [mdmcfg1])
  396. def set_preamble_length_bytes(self, length: int) -> None:
  397. """
  398. see .get_preamble_length_bytes()
  399. """
  400. if length < 1:
  401. raise ValueError(
  402. "invalid preamble length {} given".format(length)
  403. + "\ncall .set_sync_mode(cc1101.SyncMode.NO_PREAMBLE_AND_SYNC_WORD)"
  404. + " to disable preamble"
  405. )
  406. if length % 3 == 0:
  407. index = math.log2(length / 3) * 2 + 1
  408. else:
  409. index = math.log2(length / 2) * 2
  410. if not index.is_integer() or index < 0 or index > 0b111:
  411. raise ValueError(
  412. "unsupported preamble length: {} bytes".format(length)
  413. + "\nsee MDMCFG1.NUM_PREAMBLE in cc1101 docs"
  414. )
  415. self._set_preamble_length_index(int(index))
  416. def _get_power_amplifier_setting_index(self) -> int:
  417. """
  418. see ._set_power_amplifier_setting_index
  419. """
  420. return self._read_single_byte(ConfigurationRegisterAddress.FREND0) & 0b111
  421. def _set_power_amplifier_setting_index(self, setting_index: int) -> None:
  422. """
  423. FREND0.PA_POWER
  424. > This value is an index to the PATABLE,
  425. > which can be programmed with up to 8 different PA settings.
  426. > In OOK/ASK mode, this selects the PATABLE index to use
  427. > when transmitting a '1'.
  428. > PATABLE index zero is used in OOK/ASK when transmitting a '0'.
  429. > The PATABLE settings from index 0 to the PA_POWER value are
  430. > used for > ASK TX shaping, [...]
  431. see "Figure 32: Shaping of ASK Signal"
  432. > If OOK modulation is used, the logic 0 and logic 1 power levels
  433. > shall be programmed to index 0 and 1 respectively.
  434. """
  435. assert 0 <= setting_index <= 0b111, setting_index
  436. frend0 = self._read_single_byte(ConfigurationRegisterAddress.FREND0)
  437. frend0 &= 0b11111000
  438. frend0 |= setting_index
  439. self._write_burst(ConfigurationRegisterAddress.FREND0, [frend0])
  440. def _verify_chip(self) -> None:
  441. partnum = self._read_status_register(StatusRegisterAddress.PARTNUM)
  442. if partnum != self._SUPPORTED_PARTNUM:
  443. raise ValueError(
  444. "unexpected chip part number {} (expected: {})".format(
  445. partnum, self._SUPPORTED_PARTNUM
  446. )
  447. )
  448. version = self._read_status_register(StatusRegisterAddress.VERSION)
  449. if version not in self._SUPPORTED_VERSIONS:
  450. msg = "Unsupported chip version 0x{:02x} (expected one of [{}])".format(
  451. version,
  452. ", ".join("0x{:02x}".format(v) for v in self._SUPPORTED_VERSIONS),
  453. )
  454. if version == 0:
  455. msg += (
  456. "\n\nPlease verify that all required pins are connected"
  457. " (see https://github.com/fphammerle/python-cc1101#wiring-raspberry-pi)"
  458. " and that you selected the correct SPI bus and chip/slave select line."
  459. )
  460. raise ValueError(msg)
  461. def _configure_defaults(self) -> None:
  462. # next major/breaking release will probably stick closer to CC1101's defaults
  463. # 6:4 MOD_FORMAT: OOK (default: 2-FSK)
  464. self._set_modulation_format(ModulationFormat.ASK_OOK)
  465. self._set_power_amplifier_setting_index(1)
  466. self._disable_data_whitening()
  467. # 7:6 unused
  468. # 5:4 FS_AUTOCAL: calibrate when going from IDLE to RX or TX
  469. # 3:2 PO_TIMEOUT: default
  470. # 1 PIN_CTRL_EN: default
  471. # 0 XOSC_FORCE_ON: default
  472. self._write_burst(ConfigurationRegisterAddress.MCSM0, [0b010100])
  473. # > Default is CLK_XOSC/192 (See Table 41 on page 62).
  474. # > It is recommended to disable the clock output in initialization,
  475. # > in order to optimize RF performance.
  476. self._write_burst(
  477. ConfigurationRegisterAddress.IOCFG0,
  478. # required for _wait_for_packet()
  479. [GDOSignalSelection.RX_FIFO_AT_OR_ABOVE_THRESHOLD_OR_PACKET_END_REACHED],
  480. )
  481. def __enter__(self) -> "CC1101":
  482. # https://docs.python.org/3/reference/datamodel.html#object.__enter__
  483. try:
  484. self._spi.open(self._spi_bus, self._spi_chip_select)
  485. except PermissionError as exc:
  486. raise PermissionError(
  487. "Could not access {}".format(self._spi_device_path)
  488. + "\nVerify that the current user has both read and write access."
  489. + "\nOn some systems, like Raspberry Pi OS / Raspbian,"
  490. + "\n\tsudo usermod -a -G spi $USER"
  491. + "\nfollowed by a re-login grants sufficient permissions."
  492. ) from exc
  493. if self._lock_spi_device:
  494. # advisory, exclusive, non-blocking
  495. # lock removed in __exit__ by SpiDev.close()
  496. fcntl.flock(self._spi.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
  497. try:
  498. self._spi.max_speed_hz = 55700 # empirical
  499. self._reset()
  500. self._verify_chip()
  501. self._configure_defaults()
  502. marcstate = self.get_main_radio_control_state_machine_state()
  503. if marcstate != MainRadioControlStateMachineState.IDLE:
  504. raise ValueError(
  505. "expected marcstate idle (actual: {})".format(marcstate.name)
  506. )
  507. except:
  508. self._spi.close()
  509. raise
  510. return self
  511. def __exit__(self, exc_type, exc_value, traceback): # -> typing.Literal[False]
  512. # https://docs.python.org/3/reference/datamodel.html#object.__exit__
  513. self._spi.close()
  514. return False
  515. def unlock_spi_device(self) -> None:
  516. """
  517. Manually release the lock set on the SPI device file.
  518. Alternatively, the lock will be released automatically,
  519. when leaving the context.
  520. Method fails silently, if the SPI device file is not locked.
  521. >>> transceiver = cc1101.CC1101(lock_spi_device=True)
  522. >>> # not locked
  523. >>> with transceiver:
  524. >>> # locked
  525. >>> # lock removed
  526. >>> with transceiver:
  527. >>> # locked
  528. >>> transceiver.unlock_spi_device()
  529. >>> # lock removed
  530. """
  531. fileno = self._spi.fileno()
  532. if fileno != -1:
  533. fcntl.flock(fileno, fcntl.LOCK_UN)
  534. def get_main_radio_control_state_machine_state(
  535. self,
  536. ) -> MainRadioControlStateMachineState:
  537. return MainRadioControlStateMachineState(
  538. self._read_status_register(StatusRegisterAddress.MARCSTATE)
  539. )
  540. def get_marc_state(self) -> MainRadioControlStateMachineState:
  541. """
  542. alias for get_main_radio_control_state_machine_state()
  543. """
  544. return self.get_main_radio_control_state_machine_state()
  545. @classmethod
  546. def _frequency_control_word_to_hertz(cls, control_word: typing.List[int]) -> float:
  547. return (
  548. int.from_bytes(control_word, byteorder="big", signed=False)
  549. * cls._FREQUENCY_CONTROL_WORD_HERTZ_FACTOR
  550. )
  551. @classmethod
  552. def _hertz_to_frequency_control_word(cls, hertz: float) -> typing.List[int]:
  553. return list(
  554. round(hertz / cls._FREQUENCY_CONTROL_WORD_HERTZ_FACTOR).to_bytes(
  555. length=3, byteorder="big", signed=False
  556. )
  557. )
  558. def _get_base_frequency_control_word(self) -> typing.List[int]:
  559. # > The base or start frequency is set by the 24 bitfrequency
  560. # > word located in the FREQ2, FREQ1, FREQ0 registers.
  561. return self._read_burst(
  562. start_register=ConfigurationRegisterAddress.FREQ2, length=3
  563. )
  564. def _set_base_frequency_control_word(self, control_word: typing.List[int]) -> None:
  565. self._write_burst(
  566. start_register=ConfigurationRegisterAddress.FREQ2, values=control_word
  567. )
  568. def get_base_frequency_hertz(self) -> float:
  569. return self._frequency_control_word_to_hertz(
  570. self._get_base_frequency_control_word()
  571. )
  572. def set_base_frequency_hertz(self, freq: float) -> None:
  573. if freq < (self._TRANSMIT_MIN_FREQUENCY_HERTZ - 50e3):
  574. # > [use] warnings.warn() in library code if the issue is avoidable
  575. # > and the client application should be modified to eliminate the warning[.]
  576. # > [use] logging.warning() if there is nothing the client application
  577. # > can do about the situation, but the event should still be noted.
  578. # https://docs.python.org/3/howto/logging.html#when-to-use-logging
  579. warnings.warn(
  580. "CC1101 is unable to transmit at frequencies below {:.1f} MHz".format(
  581. self._TRANSMIT_MIN_FREQUENCY_HERTZ / 1e6
  582. )
  583. )
  584. self._set_base_frequency_control_word(
  585. self._hertz_to_frequency_control_word(freq)
  586. )
  587. def __str__(self) -> str:
  588. sync_mode = self.get_sync_mode()
  589. attrs = (
  590. "marcstate={}".format(
  591. self.get_main_radio_control_state_machine_state().name.lower()
  592. ),
  593. "base_frequency={:.2f}MHz".format(
  594. self.get_base_frequency_hertz() / 10 ** 6
  595. ),
  596. "symbol_rate={:.2f}kBaud".format(self.get_symbol_rate_baud() / 1000),
  597. "modulation_format={}".format(self.get_modulation_format().name),
  598. "sync_mode={}".format(sync_mode.name),
  599. "preamble_length={}B".format(self.get_preamble_length_bytes())
  600. if sync_mode != SyncMode.NO_PREAMBLE_AND_SYNC_WORD
  601. else None,
  602. "sync_word=0x{}".format(self.get_sync_word().hex())
  603. if sync_mode != SyncMode.NO_PREAMBLE_AND_SYNC_WORD
  604. else None,
  605. "packet_length{}{}B".format(
  606. "≤"
  607. if self.get_packet_length_mode() == PacketLengthMode.VARIABLE
  608. else "=",
  609. self.get_packet_length_bytes(),
  610. ),
  611. "output_power={}".format(
  612. _format_patable(self.get_output_power(), insert_spaces=False)
  613. ),
  614. )
  615. return "CC1101({})".format(", ".join(filter(None, attrs)))
  616. def get_configuration_register_values(
  617. self,
  618. start_register: ConfigurationRegisterAddress = min(
  619. ConfigurationRegisterAddress
  620. ),
  621. end_register: ConfigurationRegisterAddress = max(ConfigurationRegisterAddress),
  622. ) -> typing.Dict[ConfigurationRegisterAddress, int]:
  623. assert start_register <= end_register, (start_register, end_register)
  624. values = self._read_burst(
  625. start_register=start_register, length=end_register - start_register + 1
  626. )
  627. return {
  628. ConfigurationRegisterAddress(start_register + i): v
  629. for i, v in enumerate(values)
  630. }
  631. def get_sync_word(self) -> bytes:
  632. """
  633. SYNC1 & SYNC0
  634. See "15.2 Packet Format"
  635. The first byte's most significant bit is transmitted first.
  636. """
  637. return bytes(
  638. self._read_burst(
  639. start_register=ConfigurationRegisterAddress.SYNC1, length=2
  640. )
  641. )
  642. def set_sync_word(self, sync_word: bytes) -> None:
  643. """
  644. See .set_sync_word()
  645. """
  646. if len(sync_word) != 2:
  647. raise ValueError("expected two bytes, got {!r}".format(sync_word))
  648. self._write_burst(
  649. start_register=ConfigurationRegisterAddress.SYNC1, values=list(sync_word)
  650. )
  651. def get_packet_length_bytes(self) -> int:
  652. """
  653. PKTLEN
  654. Packet length in fixed packet length mode,
  655. maximum packet length in variable packet length mode.
  656. > In variable packet length mode, [...]
  657. > any packet received with a length byte
  658. > with a value greater than PKTLEN will be discarded.
  659. """
  660. return self._read_single_byte(ConfigurationRegisterAddress.PKTLEN)
  661. def set_packet_length_bytes(self, packet_length: int) -> None:
  662. """
  663. see get_packet_length_bytes()
  664. """
  665. assert 1 <= packet_length <= 255, "unsupported packet length {}".format(
  666. packet_length
  667. )
  668. self._write_burst(
  669. start_register=ConfigurationRegisterAddress.PKTLEN, values=[packet_length]
  670. )
  671. def _disable_data_whitening(self):
  672. """
  673. PKTCTRL0.WHITE_DATA
  674. see "15.1 Data Whitening"
  675. > By setting PKTCTRL0.WHITE_DATA=1 [default],
  676. > all data, except the preamble and the sync word
  677. > will be XOR-ed with a 9-bit pseudo-random (PN9)
  678. > sequence before being transmitted.
  679. """
  680. pktctrl0 = self._read_single_byte(ConfigurationRegisterAddress.PKTCTRL0)
  681. pktctrl0 &= 0b10111111
  682. self._write_burst(
  683. start_register=ConfigurationRegisterAddress.PKTCTRL0, values=[pktctrl0]
  684. )
  685. def disable_checksum(self) -> None:
  686. """
  687. PKTCTRL0.CRC_EN
  688. Disable automatic 2-byte cyclic redundancy check (CRC) sum
  689. appending in TX mode and checking in RX mode.
  690. See "Figure 19: Packet Format".
  691. """
  692. pktctrl0 = self._read_single_byte(ConfigurationRegisterAddress.PKTCTRL0)
  693. pktctrl0 &= 0b11111011
  694. self._write_burst(
  695. start_register=ConfigurationRegisterAddress.PKTCTRL0, values=[pktctrl0]
  696. )
  697. def _get_transceive_mode(self) -> _TransceiveMode:
  698. pktctrl0 = self._read_single_byte(ConfigurationRegisterAddress.PKTCTRL0)
  699. return _TransceiveMode((pktctrl0 >> 4) & 0b11)
  700. def _set_transceive_mode(self, mode: _TransceiveMode) -> None:
  701. _LOGGER.info("changing transceive mode to %s", mode.name)
  702. pktctrl0 = self._read_single_byte(ConfigurationRegisterAddress.PKTCTRL0)
  703. pktctrl0 &= ~0b00110000
  704. pktctrl0 |= mode << 4
  705. self._write_burst(
  706. start_register=ConfigurationRegisterAddress.PKTCTRL0, values=[pktctrl0]
  707. )
  708. def get_packet_length_mode(self) -> PacketLengthMode:
  709. pktctrl0 = self._read_single_byte(ConfigurationRegisterAddress.PKTCTRL0)
  710. return PacketLengthMode(pktctrl0 & 0b11)
  711. def set_packet_length_mode(self, mode: PacketLengthMode) -> None:
  712. pktctrl0 = self._read_single_byte(ConfigurationRegisterAddress.PKTCTRL0)
  713. pktctrl0 &= 0b11111100
  714. pktctrl0 |= mode
  715. self._write_burst(
  716. start_register=ConfigurationRegisterAddress.PKTCTRL0, values=[pktctrl0]
  717. )
  718. def _get_patable(self) -> typing.Tuple[int, ...]:
  719. """
  720. see "10.6 PATABLE Access" and "24 Output Power Programming"
  721. default: (0xC6, 0, 0, 0, 0, 0, 0, 0)
  722. """
  723. return tuple(
  724. self._read_burst(
  725. start_register=PatableAddress.PATABLE, length=self._PATABLE_LENGTH_BYTES
  726. )
  727. )
  728. def _set_patable(self, settings: typing.Iterable[int]):
  729. settings = list(settings)
  730. assert all(0 <= l <= 0xFF for l in settings), settings
  731. assert 0 < len(settings) <= self._PATABLE_LENGTH_BYTES, settings
  732. self._write_burst(start_register=PatableAddress.PATABLE, values=settings)
  733. def get_output_power(self) -> typing.Tuple[int, ...]:
  734. """
  735. Returns the enabled output power settings
  736. (up to 8 bytes of the PATABLE register).
  737. see .set_output_power()
  738. """
  739. return self._get_patable()[: self._get_power_amplifier_setting_index() + 1]
  740. def set_output_power(self, power_settings: typing.Iterable[int]) -> None:
  741. """
  742. Configures output power levels by setting PATABLE and FREND0.PA_POWER.
  743. Up to 8 bytes may be provided.
  744. > [PATABLE] provides flexible PA power ramp up and ramp down
  745. > at the start and end of transmission when using 2-FSK, GFSK,
  746. > 4-FSK, and MSK modulation as well as ASK modulation shaping.
  747. For OOK modulation, exactly 2 bytes must be provided:
  748. 0 to turn off the transmission for logical 0,
  749. and a level > 0 to turn on the transmission for logical 1.
  750. >>> transceiver.set_output_power((0, 0xC6))
  751. See "Table 39: Optimum PATABLE Settings for Various Output Power Levels [...]"
  752. and section "24 Output Power Programming".
  753. """
  754. power_settings = list(power_settings)
  755. # checks in sub-methods
  756. self._set_power_amplifier_setting_index(len(power_settings) - 1)
  757. self._set_patable(power_settings)
  758. def _flush_tx_fifo_buffer(self) -> None:
  759. # > Only issue SFTX in IDLE or TXFIFO_UNDERFLOW states.
  760. _LOGGER.debug("flushing tx fifo buffer")
  761. self._command_strobe(StrobeAddress.SFTX)
  762. def transmit(self, payload: bytes) -> None:
  763. """
  764. The most significant bit is transmitted first.
  765. In variable packet length mode,
  766. a byte indicating the packet's length will be prepended.
  767. > In variable packet length mode,
  768. > the packet length is configured by the first byte [...].
  769. > The packet length is defined as the payload data,
  770. > excluding the length byte and the optional CRC.
  771. from "15.2 Packet Format"
  772. Call .set_packet_length_mode(cc1101.PacketLengthMode.FIXED)
  773. to switch to fixed packet length mode.
  774. """
  775. # see "15.2 Packet Format"
  776. # > In variable packet length mode, [...]
  777. # > The first byte written to the TXFIFO must be different from 0.
  778. packet_length_mode = self.get_packet_length_mode()
  779. packet_length = self.get_packet_length_bytes()
  780. if packet_length_mode == PacketLengthMode.VARIABLE:
  781. if not payload:
  782. raise ValueError("empty payload {!r}".format(payload))
  783. if len(payload) > packet_length:
  784. raise ValueError(
  785. "payload exceeds maximum payload length of {} bytes".format(
  786. packet_length
  787. )
  788. + "\nsee .get_packet_length_bytes()"
  789. + "\npayload: {!r}".format(payload)
  790. )
  791. payload = int.to_bytes(len(payload), length=1, byteorder="big") + payload
  792. elif (
  793. packet_length_mode == PacketLengthMode.FIXED
  794. and len(payload) != packet_length
  795. ):
  796. raise ValueError(
  797. "expected payload length of {} bytes, got {}".format(
  798. packet_length, len(payload)
  799. )
  800. + "\nsee .set_packet_length_mode() and .get_packet_length_bytes()"
  801. + "\npayload: {!r}".format(payload)
  802. )
  803. marcstate = self.get_main_radio_control_state_machine_state()
  804. if marcstate != MainRadioControlStateMachineState.IDLE:
  805. raise Exception(
  806. "device must be idle before transmission (current marcstate: {})".format(
  807. marcstate.name
  808. )
  809. )
  810. self._flush_tx_fifo_buffer()
  811. self._write_burst(FIFORegisterAddress.TX, list(payload))
  812. _LOGGER.info("transmitting 0x%s (%r)", payload.hex(), payload)
  813. self._command_strobe(StrobeAddress.STX)
  814. @contextlib.contextmanager
  815. def asynchronous_transmission(self) -> typing.Iterator[Pin]:
  816. """
  817. > [...] the GDO0 pin is used for data input [...]
  818. > The CC1101 modulator samples the level of the asynchronous input
  819. > 8 times faster than the programmed data rate.
  820. see "27.1 Asynchronous Serial Operation"
  821. >>> with cc1101.CC1101() as transceiver:
  822. >>> transceiver.set_base_frequency_hertz(433.92e6)
  823. >>> transceiver.set_symbol_rate_baud(600)
  824. >>> print(transceiver)
  825. >>> with transceiver.asynchronous_transmission():
  826. >>> # send digital signal to GDO0 pin
  827. """
  828. self._set_transceive_mode(_TransceiveMode.ASYNCHRONOUS_SERIAL)
  829. self._command_strobe(StrobeAddress.STX)
  830. try:
  831. # > In TX, the GDO0 pin is used for data input (TX data).
  832. yield Pin.GDO0
  833. finally:
  834. self._command_strobe(StrobeAddress.SIDLE)
  835. self._set_transceive_mode(_TransceiveMode.FIFO)
  836. def _enable_receive_mode(self) -> None:
  837. self._command_strobe(StrobeAddress.SRX)
  838. def _get_received_packet(self) -> typing.Optional[_ReceivedPacket]: # unstable
  839. """
  840. see section "20 Data FIFO"
  841. """
  842. rxbytes = self._read_status_register(StatusRegisterAddress.RXBYTES)
  843. # PKTCTRL1.APPEND_STATUS is enabled by default
  844. if rxbytes < 2:
  845. return None
  846. buffer = self._read_burst(start_register=FIFORegisterAddress.RX, length=rxbytes)
  847. return _ReceivedPacket(
  848. payload=bytes(buffer[:-2]),
  849. rssi_index=buffer[-2],
  850. checksum_valid=bool(buffer[-1] >> 7),
  851. link_quality_indicator=buffer[-1] & 0b0111111,
  852. )
  853. def _wait_for_packet( # unstable
  854. self,
  855. timeout: datetime.timedelta,
  856. # https://github.com/hhk7734/python3-gpiod/blob/v1.5.0/py_src/gpiod/libgpiodcxx/__init__.py#L83
  857. gdo0_chip: cc1101._gpio.ChipSelector = 0,
  858. gdo0_line_name: str = "GPIO24", # recommended in README.md
  859. ) -> typing.Optional[_ReceivedPacket]:
  860. """
  861. depends on IOCFG0 == 0b00000001 (see _configure_defaults)
  862. """
  863. # pylint: disable=protected-access
  864. gdo0_line = cc1101._gpio.get_line(
  865. chip_selector=gdo0_chip, line_name=gdo0_line_name
  866. )
  867. import gpiod # pylint: disable=import-outside-toplevel; see get_line()
  868. # https://github.com/hhk7734/python3-gpiod/blob/v1.2.1/py_src/gpiod/test/button.py#L33
  869. gdo0_line_request = gpiod.line_request()
  870. gdo0_line_request.consumer = "python cc1101 {}".format(
  871. self._wait_for_packet.__name__
  872. )
  873. gdo0_line_request.request_type = gpiod.line_request.EVENT_RISING_EDGE
  874. gdo0_line.request(gdo0_line_request)
  875. self._enable_receive_mode()
  876. if not gdo0_line.event_wait(timeout=timeout):
  877. return None # timeout
  878. return self._get_received_packet()