__init__.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. import enum
  2. import logging
  3. import math
  4. import typing
  5. import spidev
  6. from cc1101.addresses import (
  7. StrobeAddress,
  8. ConfigurationRegisterAddress,
  9. StatusRegisterAddress,
  10. FIFORegisterAddress,
  11. )
  12. _LOGGER = logging.getLogger(__name__)
  13. class CC1101:
  14. # > All transfers on the SPI interface are done
  15. # > most significant bit first.
  16. # > All transactions on the SPI interface start with
  17. # > a header byte containing a R/W bit, a access bit (B),
  18. # > and a 6-bit address (A5 - A0).
  19. # > [...]
  20. # > Table 45: SPI Address Space
  21. _WRITE_SINGLE_BYTE = 0x00
  22. # > Registers with consecutive addresses can be
  23. # > accessed in an efficient way by setting the
  24. # > burst bit (B) in the header byte. The address
  25. # > bits (A5 - A0) set the start address in an
  26. # > internal address counter. This counter is
  27. # > incremented by one each new byte [...]
  28. _WRITE_BURST = 0x40
  29. _READ_SINGLE_BYTE = 0x80
  30. _READ_BURST = 0xC0
  31. class ModulationFormat(enum.IntEnum):
  32. """
  33. MDMCFG2.MOD_FORMAT
  34. """
  35. FSK2 = 0b000
  36. GFSK = 0b001
  37. ASK_OOK = 0b011
  38. FSK4 = 0b100
  39. MSK = 0b111
  40. class MainRadioControlStateMachineState(enum.IntEnum):
  41. """
  42. MARCSTATE - Main Radio Control State Machine State
  43. """
  44. # see "Figure 13: Simplified State Diagram"
  45. # and "Figure 25: Complete Radio Control State Diagram"
  46. IDLE = 0x01
  47. STARTCAL = 0x08 # after IDLE
  48. BWBOOST = 0x09 # after STARTCAL
  49. FS_LOCK = 0x0A
  50. TX = 0x13
  51. # 29.3 Status Register Details
  52. _SUPPORTED_PARTNUM = 0
  53. _SUPPORTED_VERSION = 0x14
  54. _CRYSTAL_OSCILLATOR_FREQUENCY_HERTZ = 26e6
  55. # see "21 Frequency Programming"
  56. # > f_carrier = f_XOSC / 2**16 * (FREQ + CHAN * ((256 + CHANSPC_M) * 2**CHANSPC_E-2))
  57. _FREQUENCY_CONTROL_WORD_HERTZ_FACTOR = _CRYSTAL_OSCILLATOR_FREQUENCY_HERTZ / 2 ** 16
  58. def __init__(self) -> None:
  59. self._spi = spidev.SpiDev()
  60. @staticmethod
  61. def _log_chip_status_byte(chip_status: int) -> None:
  62. # see "10.1 Chip Status Byte" & "Table 23: Status Byte Summary"
  63. _LOGGER.debug(
  64. "chip status byte: CHIP_RDYn=%d STATE=%s FIFO_BYTES_AVAILBLE=%d",
  65. chip_status >> 7,
  66. bin((chip_status >> 4) & 0b111),
  67. chip_status & 0b1111,
  68. )
  69. def _read_single_byte(
  70. self, register: typing.Union[ConfigurationRegisterAddress, FIFORegisterAddress]
  71. ) -> int:
  72. response = self._spi.xfer([register | self._READ_SINGLE_BYTE, 0])
  73. assert len(response) == 2, response
  74. self._log_chip_status_byte(response[0])
  75. return response[1]
  76. def _read_burst(
  77. self,
  78. start_register: typing.Union[ConfigurationRegisterAddress, FIFORegisterAddress],
  79. length: int,
  80. ) -> typing.List[int]:
  81. response = self._spi.xfer([start_register | self._READ_BURST] + [0] * length)
  82. assert len(response) == length + 1, response
  83. self._log_chip_status_byte(response[0])
  84. return response[1:]
  85. def _read_status_register(self, register: StatusRegisterAddress) -> int:
  86. # > For register addresses in the range 0x30-0x3D,
  87. # > the burst bit is used to select between
  88. # > status registers when burst bit is one, and
  89. # > between command strobes when burst bit is
  90. # > zero. [...]
  91. # > Because of this, burst access is not available
  92. # > for status registers and they must be accessed
  93. # > one at a time. The status registers can only be
  94. # > read.
  95. response = self._spi.xfer([register | self._READ_BURST, 0])
  96. assert len(response) == 2, response
  97. self._log_chip_status_byte(response[0])
  98. return response[1]
  99. def _command_strobe(self, register: StrobeAddress) -> None:
  100. # see "10.4 Command Strobes"
  101. _LOGGER.debug("sending command strobe 0x%02x", register)
  102. response = self._spi.xfer([register | self._WRITE_SINGLE_BYTE])
  103. assert len(response) == 1, response
  104. self._log_chip_status_byte(response[0])
  105. def _write_burst(
  106. self,
  107. start_register: typing.Union[ConfigurationRegisterAddress, FIFORegisterAddress],
  108. values: typing.List[int],
  109. ) -> None:
  110. _LOGGER.debug(
  111. "writing burst: start_register=0x%02x values=%s", start_register, values
  112. )
  113. response = self._spi.xfer([start_register | self._WRITE_BURST] + values)
  114. assert len(response) == len(values) + 1, response
  115. self._log_chip_status_byte(response[0])
  116. assert all(v == 0x0F for v in response[1:]), response # TODO why?
  117. def _reset(self) -> None:
  118. self._command_strobe(StrobeAddress.SRES)
  119. def _get_symbol_rate_exponent(self) -> int:
  120. """
  121. MDMCFG4.DRATE_E
  122. """
  123. return self._read_single_byte(ConfigurationRegisterAddress.MDMCFG4) & 0b00001111
  124. def _set_symbol_rate_exponent(self, exponent: int):
  125. mdmcfg4 = self._read_single_byte(ConfigurationRegisterAddress.MDMCFG4)
  126. mdmcfg4 &= 0b11110000
  127. mdmcfg4 |= exponent
  128. self._write_burst(
  129. start_register=ConfigurationRegisterAddress.MDMCFG4, values=[mdmcfg4]
  130. )
  131. def _get_symbol_rate_mantissa(self) -> int:
  132. """
  133. MDMCFG3.DRATE_M
  134. """
  135. return self._read_single_byte(ConfigurationRegisterAddress.MDMCFG3)
  136. def _set_symbol_rate_mantissa(self, mantissa: int) -> None:
  137. self._write_burst(
  138. start_register=ConfigurationRegisterAddress.MDMCFG3, values=[mantissa]
  139. )
  140. @classmethod
  141. def _symbol_rate_floating_point_to_real(cls, mantissa: int, exponent: int) -> float:
  142. # see "12 Data Rate Programming"
  143. return (
  144. (256 + mantissa)
  145. * (2 ** exponent)
  146. * cls._CRYSTAL_OSCILLATOR_FREQUENCY_HERTZ
  147. / (2 ** 28)
  148. )
  149. @classmethod
  150. def _symbol_rate_real_to_floating_point(cls, real: float) -> typing.Tuple[int, int]:
  151. # see "12 Data Rate Programming"
  152. assert real > 0, real
  153. exponent = math.floor(
  154. math.log2(real / cls._CRYSTAL_OSCILLATOR_FREQUENCY_HERTZ) + 20
  155. )
  156. mantissa = round(
  157. real * 2 ** 28 / cls._CRYSTAL_OSCILLATOR_FREQUENCY_HERTZ / 2 ** exponent
  158. - 256
  159. )
  160. if mantissa == 256:
  161. exponent += 1
  162. mantissa = 0
  163. assert 0 < exponent <= 2 ** 4, exponent
  164. assert mantissa <= 2 ** 8, mantissa
  165. return mantissa, exponent
  166. def get_symbol_rate_baud(self) -> float:
  167. return self._symbol_rate_floating_point_to_real(
  168. mantissa=self._get_symbol_rate_mantissa(),
  169. exponent=self._get_symbol_rate_exponent(),
  170. )
  171. def set_symbol_rate_baud(self, real: float) -> None:
  172. mantissa, exponent = self._symbol_rate_real_to_floating_point(real)
  173. self._set_symbol_rate_mantissa(mantissa)
  174. self._set_symbol_rate_exponent(exponent)
  175. def get_modulation_format(self) -> ModulationFormat:
  176. mdmcfg2 = self._read_single_byte(ConfigurationRegisterAddress.MDMCFG2)
  177. return self.ModulationFormat((mdmcfg2 >> 4) & 0b111)
  178. def _set_modulation_format(self, modulation_format: ModulationFormat) -> None:
  179. mdmcfg2 = self._read_single_byte(ConfigurationRegisterAddress.MDMCFG2)
  180. mdmcfg2 &= ~(modulation_format << 4)
  181. mdmcfg2 |= modulation_format << 4
  182. self._write_burst(ConfigurationRegisterAddress.MDMCFG2, [mdmcfg2])
  183. def __enter__(self) -> "CC1101":
  184. # https://docs.python.org/3/reference/datamodel.html#object.__enter__
  185. self._spi.open(0, 0)
  186. self._spi.max_speed_hz = 55700 # empirical
  187. self._reset()
  188. partnum = self._read_status_register(StatusRegisterAddress.PARTNUM)
  189. if partnum != self._SUPPORTED_PARTNUM:
  190. raise ValueError(
  191. "unexpected chip part number {} (expected: {})".format(
  192. partnum, self._SUPPORTED_PARTNUM
  193. )
  194. )
  195. version = self._read_status_register(StatusRegisterAddress.VERSION)
  196. if version != self._SUPPORTED_VERSION:
  197. raise ValueError(
  198. "unexpected chip version number {} (expected: {})".format(
  199. version, self._SUPPORTED_VERSION
  200. )
  201. )
  202. # 6:4 MOD_FORMAT: OOK (default: 2-FSK)
  203. self._set_modulation_format(self.ModulationFormat.ASK_OOK)
  204. # 7:6 unused
  205. # 5:4 FS_AUTOCAL: calibrate when going from IDLE to RX or TX
  206. # 3:2 PO_TIMEOUT: default
  207. # 1 PIN_CTRL_EN: default
  208. # 0 XOSC_FORCE_ON: default
  209. self._write_burst(ConfigurationRegisterAddress.MCSM0, [0b010100])
  210. marcstate = self.get_main_radio_control_state_machine_state()
  211. if marcstate != self.MainRadioControlStateMachineState.IDLE:
  212. raise ValueError("expected marcstate idle (actual: {})".format(marcstate))
  213. return self
  214. def __exit__(self, exc_type, exc_value, traceback) -> bool:
  215. # https://docs.python.org/3/reference/datamodel.html#object.__exit__
  216. self._spi.close()
  217. return False
  218. def get_main_radio_control_state_machine_state(
  219. self
  220. ) -> MainRadioControlStateMachineState:
  221. return self.MainRadioControlStateMachineState(
  222. self._read_status_register(StatusRegisterAddress.MARCSTATE)
  223. )
  224. def get_marc_state(self) -> MainRadioControlStateMachineState:
  225. """
  226. alias for get_main_radio_control_state_machine_state()
  227. """
  228. return self.get_main_radio_control_state_machine_state()
  229. @classmethod
  230. def _frequency_control_word_to_hertz(cls, control_word: typing.List[int]) -> float:
  231. return (
  232. int.from_bytes(control_word, byteorder="big", signed=False)
  233. * cls._FREQUENCY_CONTROL_WORD_HERTZ_FACTOR
  234. )
  235. @classmethod
  236. def _hertz_to_frequency_control_word(cls, hertz: float) -> typing.List[int]:
  237. return list(
  238. round(hertz / cls._FREQUENCY_CONTROL_WORD_HERTZ_FACTOR).to_bytes(
  239. length=3, byteorder="big", signed=False
  240. )
  241. )
  242. def _get_base_frequency_control_word(self) -> typing.List[int]:
  243. # > The base or start frequency is set by the 24 bitfrequency
  244. # > word located in the FREQ2, FREQ1, FREQ0 registers.
  245. return self._read_burst(
  246. start_register=ConfigurationRegisterAddress.FREQ2, length=3
  247. )
  248. def _set_base_frequency_control_word(self, control_word: typing.List[int]) -> None:
  249. self._write_burst(
  250. start_register=ConfigurationRegisterAddress.FREQ2, values=control_word
  251. )
  252. def get_base_frequency_hertz(self) -> float:
  253. return self._frequency_control_word_to_hertz(
  254. self._get_base_frequency_control_word()
  255. )
  256. def set_base_frequency_hertz(self, freq: float) -> None:
  257. self._set_base_frequency_control_word(
  258. self._hertz_to_frequency_control_word(freq)
  259. )
  260. def __str__(self) -> str:
  261. return "CC1101(marcstate={}, base_frequency={:.2f}MHz, symbol_rate={:.2f}kBaud, modulation_format={})".format(
  262. self.get_main_radio_control_state_machine_state().name.lower(),
  263. self.get_base_frequency_hertz() / 10 ** 6,
  264. self.get_symbol_rate_baud() / 1000,
  265. self.get_modulation_format().name,
  266. )
  267. def _get_packet_length(self) -> int:
  268. """
  269. packet length in fixed packet length mode,
  270. maximum packet length in variable packet length mode.
  271. """
  272. return self._read_single_byte(ConfigurationRegisterAddress.PKTLEN)
  273. def _flush_tx_fifo_buffer(self) -> None:
  274. # > Only issue SFTX in IDLE or TXFIFO_UNDERFLOW states.
  275. _LOGGER.debug("flushing tx fifo buffer")
  276. self._command_strobe(StrobeAddress.SFTX)
  277. def transmit(self, payload: typing.List[int]) -> None:
  278. # see "15.2 Packet Format"
  279. # > In variable packet length mode, [...]
  280. # > The first byte written to the TXFIFO must be different from 0.
  281. if payload[0] == 0:
  282. raise ValueError(
  283. "in variable packet length mode the first byte of payload must not be null"
  284. + "\npayload: {}".format(payload)
  285. )
  286. marcstate = self.get_main_radio_control_state_machine_state()
  287. if marcstate != self.MainRadioControlStateMachineState.IDLE:
  288. raise Exception(
  289. "device must be idle before transmission (current marcstate: {})".format(
  290. marcstate.name
  291. )
  292. )
  293. max_packet_length = self._get_packet_length()
  294. if len(payload) > max_packet_length:
  295. raise ValueError(
  296. "payload exceeds maximum payload length of {} bytes".format(
  297. max_packet_length
  298. )
  299. + "\npayload: {}".format(payload)
  300. )
  301. self._flush_tx_fifo_buffer()
  302. self._write_burst(FIFORegisterAddress.TX, payload)
  303. _LOGGER.info("transmitting %s", payload)
  304. self._command_strobe(StrobeAddress.STX)