Python library for working with the PD Buddy Sink Serial Console Configuration Interface
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

__init__.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. """Python bindings for PD Buddy Sink configuration"""
  2. try:
  3. # Try importing enum from the standard library
  4. import enum
  5. # Make sure Flag is available
  6. enum.Flag
  7. except (ImportError, NameError):
  8. # If something above failed, try aenum instead
  9. import aenum as enum
  10. import serial
  11. import serial.tools.list_ports
  12. class Sink:
  13. """Interface for configuring a PD Buddy Sink"""
  14. vid = 0x1209
  15. pid = 0x9DB5
  16. def __init__(self, sp):
  17. """Open a serial port to communicate with the PD Buddy Sink
  18. :param sp: the serial port of the device
  19. :type sp: str or `serial.tools.list_ports.ListPortInfo`
  20. """
  21. try:
  22. self._port = serial.Serial(sp, baudrate=115200)
  23. except ValueError:
  24. self._port = serial.Serial(sp.device, baudrate=115200)
  25. # Put communications in a known state, cancelling any partially-entered
  26. # command that may be sitting in the buffer.
  27. self.send_command("\x04", newline=False)
  28. def __enter__(self):
  29. return self
  30. def __exit__(self, exc_type, exc_value, traceback):
  31. self._port.close()
  32. def send_command(self, cmd, newline=True):
  33. """Send a command to the PD Buddy Sink, returning the result
  34. :param cmd: the text to send to the Sink
  35. :param newline: whether to append a ``\r\n`` to the command
  36. :type cmd: str
  37. :type newline: bool
  38. :returns: a list of zero or more bytes objects, each being one line
  39. printed as a response to the command.
  40. """
  41. # Build the command
  42. cmd = cmd.encode("utf-8")
  43. if newline:
  44. cmd += b"\r\n"
  45. # Send the command
  46. self._port.write(cmd)
  47. self._port.flush()
  48. # Read the result
  49. answer = b""
  50. while not answer.endswith(b"PDBS) "):
  51. answer += self._port.read(1)
  52. answer = answer.split(b"\r\n")
  53. # Remove the echoed command and prompt
  54. answer = answer[1:-1]
  55. return answer
  56. def close(self):
  57. """Close the serial port"""
  58. self._port.close()
  59. def help(self):
  60. """Returns the help text from the PD Buddy Sink"""
  61. return self.send_command("help")
  62. def license(self):
  63. """Returns the license text from the PD Buddy Sink"""
  64. return self.send_command("license")
  65. def erase(self):
  66. """Synchronously erases all stored configuration from flash"""
  67. self.send_command("erase")
  68. def write(self):
  69. """Synchronously writes the contents of the configuration buffer to flash"""
  70. self.send_command("write")
  71. def load(self):
  72. """Loads the current configuration from flash into the buffer
  73. :raises: KeyError
  74. """
  75. text = self.send_command("load")
  76. if len(text) > 0 and text[0].startswith(b"No configuration"):
  77. raise KeyError("no configuration")
  78. def get_cfg(self, index=None):
  79. """Reads configuration from flash
  80. :param index: optional index of configuration object in flash to read
  81. :returns: a `SinkConfig` object
  82. """
  83. if index is None:
  84. cfg = self.send_command("get_cfg")
  85. else:
  86. cfg = self.send_command("get_cfg {}".format(index))
  87. return SinkConfig.from_text(cfg)
  88. def get_tmpcfg(self):
  89. """Reads the contents of the configuration buffer
  90. :returns: a `SinkConfig` object
  91. """
  92. cfg = self.send_command("get_tmpcfg")
  93. return SinkConfig.from_text(cfg)
  94. def clear_flags(self):
  95. """Clears all the flags in the configuration buffer"""
  96. self.send_command("clear_flags")
  97. def toggle_giveback(self):
  98. """Toggles the GiveBack flag in the configuration buffer"""
  99. self.send_command("toggle_giveback")
  100. def set_v(self, mv):
  101. """Sets the voltage of the configuration buffer, in millivolts"""
  102. out = self.send_command("set_v {}".format(mv))
  103. # If that command gave any output, that indicates an error. Raise an
  104. # exception to make that clear.
  105. if len(out):
  106. raise ValueError(out[0])
  107. def set_i(self, ma):
  108. """Sets the current of the configuration buffer, in milliamperes"""
  109. out = self.send_command("set_i {}".format(ma))
  110. # If that command gave any output, that indicates an error. Raise an
  111. # exception to make that clear.
  112. if len(out):
  113. raise ValueError(out[0])
  114. def identify(self):
  115. """Blinks the LED quickly"""
  116. self.send_command("identify")
  117. def output(self, state=None):
  118. """Gets or sets the state of a Sink's output
  119. If an invalid output is read, raises ValueError. This may indicate
  120. that the firmware does not support the ``output`` command.
  121. :param state: optional value of the output to set
  122. :returns: the output state if state is None, None otherwise
  123. """
  124. # With no parameter, return the output state
  125. if state is None:
  126. value = self.send_command("output")
  127. if value[0] == b"enabled":
  128. return True
  129. elif value[0] == b"disabled":
  130. return False
  131. else:
  132. # If unexpected text is returned, raise an exception indicating a
  133. # firmware error
  134. raise ValueError("unknown output state")
  135. # With a parameter, set the output state
  136. if state:
  137. self.send_command("output enable")
  138. else:
  139. self.send_command("output disable")
  140. def set_tmpcfg(self, sc):
  141. """Writes a SinkConfig object to the device's configuration buffer
  142. Note: the value of the status field is ignored; it will always be
  143. `SinkStatus.VALID`.
  144. """
  145. # Set flags
  146. self.clear_flags()
  147. if sc.flags & SinkFlags.GIVEBACK:
  148. self.toggle_giveback()
  149. # Set voltage
  150. self.set_v(sc.v)
  151. # Set current
  152. self.set_i(sc.i)
  153. @classmethod
  154. def get_devices(cls):
  155. """Get an iterable of PD Buddy Sink devices
  156. :returns: an iterable of `serial.tools.list_ports.ListPortInfo` objects
  157. """
  158. return serial.tools.list_ports.grep("{:04X}:{:04X}".format(cls.vid,
  159. cls.pid))
  160. class SinkConfig:
  161. """Python representation of a PD Buddy Sink configuration object"""
  162. def __init__(self, status=None, flags=None, v=None, i=None):
  163. """Create a SinkConfig object
  164. :param status: A `SinkStatus` value
  165. :param flags: Zero or more `SinkFlags` values
  166. :param v: Voltage in millivolts
  167. :param i: Current in milliamperes
  168. """
  169. self.status = status
  170. self.flags = flags
  171. self.v = v
  172. self.i = i
  173. def __repr__(self):
  174. s = self.__class__.__name__ + "("
  175. if self.status is not None:
  176. s += "status={}".format(self.status)
  177. if self.flags is not None:
  178. if not s.endswith("("):
  179. s += ", "
  180. s += "flags={}".format(self.flags)
  181. if self.v is not None:
  182. if not s.endswith("("):
  183. s += ", "
  184. s += "v={}".format(self.v)
  185. if self.i is not None:
  186. if not s.endswith("("):
  187. s += ", "
  188. s += "i={}".format(self.i)
  189. s += ")"
  190. return s
  191. def __str__(self):
  192. """Print the SinkStatus in the manner of the configuration shell"""
  193. s = ""
  194. if self.status is not None:
  195. s += "status: "
  196. if self.status is SinkStatus.EMPTY:
  197. s += "empty"
  198. elif self.status is SinkStatus.VALID:
  199. s += "valid"
  200. elif self.status is SinkStatus.INVALID:
  201. s += "invalid"
  202. s += "\n"
  203. if self.flags is not None:
  204. s += "flags: "
  205. if self.flags is SinkFlags.NONE:
  206. s += "(none)"
  207. else:
  208. if self.flags & SinkFlags.GIVEBACK:
  209. s += "GiveBack"
  210. s += "\n"
  211. if self.v is not None:
  212. s += "v: {:.2f} V\n".format(self.v / 1000)
  213. if self.i is not None:
  214. s += "i: {:.2f} A\n".format(self.i / 1000)
  215. # Return all but the last character of s to remove the trailing newline
  216. if s:
  217. return s[:-1]
  218. else:
  219. return "No configuration"
  220. def __eq__(self, other):
  221. if isinstance(other, self.__class__):
  222. if other.status is not self.status:
  223. return False
  224. if other.flags is not self.flags:
  225. return False
  226. if other.v != self.v:
  227. return False
  228. if other.i != self.i:
  229. return False
  230. return True
  231. return NotImplemented
  232. def __ne__(self, other):
  233. if isinstance(other, self.__class__):
  234. return not self.__eq__(other)
  235. return NotImplemented
  236. def __hash__(self):
  237. return hash(tuple(sorted(self.__dict__.items())))
  238. @classmethod
  239. def from_text(cls, text):
  240. """Creates a SinkConfig from text returned by Sink.send_command
  241. :param text: the text to load
  242. :type text: a list of bytes objects
  243. :returns: a new `SinkConfig` object.
  244. :raises: IndexError
  245. """
  246. # Assume the parameters will all be None
  247. status = None
  248. flags = None
  249. v = None
  250. i = None
  251. # Iterate over all lines of text
  252. for line in text:
  253. # If the configuration said invalid index, raise an IndexError
  254. if line.startswith(b"Invalid index"):
  255. raise IndexError("configuration index out of range")
  256. # If there is no configuration, return an empty SinkConfig
  257. elif line.startswith(b"No configuration"):
  258. return cls()
  259. # If this line is the status field
  260. elif line.startswith(b"status: "):
  261. line = line.split()[1:]
  262. if line[0] == b"empty":
  263. status = SinkStatus.EMPTY
  264. elif line[0] == b"valid":
  265. status = SinkStatus.VALID
  266. elif line[0] == b"invalid":
  267. status = SinkStatus.INVALID
  268. # If this line is the flags field
  269. elif line.startswith(b"flags: "):
  270. line = line.split()[1:]
  271. flags = SinkFlags.NONE
  272. for word in line:
  273. if word == b"(none)":
  274. # If there are no flags set, stop looking
  275. break
  276. elif word == b"GiveBack":
  277. flags |= SinkFlags.GIVEBACK
  278. # If this line is the v field
  279. elif line.startswith(b"v: "):
  280. word = line.split()[1]
  281. v = round(1000*float(word))
  282. # If this line is the i field
  283. elif line.startswith(b"i: "):
  284. word = line.split()[1]
  285. i = round(1000*float(word))
  286. # Create a new SinkConfig object with the values we just read
  287. return cls(status=status, flags=flags, v=v, i=i)
  288. class SinkStatus(enum.Enum):
  289. """Status field of a PD Buddy Sink configuration object"""
  290. EMPTY = 1
  291. VALID = 2
  292. INVALID = 3
  293. class SinkFlags(enum.Flag):
  294. """Flags field of a PD Buddy Sink configuration object"""
  295. NONE = 0
  296. GIVEBACK = enum.auto()