__init__.py 33 KB

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