_cli.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. # python-cc1101 - Python Library to Transmit RF Signals via CC1101 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 argparse
  18. import logging
  19. import sys
  20. import typing
  21. import cc1101
  22. import cc1101.options
  23. _LOGGER = logging.getLogger(__name__)
  24. def _add_common_args(argparser: argparse.ArgumentParser) -> None:
  25. argparser.add_argument("-f", "--base-frequency-hertz", type=int)
  26. argparser.add_argument("-r", "--symbol-rate-baud", type=int)
  27. argparser.add_argument(
  28. "-s",
  29. "--sync-mode",
  30. type=str,
  31. choices=[m.name.lower().replace("_", "-") for m in cc1101.options.SyncMode],
  32. )
  33. argparser.add_argument(
  34. "-l",
  35. "--packet-length-mode",
  36. type=str,
  37. choices=[m.name.lower() for m in cc1101.options.PacketLengthMode],
  38. )
  39. argparser.add_argument("--disable-checksum", action="store_true")
  40. argparser.add_argument(
  41. "-p",
  42. "--output-power",
  43. metavar="SETTING",
  44. dest="output_power_settings",
  45. type=int,
  46. nargs="+",
  47. help="Configures output power levels by setting PATABLE and FREND0.PA_POWER."
  48. " Up to 8 bytes may be provided."
  49. # add when making _set_modulation_format() public
  50. # ' "[PATABLE] provides flexible PA power ramp up and ramp down'
  51. # " at the start and end of transmission when using 2-FSK, GFSK,"
  52. # ' 4-FSK, and MSK modulation as well as ASK modulation shaping."'
  53. " For OOK modulation, exactly 2 bytes must be provided:"
  54. " 0 to turn off the transmission for logical 0,"
  55. " and a level > 0 to turn on the transmission for logical 1"
  56. " (e.g., --output-power 0 198)."
  57. ' See "Table 39: Optimum PATABLE Settings for Various Output Power Levels [...]"'
  58. ' and section "24 Output Power Programming".',
  59. )
  60. argparser.add_argument("-d", "--debug", action="store_true")
  61. def _init_logging(args: argparse.Namespace) -> None:
  62. logging.basicConfig(
  63. level=logging.DEBUG if args.debug else logging.INFO,
  64. format="%(asctime)s:%(levelname)s:%(name)s:%(funcName)s:%(message)s"
  65. if args.debug
  66. else "%(message)s",
  67. datefmt="%Y-%m-%dT%H:%M:%S%z",
  68. )
  69. def _configure_via_args(
  70. *,
  71. transceiver: cc1101.CC1101,
  72. args: argparse.Namespace,
  73. packet_length_if_fixed: typing.Optional[int],
  74. ) -> None:
  75. if args.base_frequency_hertz:
  76. transceiver.set_base_frequency_hertz(args.base_frequency_hertz)
  77. if args.symbol_rate_baud:
  78. transceiver.set_symbol_rate_baud(args.symbol_rate_baud)
  79. if args.sync_mode:
  80. transceiver.set_sync_mode(
  81. cc1101.options.SyncMode[args.sync_mode.upper().replace("-", "_")]
  82. )
  83. if args.packet_length_mode:
  84. packet_length_mode = cc1101.options.PacketLengthMode[
  85. args.packet_length_mode.upper()
  86. ]
  87. # default: variable length
  88. transceiver.set_packet_length_mode(packet_length_mode)
  89. # default: 255 (maximum)
  90. if (
  91. packet_length_if_fixed is not None
  92. and packet_length_mode == cc1101.options.PacketLengthMode.FIXED
  93. ):
  94. transceiver.set_packet_length_bytes(packet_length_if_fixed)
  95. if args.disable_checksum:
  96. transceiver.disable_checksum()
  97. if args.output_power_settings:
  98. transceiver.set_output_power(args.output_power_settings)
  99. def _export_config():
  100. argparser = argparse.ArgumentParser(
  101. description="Export values in CC1101's configuration registers"
  102. " after applying settings specified via command-line arguments & options",
  103. allow_abbrev=False,
  104. )
  105. _add_common_args(argparser)
  106. argparser.add_argument("--format", choices=["python-list"], default="python-list")
  107. args = argparser.parse_args()
  108. _init_logging(args)
  109. _LOGGER.debug("args=%r", args)
  110. with cc1101.CC1101(lock_spi_device=True) as transceiver:
  111. _configure_via_args(
  112. transceiver=transceiver, args=args, packet_length_if_fixed=None
  113. )
  114. _LOGGER.info("%s", transceiver)
  115. print("[")
  116. for register_index, (register, value) in enumerate(
  117. transceiver.get_configuration_register_values().items()
  118. ):
  119. assert register_index == register.value
  120. print(
  121. "0b{value:08b}, # 0x{value:02x} {register_name}".format(
  122. value=value, register_name=register.name
  123. )
  124. )
  125. print("]")
  126. print(
  127. # pylint: disable=protected-access; internal function & method
  128. "# PATABLE = "
  129. + cc1101._format_patable(transceiver._get_patable(), insert_spaces=True)
  130. )
  131. def _transmit():
  132. argparser = argparse.ArgumentParser(
  133. description="Transmits the payload provided via standard input (stdin)"
  134. " ASK/OOK-modulated in big-endian bit order.",
  135. allow_abbrev=False,
  136. )
  137. _add_common_args(argparser)
  138. args = argparser.parse_args()
  139. _init_logging(args)
  140. _LOGGER.debug("args=%r", args)
  141. payload = sys.stdin.buffer.read()
  142. # configure transceiver after reading from stdin
  143. # to avoid delay between configuration and transmission if pipe is slow
  144. with cc1101.CC1101(lock_spi_device=True) as transceiver:
  145. _configure_via_args(
  146. transceiver=transceiver, args=args, packet_length_if_fixed=len(payload)
  147. )
  148. _LOGGER.info("%s", transceiver)
  149. transceiver.transmit(payload)