__init__.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. import contextlib
  2. import enum
  3. import logging
  4. import math
  5. import typing
  6. import spidev
  7. from cc1101.addresses import (
  8. StrobeAddress,
  9. ConfigurationRegisterAddress,
  10. StatusRegisterAddress,
  11. FIFORegisterAddress,
  12. )
  13. _LOGGER = logging.getLogger(__name__)
  14. class CC1101:
  15. # > All transfers on the SPI interface are done
  16. # > most significant bit first.
  17. # > All transactions on the SPI interface start with
  18. # > a header byte containing a R/W bit, a access bit (B),
  19. # > and a 6-bit address (A5 - A0).
  20. # > [...]
  21. # > Table 45: SPI Address Space
  22. _WRITE_SINGLE_BYTE = 0x00
  23. # > Registers with consecutive addresses can be
  24. # > accessed in an efficient way by setting the
  25. # > burst bit (B) in the header byte. The address
  26. # > bits (A5 - A0) set the start address in an
  27. # > internal address counter. This counter is
  28. # > incremented by one each new byte [...]
  29. _WRITE_BURST = 0x40
  30. _READ_SINGLE_BYTE = 0x80
  31. _READ_BURST = 0xC0
  32. class Pin(enum.Enum):
  33. GDO0 = "GDO0"
  34. class _TransceiveMode(enum.IntEnum):
  35. """
  36. PKTCTRL0.PKT_FORMAT
  37. """
  38. FIFO = 0b00
  39. SYNCHRONOUS_SERIAL = 0b01
  40. RANDOM_TRANSMISSION = 0b10
  41. ASYNCHRONOUS_SERIAL = 0b11
  42. class ModulationFormat(enum.IntEnum):
  43. """
  44. MDMCFG2.MOD_FORMAT
  45. """
  46. FSK2 = 0b000
  47. GFSK = 0b001
  48. ASK_OOK = 0b011
  49. FSK4 = 0b100
  50. MSK = 0b111
  51. class MainRadioControlStateMachineState(enum.IntEnum):
  52. """
  53. MARCSTATE - Main Radio Control State Machine State
  54. """
  55. # see "Figure 13: Simplified State Diagram"
  56. # and "Figure 25: Complete Radio Control State Diagram"
  57. IDLE = 0x01
  58. STARTCAL = 0x08 # after IDLE
  59. BWBOOST = 0x09 # after STARTCAL
  60. FS_LOCK = 0x0A
  61. TX = 0x13
  62. # 29.3 Status Register Details
  63. _SUPPORTED_PARTNUM = 0
  64. _SUPPORTED_VERSION = 0x14
  65. _CRYSTAL_OSCILLATOR_FREQUENCY_HERTZ = 26e6
  66. # see "21 Frequency Programming"
  67. # > f_carrier = f_XOSC / 2**16 * (FREQ + CHAN * ((256 + CHANSPC_M) * 2**CHANSPC_E-2))
  68. _FREQUENCY_CONTROL_WORD_HERTZ_FACTOR = _CRYSTAL_OSCILLATOR_FREQUENCY_HERTZ / 2 ** 16
  69. def __init__(self) -> None:
  70. self._spi = spidev.SpiDev()
  71. @staticmethod
  72. def _log_chip_status_byte(chip_status: int) -> None:
  73. # see "10.1 Chip Status Byte" & "Table 23: Status Byte Summary"
  74. _LOGGER.debug(
  75. "chip status byte: CHIP_RDYn=%d STATE=%s FIFO_BYTES_AVAILBLE=%d",
  76. chip_status >> 7,
  77. bin((chip_status >> 4) & 0b111),
  78. chip_status & 0b1111,
  79. )
  80. def _read_single_byte(
  81. self, register: typing.Union[ConfigurationRegisterAddress, FIFORegisterAddress]
  82. ) -> int:
  83. response = self._spi.xfer([register | self._READ_SINGLE_BYTE, 0])
  84. assert len(response) == 2, response
  85. self._log_chip_status_byte(response[0])
  86. return response[1]
  87. def _read_burst(
  88. self,
  89. start_register: typing.Union[ConfigurationRegisterAddress, FIFORegisterAddress],
  90. length: int,
  91. ) -> typing.List[int]:
  92. response = self._spi.xfer([start_register | self._READ_BURST] + [0] * length)
  93. assert len(response) == length + 1, response
  94. self._log_chip_status_byte(response[0])
  95. return response[1:]
  96. def _read_status_register(self, register: StatusRegisterAddress) -> int:
  97. # > For register addresses in the range 0x30-0x3D,
  98. # > the burst bit is used to select between
  99. # > status registers when burst bit is one, and
  100. # > between command strobes when burst bit is
  101. # > zero. [...]
  102. # > Because of this, burst access is not available
  103. # > for status registers and they must be accessed
  104. # > one at a time. The status registers can only be
  105. # > read.
  106. response = self._spi.xfer([register | self._READ_BURST, 0])
  107. assert len(response) == 2, response
  108. self._log_chip_status_byte(response[0])
  109. return response[1]
  110. def _command_strobe(self, register: StrobeAddress) -> None:
  111. # see "10.4 Command Strobes"
  112. _LOGGER.debug("sending command strobe 0x%02x", register)
  113. response = self._spi.xfer([register | self._WRITE_SINGLE_BYTE])
  114. assert len(response) == 1, response
  115. self._log_chip_status_byte(response[0])
  116. def _write_burst(
  117. self,
  118. start_register: typing.Union[ConfigurationRegisterAddress, FIFORegisterAddress],
  119. values: typing.List[int],
  120. ) -> None:
  121. _LOGGER.debug(
  122. "writing burst: start_register=0x%02x values=%s", start_register, values
  123. )
  124. response = self._spi.xfer([start_register | self._WRITE_BURST] + values)
  125. assert len(response) == len(values) + 1, response
  126. self._log_chip_status_byte(response[0])
  127. assert all(v == response[0] for v in response[1:]), response
  128. def _reset(self) -> None:
  129. self._command_strobe(StrobeAddress.SRES)
  130. def _get_symbol_rate_exponent(self) -> int:
  131. """
  132. MDMCFG4.DRATE_E
  133. """
  134. return self._read_single_byte(ConfigurationRegisterAddress.MDMCFG4) & 0b00001111
  135. def _set_symbol_rate_exponent(self, exponent: int):
  136. mdmcfg4 = self._read_single_byte(ConfigurationRegisterAddress.MDMCFG4)
  137. mdmcfg4 &= 0b11110000
  138. mdmcfg4 |= exponent
  139. self._write_burst(
  140. start_register=ConfigurationRegisterAddress.MDMCFG4, values=[mdmcfg4]
  141. )
  142. def _get_symbol_rate_mantissa(self) -> int:
  143. """
  144. MDMCFG3.DRATE_M
  145. """
  146. return self._read_single_byte(ConfigurationRegisterAddress.MDMCFG3)
  147. def _set_symbol_rate_mantissa(self, mantissa: int) -> None:
  148. self._write_burst(
  149. start_register=ConfigurationRegisterAddress.MDMCFG3, values=[mantissa]
  150. )
  151. @classmethod
  152. def _symbol_rate_floating_point_to_real(cls, mantissa: int, exponent: int) -> float:
  153. # see "12 Data Rate Programming"
  154. return (
  155. (256 + mantissa)
  156. * (2 ** exponent)
  157. * cls._CRYSTAL_OSCILLATOR_FREQUENCY_HERTZ
  158. / (2 ** 28)
  159. )
  160. @classmethod
  161. def _symbol_rate_real_to_floating_point(cls, real: float) -> typing.Tuple[int, int]:
  162. # see "12 Data Rate Programming"
  163. assert real > 0, real
  164. exponent = math.floor(
  165. math.log2(real / cls._CRYSTAL_OSCILLATOR_FREQUENCY_HERTZ) + 20
  166. )
  167. mantissa = round(
  168. real * 2 ** 28 / cls._CRYSTAL_OSCILLATOR_FREQUENCY_HERTZ / 2 ** exponent
  169. - 256
  170. )
  171. if mantissa == 256:
  172. exponent += 1
  173. mantissa = 0
  174. assert 0 < exponent <= 2 ** 4, exponent
  175. assert mantissa <= 2 ** 8, mantissa
  176. return mantissa, exponent
  177. def get_symbol_rate_baud(self) -> float:
  178. return self._symbol_rate_floating_point_to_real(
  179. mantissa=self._get_symbol_rate_mantissa(),
  180. exponent=self._get_symbol_rate_exponent(),
  181. )
  182. def set_symbol_rate_baud(self, real: float) -> None:
  183. # > The data rate can be set from 0.6 kBaud to 500 kBaud [...]
  184. mantissa, exponent = self._symbol_rate_real_to_floating_point(real)
  185. self._set_symbol_rate_mantissa(mantissa)
  186. self._set_symbol_rate_exponent(exponent)
  187. def get_modulation_format(self) -> ModulationFormat:
  188. mdmcfg2 = self._read_single_byte(ConfigurationRegisterAddress.MDMCFG2)
  189. return self.ModulationFormat((mdmcfg2 >> 4) & 0b111)
  190. def _set_modulation_format(self, modulation_format: ModulationFormat) -> None:
  191. mdmcfg2 = self._read_single_byte(ConfigurationRegisterAddress.MDMCFG2)
  192. mdmcfg2 &= ~(modulation_format << 4)
  193. mdmcfg2 |= modulation_format << 4
  194. self._write_burst(ConfigurationRegisterAddress.MDMCFG2, [mdmcfg2])
  195. def _set_power_amplifier_setting_index(self, setting_index: int) -> None:
  196. """
  197. FREND0.PA_POWER
  198. > This value is an index to the PATABLE,
  199. > which can be programmed with up to 8 different PA settings.
  200. > In OOK/ASK mode, this selects the PATABLE index to use
  201. > when transmitting a '1'.
  202. > PATABLE index zero is used in OOK/ASK when transmitting a '0'.
  203. > The PATABLE settings from index 0 to the PA_POWER value are
  204. > used for > ASK TX shaping, [...]
  205. see "Figure 32: Shaping of ASK Signal"
  206. > If OOK modulation is used, the logic 0 and logic 1 power levels
  207. > shall be programmed to index 0 and 1 respectively.
  208. """
  209. frend0 = self._read_single_byte(ConfigurationRegisterAddress.FREND0)
  210. frend0 &= 0b000
  211. frend0 |= setting_index
  212. self._write_burst(ConfigurationRegisterAddress.FREND0, [setting_index])
  213. def __enter__(self) -> "CC1101":
  214. # https://docs.python.org/3/reference/datamodel.html#object.__enter__
  215. self._spi.open(0, 0)
  216. self._spi.max_speed_hz = 55700 # empirical
  217. self._reset()
  218. partnum = self._read_status_register(StatusRegisterAddress.PARTNUM)
  219. if partnum != self._SUPPORTED_PARTNUM:
  220. raise ValueError(
  221. "unexpected chip part number {} (expected: {})".format(
  222. partnum, self._SUPPORTED_PARTNUM
  223. )
  224. )
  225. version = self._read_status_register(StatusRegisterAddress.VERSION)
  226. if version != self._SUPPORTED_VERSION:
  227. raise ValueError(
  228. "unexpected chip version number {} (expected: {})".format(
  229. version, self._SUPPORTED_VERSION
  230. )
  231. )
  232. # 6:4 MOD_FORMAT: OOK (default: 2-FSK)
  233. self._set_modulation_format(self.ModulationFormat.ASK_OOK)
  234. self._set_power_amplifier_setting_index(1)
  235. self._disable_data_whitening()
  236. # 7:6 unused
  237. # 5:4 FS_AUTOCAL: calibrate when going from IDLE to RX or TX
  238. # 3:2 PO_TIMEOUT: default
  239. # 1 PIN_CTRL_EN: default
  240. # 0 XOSC_FORCE_ON: default
  241. self._write_burst(ConfigurationRegisterAddress.MCSM0, [0b010100])
  242. marcstate = self.get_main_radio_control_state_machine_state()
  243. if marcstate != self.MainRadioControlStateMachineState.IDLE:
  244. raise ValueError("expected marcstate idle (actual: {})".format(marcstate))
  245. return self
  246. def __exit__(self, exc_type, exc_value, traceback) -> bool:
  247. # https://docs.python.org/3/reference/datamodel.html#object.__exit__
  248. self._spi.close()
  249. return False
  250. def get_main_radio_control_state_machine_state(
  251. self
  252. ) -> MainRadioControlStateMachineState:
  253. return self.MainRadioControlStateMachineState(
  254. self._read_status_register(StatusRegisterAddress.MARCSTATE)
  255. )
  256. def get_marc_state(self) -> MainRadioControlStateMachineState:
  257. """
  258. alias for get_main_radio_control_state_machine_state()
  259. """
  260. return self.get_main_radio_control_state_machine_state()
  261. @classmethod
  262. def _frequency_control_word_to_hertz(cls, control_word: typing.List[int]) -> float:
  263. return (
  264. int.from_bytes(control_word, byteorder="big", signed=False)
  265. * cls._FREQUENCY_CONTROL_WORD_HERTZ_FACTOR
  266. )
  267. @classmethod
  268. def _hertz_to_frequency_control_word(cls, hertz: float) -> typing.List[int]:
  269. return list(
  270. round(hertz / cls._FREQUENCY_CONTROL_WORD_HERTZ_FACTOR).to_bytes(
  271. length=3, byteorder="big", signed=False
  272. )
  273. )
  274. def _get_base_frequency_control_word(self) -> typing.List[int]:
  275. # > The base or start frequency is set by the 24 bitfrequency
  276. # > word located in the FREQ2, FREQ1, FREQ0 registers.
  277. return self._read_burst(
  278. start_register=ConfigurationRegisterAddress.FREQ2, length=3
  279. )
  280. def _set_base_frequency_control_word(self, control_word: typing.List[int]) -> None:
  281. self._write_burst(
  282. start_register=ConfigurationRegisterAddress.FREQ2, values=control_word
  283. )
  284. def get_base_frequency_hertz(self) -> float:
  285. return self._frequency_control_word_to_hertz(
  286. self._get_base_frequency_control_word()
  287. )
  288. def set_base_frequency_hertz(self, freq: float) -> None:
  289. self._set_base_frequency_control_word(
  290. self._hertz_to_frequency_control_word(freq)
  291. )
  292. def __str__(self) -> str:
  293. return "CC1101(marcstate={}, base_frequency={:.2f}MHz, symbol_rate={:.2f}kBaud, modulation_format={})".format(
  294. self.get_main_radio_control_state_machine_state().name.lower(),
  295. self.get_base_frequency_hertz() / 10 ** 6,
  296. self.get_symbol_rate_baud() / 1000,
  297. self.get_modulation_format().name,
  298. )
  299. def _get_packet_length(self) -> int:
  300. """
  301. packet length in fixed packet length mode,
  302. maximum packet length in variable packet length mode.
  303. """
  304. return self._read_single_byte(ConfigurationRegisterAddress.PKTLEN)
  305. def get_configuration_register_values(
  306. self,
  307. start_register: ConfigurationRegisterAddress = min(
  308. ConfigurationRegisterAddress
  309. ),
  310. end_register: ConfigurationRegisterAddress = max(ConfigurationRegisterAddress),
  311. ) -> typing.Dict[ConfigurationRegisterAddress, int]:
  312. assert start_register <= end_register, (start_register, end_register)
  313. values = self._read_burst(
  314. start_register=start_register, length=end_register - start_register + 1
  315. )
  316. return {
  317. ConfigurationRegisterAddress(start_register + i): v
  318. for i, v in enumerate(values)
  319. }
  320. def _disable_data_whitening(self):
  321. """
  322. PKTCTRL0.WHITE_DATA
  323. see "15.1 Data Whitening"
  324. > By setting PKTCTRL0.WHITE_DATA=1 [default],
  325. > all data, except the preamble and the sync word
  326. > will be XOR-ed with a 9-bit pseudo-random (PN9)
  327. > sequence before being transmitted.
  328. """
  329. pktctrl0 = self._read_single_byte(ConfigurationRegisterAddress.PKTCTRL0)
  330. pktctrl0 &= 0b10111111
  331. self._write_burst(
  332. start_register=ConfigurationRegisterAddress.PKTCTRL0, values=[pktctrl0]
  333. )
  334. def _get_transceive_mode(self) -> _TransceiveMode:
  335. pktctrl0 = self._read_single_byte(ConfigurationRegisterAddress.PKTCTRL0)
  336. return self._TransceiveMode((pktctrl0 >> 4) & 0b11)
  337. def _set_transceive_mode(self, mode: _TransceiveMode) -> None:
  338. _LOGGER.info("changing transceive mode to %s", mode.name)
  339. pktctrl0 = self._read_single_byte(ConfigurationRegisterAddress.PKTCTRL0)
  340. pktctrl0 &= ~0b00110000
  341. pktctrl0 |= mode << 4
  342. self._write_burst(
  343. start_register=ConfigurationRegisterAddress.PKTCTRL0, values=[pktctrl0]
  344. )
  345. def _flush_tx_fifo_buffer(self) -> None:
  346. # > Only issue SFTX in IDLE or TXFIFO_UNDERFLOW states.
  347. _LOGGER.debug("flushing tx fifo buffer")
  348. self._command_strobe(StrobeAddress.SFTX)
  349. def transmit(self, payload: typing.List[int]) -> None:
  350. # see "15.2 Packet Format"
  351. # > In variable packet length mode, [...]
  352. # > The first byte written to the TXFIFO must be different from 0.
  353. if payload[0] == 0:
  354. raise ValueError(
  355. "in variable packet length mode the first byte of payload must not be null"
  356. + "\npayload: {}".format(payload)
  357. )
  358. marcstate = self.get_main_radio_control_state_machine_state()
  359. if marcstate != self.MainRadioControlStateMachineState.IDLE:
  360. raise Exception(
  361. "device must be idle before transmission (current marcstate: {})".format(
  362. marcstate.name
  363. )
  364. )
  365. max_packet_length = self._get_packet_length()
  366. if len(payload) > max_packet_length:
  367. raise ValueError(
  368. "payload exceeds maximum payload length of {} bytes".format(
  369. max_packet_length
  370. )
  371. + "\npayload: {}".format(payload)
  372. )
  373. self._flush_tx_fifo_buffer()
  374. self._write_burst(FIFORegisterAddress.TX, payload)
  375. _LOGGER.info("transmitting %s", payload)
  376. self._command_strobe(StrobeAddress.STX)
  377. @contextlib.contextmanager
  378. def asynchronous_transmission(self) -> typing.Iterator[Pin]:
  379. """
  380. see "27.1 Asynchronous Serial Operation"
  381. >>> with cc1101.CC1101() as transceiver:
  382. >>> transceiver.set_base_frequency_hertz(433.92e6)
  383. >>> transceiver.set_symbol_rate_baud(600)
  384. >>> print(transceiver)
  385. >>> with transceiver.asynchronous_transmission():
  386. >>> # send digital signal to GDO0 pin
  387. """
  388. self._set_transceive_mode(self._TransceiveMode.ASYNCHRONOUS_SERIAL)
  389. self._command_strobe(StrobeAddress.STX)
  390. try:
  391. # > In TX, the GDO0 pin is used for data input (TX data).
  392. yield self.Pin.GDO0
  393. finally:
  394. self._command_strobe(StrobeAddress.SIDLE)
  395. self._set_transceive_mode(self._TransceiveMode.FIFO)