__init__.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. import enum
  2. import logging
  3. import typing
  4. import spidev
  5. _LOGGER = logging.getLogger(__name__)
  6. class CC1101:
  7. # > All transfers on the SPI interface are done
  8. # > most significant bit first.
  9. # > All transactions on the SPI interface start with
  10. # > a header byte containing a R/W bit, a access bit (B),
  11. # > and a 6-bit address (A5 - A0).
  12. # > [...]
  13. # > Table 45: SPI Address Space
  14. _WRITE_SINGLE_BYTE = 0x00
  15. # > Registers with consecutive addresses can be
  16. # > accessed in an efficient way by setting the
  17. # > burst bit (B) in the header byte. The address
  18. # > bits (A5 - A0) set the start address in an
  19. # > internal address counter. This counter is
  20. # > incremented by one each new byte [...]
  21. _WRITE_BURST = 0x40
  22. _READ_SINGLE_BYTE = 0x80
  23. _READ_BURST = 0xC0
  24. class _SPIAddress(enum.IntEnum):
  25. # see "Table 45: SPI Address Space"
  26. # > The configuration registers on the CC1101 are
  27. # > located on SPI addresses from 0x00 to 0x2E.
  28. FREQ2 = 0x0D
  29. FREQ1 = 0x0E
  30. FREQ0 = 0x0F
  31. MCSM0 = 0x18
  32. # > For register addresses in the range 0x30-0x3D,
  33. # > the burst bit is used to select between
  34. # > status registers when burst bit is one, and
  35. # > between command strobes when burst bit is
  36. # > zero. [...]
  37. # > Because of this, burst access is not available
  38. # > for status registers and they must be accessed
  39. # > one at a time. The status registers can only be
  40. # > read.
  41. SRES = 0x30
  42. PARTNUM = 0x30
  43. VERSION = 0x31
  44. MARCSTATE = 0x35
  45. class MainRadioControlStateMachineState(enum.IntEnum):
  46. """
  47. MARCSTATE - Main Radio Control State Machine State
  48. """
  49. # > Figure 13: Simplified State Diagram
  50. IDLE = 0x01
  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_burst(self, start_register: _SPIAddress, length: int) -> typing.List[int]:
  70. response = self._spi.xfer([start_register | self._READ_BURST] + [0] * length)
  71. assert len(response) == length + 1, response
  72. self._log_chip_status_byte(response[0])
  73. return response[1:]
  74. def _read_status_register(self, register: _SPIAddress) -> int:
  75. _LOGGER.debug("reading status register 0x%02x", register)
  76. values = self._read_burst(start_register=register, length=1)
  77. assert len(values) == 1, values
  78. return values[0]
  79. def _command_strobe(self, register: _SPIAddress) -> None:
  80. # see "10.4 Command Strobes"
  81. _LOGGER.debug("sending command strobe 0x%02x", register)
  82. response = self._spi.xfer([register | self._WRITE_SINGLE_BYTE])
  83. assert len(response) == 1, response
  84. self._log_chip_status_byte(response[0])
  85. def _write_burst(
  86. self, start_register: _SPIAddress, values: typing.List[int]
  87. ) -> None:
  88. _LOGGER.debug(
  89. "writing burst: start_register=0x%02x values=%s", start_register, values
  90. )
  91. response = self._spi.xfer([start_register | self._WRITE_BURST] + values)
  92. assert len(response) == len(values) + 1, response
  93. self._log_chip_status_byte(response[0])
  94. assert all(v == 0x0F for v in response[1:]), response # TODO why?
  95. def _reset(self) -> None:
  96. self._command_strobe(self._SPIAddress.SRES)
  97. def __enter__(self) -> "CC1101":
  98. # https://docs.python.org/3/reference/datamodel.html#object.__enter__
  99. self._spi.open(0, 0)
  100. self._spi.max_speed_hz = 55700 # empirical
  101. self._reset()
  102. partnum = self._read_status_register(self._SPIAddress.PARTNUM)
  103. if partnum != self._SUPPORTED_PARTNUM:
  104. raise ValueError(
  105. "unexpected chip part number {} (expected: {})".format(
  106. partnum, self._SUPPORTED_PARTNUM
  107. )
  108. )
  109. version = self._read_status_register(self._SPIAddress.VERSION)
  110. if version != self._SUPPORTED_VERSION:
  111. raise ValueError(
  112. "unexpected chip version number {} (expected: {})".format(
  113. version, self._SUPPORTED_VERSION
  114. )
  115. )
  116. # 7:6 unused
  117. # 5:4 FS_AUTOCAL: calibrate when going from IDLE to RX or TX
  118. # 3:2 PO_TIMEOUT: default
  119. # 1 PIN_CTRL_EN: default
  120. # 0 XOSC_FORCE_ON: default
  121. self._write_burst(self._SPIAddress.MCSM0, [0b010100])
  122. marcstate = self.get_main_radio_control_state_machine_state()
  123. if marcstate != self.MainRadioControlStateMachineState.IDLE:
  124. raise ValueError("expected marcstate idle (actual: {})".format(marcstate))
  125. return self
  126. def __exit__(self, exc_type, exc_value, traceback) -> bool:
  127. # https://docs.python.org/3/reference/datamodel.html#object.__exit__
  128. self._spi.close()
  129. return False
  130. def get_main_radio_control_state_machine_state(
  131. self
  132. ) -> MainRadioControlStateMachineState:
  133. return self.MainRadioControlStateMachineState(
  134. self._read_status_register(self._SPIAddress.MARCSTATE)
  135. )
  136. def get_marc_state(self) -> MainRadioControlStateMachineState:
  137. """
  138. alias for get_main_radio_control_state_machine_state()
  139. """
  140. return self.get_main_radio_control_state_machine_state()
  141. @classmethod
  142. def _frequency_control_word_to_hertz(cls, control_word: typing.List[int]) -> float:
  143. return (
  144. int.from_bytes(control_word, byteorder="big", signed=False)
  145. * cls._FREQUENCY_CONTROL_WORD_HERTZ_FACTOR
  146. )
  147. @classmethod
  148. def _hertz_to_frequency_control_word(cls, hertz: float) -> typing.List[int]:
  149. return list(
  150. round(hertz / cls._FREQUENCY_CONTROL_WORD_HERTZ_FACTOR).to_bytes(
  151. length=3, byteorder="big", signed=False
  152. )
  153. )
  154. def _get_base_frequency_control_word(self) -> typing.List[int]:
  155. # > The base or start frequency is set by the 24 bitfrequency
  156. # > word located in the FREQ2, FREQ1, FREQ0 registers.
  157. return self._read_burst(start_register=self._SPIAddress.FREQ2, length=3)
  158. def _set_base_frequency_control_word(self, control_word: typing.List[int]) -> None:
  159. self._write_burst(start_register=self._SPIAddress.FREQ2, values=control_word)
  160. def get_base_frequency_hertz(self) -> float:
  161. return self._frequency_control_word_to_hertz(
  162. self._get_base_frequency_control_word()
  163. )
  164. def set_base_frequency_hertz(self, freq: float) -> None:
  165. self._set_base_frequency_control_word(
  166. self._hertz_to_frequency_control_word(freq)
  167. )
  168. def __str__(self) -> str:
  169. return "CC1101(marcstate={}, base_frequency={:.2f}MHz)".format(
  170. self.get_main_radio_control_state_machine_state().name.lower(),
  171. self.get_base_frequency_hertz() / 10 ** 6,
  172. )