__init__.py 37 KB

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