__init__.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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 CC1101:
  56. # > All transfers on the SPI interface are done
  57. # > most significant bit first.
  58. # > All transactions on the SPI interface start with
  59. # > a header byte containing a R/W bit, a access bit (B),
  60. # > and a 6-bit address (A5 - A0).
  61. # > [...]
  62. # > Table 45: SPI Address Space
  63. _WRITE_SINGLE_BYTE = 0x00
  64. # > Registers with consecutive addresses can be
  65. # > accessed in an efficient way by setting the
  66. # > burst bit (B) in the header byte. The address
  67. # > bits (A5 - A0) set the start address in an
  68. # > internal address counter. This counter is
  69. # > incremented by one each new byte [...]
  70. _WRITE_BURST = 0x40
  71. _READ_SINGLE_BYTE = 0x80
  72. _READ_BURST = 0xC0
  73. # 29.3 Status Register Details
  74. _SUPPORTED_PARTNUM = 0
  75. _SUPPORTED_VERSION = 0x14
  76. _CRYSTAL_OSCILLATOR_FREQUENCY_HERTZ = 26e6
  77. # see "21 Frequency Programming"
  78. # > f_carrier = f_XOSC / 2**16 * (FREQ + CHAN * ((256 + CHANSPC_M) * 2**CHANSPC_E-2))
  79. _FREQUENCY_CONTROL_WORD_HERTZ_FACTOR = _CRYSTAL_OSCILLATOR_FREQUENCY_HERTZ / 2 ** 16
  80. def __init__(self) -> None:
  81. self._spi = spidev.SpiDev()
  82. @staticmethod
  83. def _log_chip_status_byte(chip_status: int) -> None:
  84. # see "10.1 Chip Status Byte" & "Table 23: Status Byte Summary"
  85. # > The command strobe registers are accessed by transferring
  86. # > a single header byte [...]. That is, only the R/W̄ bit,
  87. # > the burst access bit (set to 0), and the six address bits [...]
  88. # > The R/W̄ bit can be either one or zero and will determine how the
  89. # > FIFO_BYTES_AVAILABLE field in the status byte should be interpreted.
  90. _LOGGER.debug(
  91. "chip status byte: CHIP_RDYn=%d STATE=%s FIFO_BYTES_AVAILBLE=%d",
  92. chip_status >> 7,
  93. bin((chip_status >> 4) & 0b111),
  94. chip_status & 0b1111,
  95. )
  96. def _read_single_byte(
  97. self, register: typing.Union[ConfigurationRegisterAddress, FIFORegisterAddress]
  98. ) -> int:
  99. response = self._spi.xfer([register | self._READ_SINGLE_BYTE, 0])
  100. assert len(response) == 2, response
  101. self._log_chip_status_byte(response[0])
  102. return response[1]
  103. def _read_burst(
  104. self,
  105. start_register: typing.Union[ConfigurationRegisterAddress, FIFORegisterAddress],
  106. length: int,
  107. ) -> typing.List[int]:
  108. response = self._spi.xfer([start_register | self._READ_BURST] + [0] * length)
  109. assert len(response) == length + 1, response
  110. self._log_chip_status_byte(response[0])
  111. return response[1:]
  112. def _read_status_register(self, register: StatusRegisterAddress) -> int:
  113. # > For register addresses in the range 0x30-0x3D,
  114. # > the burst bit is used to select between
  115. # > status registers when burst bit is one, and
  116. # > between command strobes when burst bit is
  117. # > zero. [...]
  118. # > Because of this, burst access is not available
  119. # > for status registers and they must be accessed
  120. # > one at a time. The status registers can only be
  121. # > read.
  122. response = self._spi.xfer([register | self._READ_BURST, 0])
  123. assert len(response) == 2, response
  124. self._log_chip_status_byte(response[0])
  125. return response[1]
  126. def _command_strobe(self, register: StrobeAddress) -> None:
  127. # see "10.4 Command Strobes"
  128. _LOGGER.debug("sending command strobe 0x%02x", register)
  129. response = self._spi.xfer([register | self._WRITE_SINGLE_BYTE])
  130. assert len(response) == 1, response
  131. self._log_chip_status_byte(response[0])
  132. def _write_burst(
  133. self,
  134. start_register: typing.Union[ConfigurationRegisterAddress, FIFORegisterAddress],
  135. values: typing.List[int],
  136. ) -> None:
  137. _LOGGER.debug(
  138. "writing burst: start_register=0x%02x values=%s", start_register, values
  139. )
  140. response = self._spi.xfer([start_register | self._WRITE_BURST] + values)
  141. assert len(response) == len(values) + 1, response
  142. self._log_chip_status_byte(response[0])
  143. assert all(v == response[0] for v in response[1:]), response
  144. def _reset(self) -> None:
  145. self._command_strobe(StrobeAddress.SRES)
  146. def _get_symbol_rate_exponent(self) -> int:
  147. """
  148. MDMCFG4.DRATE_E
  149. """
  150. return self._read_single_byte(ConfigurationRegisterAddress.MDMCFG4) & 0b00001111
  151. def _set_symbol_rate_exponent(self, exponent: int):
  152. mdmcfg4 = self._read_single_byte(ConfigurationRegisterAddress.MDMCFG4)
  153. mdmcfg4 &= 0b11110000
  154. mdmcfg4 |= exponent
  155. self._write_burst(
  156. start_register=ConfigurationRegisterAddress.MDMCFG4, values=[mdmcfg4]
  157. )
  158. def _get_symbol_rate_mantissa(self) -> int:
  159. """
  160. MDMCFG3.DRATE_M
  161. """
  162. return self._read_single_byte(ConfigurationRegisterAddress.MDMCFG3)
  163. def _set_symbol_rate_mantissa(self, mantissa: int) -> None:
  164. self._write_burst(
  165. start_register=ConfigurationRegisterAddress.MDMCFG3, values=[mantissa]
  166. )
  167. @classmethod
  168. def _symbol_rate_floating_point_to_real(cls, mantissa: int, exponent: int) -> float:
  169. # see "12 Data Rate Programming"
  170. return (
  171. (256 + mantissa)
  172. * (2 ** exponent)
  173. * cls._CRYSTAL_OSCILLATOR_FREQUENCY_HERTZ
  174. / (2 ** 28)
  175. )
  176. @classmethod
  177. def _symbol_rate_real_to_floating_point(cls, real: float) -> typing.Tuple[int, int]:
  178. # see "12 Data Rate Programming"
  179. assert real > 0, real
  180. exponent = math.floor(
  181. math.log2(real / cls._CRYSTAL_OSCILLATOR_FREQUENCY_HERTZ) + 20
  182. )
  183. mantissa = round(
  184. real * 2 ** 28 / cls._CRYSTAL_OSCILLATOR_FREQUENCY_HERTZ / 2 ** exponent
  185. - 256
  186. )
  187. if mantissa == 256:
  188. exponent += 1
  189. mantissa = 0
  190. assert 0 < exponent <= 2 ** 4, exponent
  191. assert mantissa <= 2 ** 8, mantissa
  192. return mantissa, exponent
  193. def get_symbol_rate_baud(self) -> float:
  194. return self._symbol_rate_floating_point_to_real(
  195. mantissa=self._get_symbol_rate_mantissa(),
  196. exponent=self._get_symbol_rate_exponent(),
  197. )
  198. def set_symbol_rate_baud(self, real: float) -> None:
  199. # > The data rate can be set from 0.6 kBaud to 500 kBaud [...]
  200. mantissa, exponent = self._symbol_rate_real_to_floating_point(real)
  201. self._set_symbol_rate_mantissa(mantissa)
  202. self._set_symbol_rate_exponent(exponent)
  203. def get_modulation_format(self) -> ModulationFormat:
  204. mdmcfg2 = self._read_single_byte(ConfigurationRegisterAddress.MDMCFG2)
  205. return ModulationFormat((mdmcfg2 >> 4) & 0b111)
  206. def _set_modulation_format(self, modulation_format: ModulationFormat) -> None:
  207. mdmcfg2 = self._read_single_byte(ConfigurationRegisterAddress.MDMCFG2)
  208. mdmcfg2 &= ~(modulation_format << 4)
  209. mdmcfg2 |= modulation_format << 4
  210. self._write_burst(ConfigurationRegisterAddress.MDMCFG2, [mdmcfg2])
  211. def enable_manchester_code(self) -> None:
  212. """
  213. MDMCFG2.MANCHESTER_EN
  214. Enable manchester encoding & decoding.
  215. """
  216. mdmcfg2 = self._read_single_byte(ConfigurationRegisterAddress.MDMCFG2)
  217. mdmcfg2 |= 0b1000
  218. self._write_burst(ConfigurationRegisterAddress.MDMCFG2, [mdmcfg2])
  219. def get_sync_mode(self) -> SyncMode:
  220. mdmcfg2 = self._read_single_byte(ConfigurationRegisterAddress.MDMCFG2)
  221. return SyncMode(mdmcfg2 & 0b11)
  222. def set_sync_mode(self, mode: SyncMode) -> None:
  223. """
  224. MDMCFG2.SYNC_MODE
  225. see "14.3 Byte Synchronization"
  226. """
  227. mdmcfg2 = self._read_single_byte(ConfigurationRegisterAddress.MDMCFG2)
  228. mdmcfg2 &= 0b11111100
  229. mdmcfg2 |= mode
  230. self._write_burst(ConfigurationRegisterAddress.MDMCFG2, [mdmcfg2])
  231. def _set_power_amplifier_setting_index(self, setting_index: int) -> None:
  232. """
  233. FREND0.PA_POWER
  234. > This value is an index to the PATABLE,
  235. > which can be programmed with up to 8 different PA settings.
  236. > In OOK/ASK mode, this selects the PATABLE index to use
  237. > when transmitting a '1'.
  238. > PATABLE index zero is used in OOK/ASK when transmitting a '0'.
  239. > The PATABLE settings from index 0 to the PA_POWER value are
  240. > used for > ASK TX shaping, [...]
  241. see "Figure 32: Shaping of ASK Signal"
  242. > If OOK modulation is used, the logic 0 and logic 1 power levels
  243. > shall be programmed to index 0 and 1 respectively.
  244. """
  245. frend0 = self._read_single_byte(ConfigurationRegisterAddress.FREND0)
  246. frend0 &= 0b000
  247. frend0 |= setting_index
  248. self._write_burst(ConfigurationRegisterAddress.FREND0, [setting_index])
  249. def __enter__(self) -> "CC1101":
  250. # https://docs.python.org/3/reference/datamodel.html#object.__enter__
  251. self._spi.open(0, 0)
  252. self._spi.max_speed_hz = 55700 # empirical
  253. self._reset()
  254. partnum = self._read_status_register(StatusRegisterAddress.PARTNUM)
  255. if partnum != self._SUPPORTED_PARTNUM:
  256. raise ValueError(
  257. "unexpected chip part number {} (expected: {})".format(
  258. partnum, self._SUPPORTED_PARTNUM
  259. )
  260. )
  261. version = self._read_status_register(StatusRegisterAddress.VERSION)
  262. if version != self._SUPPORTED_VERSION:
  263. raise ValueError(
  264. "unexpected chip version number {} (expected: {})".format(
  265. version, self._SUPPORTED_VERSION
  266. )
  267. )
  268. # 6:4 MOD_FORMAT: OOK (default: 2-FSK)
  269. self._set_modulation_format(ModulationFormat.ASK_OOK)
  270. self._set_power_amplifier_setting_index(1)
  271. self._disable_data_whitening()
  272. # 7:6 unused
  273. # 5:4 FS_AUTOCAL: calibrate when going from IDLE to RX or TX
  274. # 3:2 PO_TIMEOUT: default
  275. # 1 PIN_CTRL_EN: default
  276. # 0 XOSC_FORCE_ON: default
  277. self._write_burst(ConfigurationRegisterAddress.MCSM0, [0b010100])
  278. marcstate = self.get_main_radio_control_state_machine_state()
  279. if marcstate != MainRadioControlStateMachineState.IDLE:
  280. raise ValueError("expected marcstate idle (actual: {})".format(marcstate))
  281. return self
  282. def __exit__(self, exc_type, exc_value, traceback): # -> typing.Literal[False]
  283. # https://docs.python.org/3/reference/datamodel.html#object.__exit__
  284. self._spi.close()
  285. return False
  286. def get_main_radio_control_state_machine_state(
  287. self,
  288. ) -> MainRadioControlStateMachineState:
  289. return MainRadioControlStateMachineState(
  290. self._read_status_register(StatusRegisterAddress.MARCSTATE)
  291. )
  292. def get_marc_state(self) -> MainRadioControlStateMachineState:
  293. """
  294. alias for get_main_radio_control_state_machine_state()
  295. """
  296. return self.get_main_radio_control_state_machine_state()
  297. @classmethod
  298. def _frequency_control_word_to_hertz(cls, control_word: typing.List[int]) -> float:
  299. return (
  300. int.from_bytes(control_word, byteorder="big", signed=False)
  301. * cls._FREQUENCY_CONTROL_WORD_HERTZ_FACTOR
  302. )
  303. @classmethod
  304. def _hertz_to_frequency_control_word(cls, hertz: float) -> typing.List[int]:
  305. return list(
  306. round(hertz / cls._FREQUENCY_CONTROL_WORD_HERTZ_FACTOR).to_bytes(
  307. length=3, byteorder="big", signed=False
  308. )
  309. )
  310. def _get_base_frequency_control_word(self) -> typing.List[int]:
  311. # > The base or start frequency is set by the 24 bitfrequency
  312. # > word located in the FREQ2, FREQ1, FREQ0 registers.
  313. return self._read_burst(
  314. start_register=ConfigurationRegisterAddress.FREQ2, length=3
  315. )
  316. def _set_base_frequency_control_word(self, control_word: typing.List[int]) -> None:
  317. self._write_burst(
  318. start_register=ConfigurationRegisterAddress.FREQ2, values=control_word
  319. )
  320. def get_base_frequency_hertz(self) -> float:
  321. return self._frequency_control_word_to_hertz(
  322. self._get_base_frequency_control_word()
  323. )
  324. def set_base_frequency_hertz(self, freq: float) -> None:
  325. self._set_base_frequency_control_word(
  326. self._hertz_to_frequency_control_word(freq)
  327. )
  328. def __str__(self) -> str:
  329. attrs = (
  330. "marcstate={}".format(
  331. self.get_main_radio_control_state_machine_state().name.lower()
  332. ),
  333. "base_frequency={:.2f}MHz".format(
  334. self.get_base_frequency_hertz() / 10 ** 6
  335. ),
  336. "symbol_rate={:.2f}kBaud".format(self.get_symbol_rate_baud() / 1000),
  337. "modulation_format={}".format(self.get_modulation_format().name),
  338. "sync_mode={}".format(self.get_sync_mode().name),
  339. "packet_length{}{}B".format(
  340. "≤"
  341. if self.get_packet_length_mode() == PacketLengthMode.VARIABLE
  342. else "=",
  343. self.get_packet_length_bytes(),
  344. ),
  345. )
  346. return "CC1101({})".format(", ".join(attrs))
  347. def get_configuration_register_values(
  348. self,
  349. start_register: ConfigurationRegisterAddress = min(
  350. ConfigurationRegisterAddress
  351. ),
  352. end_register: ConfigurationRegisterAddress = max(ConfigurationRegisterAddress),
  353. ) -> typing.Dict[ConfigurationRegisterAddress, int]:
  354. assert start_register <= end_register, (start_register, end_register)
  355. values = self._read_burst(
  356. start_register=start_register, length=end_register - start_register + 1
  357. )
  358. return {
  359. ConfigurationRegisterAddress(start_register + i): v
  360. for i, v in enumerate(values)
  361. }
  362. def get_packet_length_bytes(self) -> int:
  363. """
  364. PKTLEN
  365. Packet length in fixed packet length mode,
  366. maximum packet length in variable packet length mode.
  367. > In variable packet length mode, [...]
  368. > any packet received with a length byte
  369. > with a value greater than PKTLEN will be discarded.
  370. """
  371. return self._read_single_byte(ConfigurationRegisterAddress.PKTLEN)
  372. def set_packet_length_bytes(self, packet_length: int) -> None:
  373. """
  374. see get_packet_length_bytes()
  375. """
  376. assert 1 <= packet_length <= 255, "unsupported packet length {}".format(
  377. packet_length
  378. )
  379. self._write_burst(
  380. start_register=ConfigurationRegisterAddress.PKTLEN, values=[packet_length]
  381. )
  382. def _disable_data_whitening(self):
  383. """
  384. PKTCTRL0.WHITE_DATA
  385. see "15.1 Data Whitening"
  386. > By setting PKTCTRL0.WHITE_DATA=1 [default],
  387. > all data, except the preamble and the sync word
  388. > will be XOR-ed with a 9-bit pseudo-random (PN9)
  389. > sequence before being transmitted.
  390. """
  391. pktctrl0 = self._read_single_byte(ConfigurationRegisterAddress.PKTCTRL0)
  392. pktctrl0 &= 0b10111111
  393. self._write_burst(
  394. start_register=ConfigurationRegisterAddress.PKTCTRL0, values=[pktctrl0]
  395. )
  396. def disable_checksum(self) -> None:
  397. """
  398. PKTCTRL0.CRC_EN
  399. Disable automatic 2-byte cyclic redundancy check (CRC) sum
  400. appending in TX mode and checking in RX mode.
  401. See "Figure 19: Packet Format".
  402. """
  403. pktctrl0 = self._read_single_byte(ConfigurationRegisterAddress.PKTCTRL0)
  404. pktctrl0 &= 0b11111011
  405. self._write_burst(
  406. start_register=ConfigurationRegisterAddress.PKTCTRL0, values=[pktctrl0]
  407. )
  408. def _get_transceive_mode(self) -> _TransceiveMode:
  409. pktctrl0 = self._read_single_byte(ConfigurationRegisterAddress.PKTCTRL0)
  410. return _TransceiveMode((pktctrl0 >> 4) & 0b11)
  411. def _set_transceive_mode(self, mode: _TransceiveMode) -> None:
  412. _LOGGER.info("changing transceive mode to %s", mode.name)
  413. pktctrl0 = self._read_single_byte(ConfigurationRegisterAddress.PKTCTRL0)
  414. pktctrl0 &= ~0b00110000
  415. pktctrl0 |= mode << 4
  416. self._write_burst(
  417. start_register=ConfigurationRegisterAddress.PKTCTRL0, values=[pktctrl0]
  418. )
  419. def get_packet_length_mode(self) -> PacketLengthMode:
  420. pktctrl0 = self._read_single_byte(ConfigurationRegisterAddress.PKTCTRL0)
  421. return PacketLengthMode(pktctrl0 & 0b11)
  422. def set_packet_length_mode(self, mode: PacketLengthMode) -> None:
  423. pktctrl0 = self._read_single_byte(ConfigurationRegisterAddress.PKTCTRL0)
  424. pktctrl0 &= 0b11111100
  425. pktctrl0 |= mode
  426. self._write_burst(
  427. start_register=ConfigurationRegisterAddress.PKTCTRL0, values=[pktctrl0]
  428. )
  429. def _flush_tx_fifo_buffer(self) -> None:
  430. # > Only issue SFTX in IDLE or TXFIFO_UNDERFLOW states.
  431. _LOGGER.debug("flushing tx fifo buffer")
  432. self._command_strobe(StrobeAddress.SFTX)
  433. def transmit(self, payload: bytes) -> None:
  434. """
  435. The most significant bit is transmitted first.
  436. In variable packet length mode,
  437. a byte indicating the packet's length will be prepended.
  438. > In variable packet length mode,
  439. > the packet length is configured by the first byte [...].
  440. > The packet length is defined as the payload data,
  441. > excluding the length byte and the optional CRC.
  442. from "15.2 Packet Format"
  443. Call .set_packet_length_mode(cc1101.PacketLengthMode.FIXED)
  444. to switch to fixed packet length mode.
  445. """
  446. # see "15.2 Packet Format"
  447. # > In variable packet length mode, [...]
  448. # > The first byte written to the TXFIFO must be different from 0.
  449. packet_length_mode = self.get_packet_length_mode()
  450. packet_length = self.get_packet_length_bytes()
  451. if packet_length_mode == PacketLengthMode.VARIABLE:
  452. if not payload:
  453. raise ValueError("empty payload {!r}".format(payload))
  454. if len(payload) > packet_length:
  455. raise ValueError(
  456. "payload exceeds maximum payload length of {} bytes".format(
  457. packet_length
  458. )
  459. + "\nsee .get_packet_length_bytes()"
  460. + "\npayload: {!r}".format(payload)
  461. )
  462. payload = int.to_bytes(len(payload), length=1, byteorder="big") + payload
  463. elif (
  464. packet_length_mode == PacketLengthMode.FIXED
  465. and len(payload) != packet_length
  466. ):
  467. raise ValueError(
  468. "expected payload length of {} bytes, got {}".format(
  469. packet_length, len(payload)
  470. )
  471. + "\nsee .set_packet_length_mode() and .get_packet_length_bytes()"
  472. + "\npayload: {!r}".format(payload)
  473. )
  474. marcstate = self.get_main_radio_control_state_machine_state()
  475. if marcstate != MainRadioControlStateMachineState.IDLE:
  476. raise Exception(
  477. "device must be idle before transmission (current marcstate: {})".format(
  478. marcstate.name
  479. )
  480. )
  481. self._flush_tx_fifo_buffer()
  482. self._write_burst(FIFORegisterAddress.TX, list(payload))
  483. _LOGGER.info(
  484. "transmitting 0x%s (%r)",
  485. "".join("{:02x}".format(b) for b in payload),
  486. payload,
  487. )
  488. self._command_strobe(StrobeAddress.STX)
  489. @contextlib.contextmanager
  490. def asynchronous_transmission(self) -> typing.Iterator[Pin]:
  491. """
  492. see "27.1 Asynchronous Serial Operation"
  493. >>> with cc1101.CC1101() as transceiver:
  494. >>> transceiver.set_base_frequency_hertz(433.92e6)
  495. >>> transceiver.set_symbol_rate_baud(600)
  496. >>> print(transceiver)
  497. >>> with transceiver.asynchronous_transmission():
  498. >>> # send digital signal to GDO0 pin
  499. """
  500. self._set_transceive_mode(_TransceiveMode.ASYNCHRONOUS_SERIAL)
  501. self._command_strobe(StrobeAddress.STX)
  502. try:
  503. # > In TX, the GDO0 pin is used for data input (TX data).
  504. yield Pin.GDO0
  505. finally:
  506. self._command_strobe(StrobeAddress.SIDLE)
  507. self._set_transceive_mode(_TransceiveMode.FIFO)