__init__.py 30 KB

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