__init__.py 34 KB

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