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 9.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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 = 0x0001
  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. def __enter__(self):
  26. return self
  27. def __exit__(self, exc_type, exc_value, traceback):
  28. self._port.close()
  29. def send_command(self, cmd):
  30. """Send a command to the PD Buddy Sink, returning the result
  31. :param cmd: the text to send to the Sink
  32. :type sp: str
  33. :returns: a list of zero or more bytes objects, each being one line
  34. printed as a response to the command.
  35. """
  36. # Send the command
  37. self._port.write(cmd.encode("utf-8") + b"\r\n")
  38. self._port.flush()
  39. # Read the result
  40. answer = b""
  41. while not answer.endswith(b"PDBS) "):
  42. answer += self._port.read(1)
  43. answer = answer.split(b"\r\n")
  44. # Remove the echoed command and prompt
  45. answer = answer[1:-1]
  46. return answer
  47. def close(self):
  48. """Close the serial port"""
  49. self._port.close()
  50. def help(self):
  51. """Returns the help text from the PD Buddy Sink"""
  52. return self.send_command("help")
  53. def license(self):
  54. """Returns the license text from the PD Buddy Sink"""
  55. return self.send_command("license")
  56. def erase(self):
  57. """Synchronously erases all stored configuration from flash"""
  58. self.send_command("erase")
  59. def write(self):
  60. """Synchronously writes the contents of the configuration buffer to flash"""
  61. self.send_command("write")
  62. def load(self):
  63. """Loads the current configuration from flash into the buffer
  64. :raises: KeyError
  65. """
  66. text = self.send_command("load")
  67. if len(text) > 0 and text[0].startswith(b"No configuration"):
  68. raise KeyError("no configuration")
  69. def get_cfg(self, index=None):
  70. """Reads configuration from flash
  71. :param index: optional index of configuration object in flash to read
  72. :returns: a `SinkConfig` object
  73. """
  74. if index is None:
  75. cfg = self.send_command("get_cfg")
  76. else:
  77. cfg = self.send_command("get_cfg {}".format(index))
  78. return SinkConfig.from_text(cfg)
  79. def get_tmpcfg(self):
  80. """Reads the contents of the configuration buffer
  81. :returns: a `SinkConfig` object
  82. """
  83. cfg = self.send_command("get_tmpcfg")
  84. return SinkConfig.from_text(cfg)
  85. def clear_flags(self):
  86. """Clears all the flags in the configuration buffer"""
  87. self.send_command("clear_flags")
  88. def toggle_giveback(self):
  89. """Toggles the GiveBack flag in the configuration buffer"""
  90. self.send_command("toggle_giveback")
  91. def set_v(self, mv):
  92. """Sets the voltage of the configuration buffer, in millivolts"""
  93. self.send_command("set_v {}".format(mv))
  94. def set_i(self, ma):
  95. """Sets the current of the configuration buffer, in milliamperes"""
  96. self.send_command("set_i {}".format(ma))
  97. def identify(self):
  98. """Blinks the LED quickly"""
  99. self.send_command("identify")
  100. def set_tmpcfg(self, sc):
  101. """Writes a SinkConfig object to the device's configuration buffer
  102. Note: the value of the status field is ignored; it will always be
  103. `SinkStatus.VALID`.
  104. """
  105. # Set flags
  106. self.clear_flags()
  107. if sc.flags & SinkFlags.GIVEBACK:
  108. self.toggle_giveback()
  109. # Set voltage
  110. self.set_v(sc.v)
  111. # Set current
  112. self.set_i(sc.i)
  113. @classmethod
  114. def get_devices(cls):
  115. """Get an iterable of PD Buddy Sink devices
  116. :returns: an iterable of `serial.tools.list_ports.ListPortInfo` objects
  117. """
  118. return serial.tools.list_ports.grep("{:04X}:{:04X}".format(cls.vid,
  119. cls.pid))
  120. class SinkConfig:
  121. """Python representation of a PD Buddy Sink configuration object"""
  122. def __init__(self, status=None, flags=None, v=None, i=None):
  123. """Create a SinkConfig object
  124. :param status: A `SinkStatus` value
  125. :param flags: Zero or more `SinkFlags` values
  126. :param v: Voltage in millivolts
  127. :param i: Current in milliamperes
  128. """
  129. self.status = status
  130. self.flags = flags
  131. self.v = v
  132. self.i = i
  133. def __repr__(self):
  134. s = self.__class__.__name__ + "("
  135. if self.status is not None:
  136. s += "status={}".format(self.status)
  137. if self.flags is not None:
  138. if not s.endswith("("):
  139. s += ", "
  140. s += "flags={}".format(self.flags)
  141. if self.v is not None:
  142. if not s.endswith("("):
  143. s += ", "
  144. s += "v={}".format(self.v)
  145. if self.i is not None:
  146. if not s.endswith("("):
  147. s += ", "
  148. s += "i={}".format(self.i)
  149. s += ")"
  150. return s
  151. def __str__(self):
  152. """Print the SinkStatus in the manner of the configuration shell"""
  153. s = ""
  154. if self.status is not None:
  155. s += "status: "
  156. if self.status is SinkStatus.EMPTY:
  157. s += "empty"
  158. elif self.status is SinkStatus.VALID:
  159. s += "valid"
  160. elif self.status is SinkStatus.INVALID:
  161. s += "invalid"
  162. s += "\n"
  163. if self.flags is not None:
  164. s += "flags: "
  165. if self.flags is SinkFlags.NONE:
  166. s += "(none)"
  167. else:
  168. if self.flags & SinkFlags.GIVEBACK:
  169. s += "GiveBack"
  170. s += "\n"
  171. if self.v is not None:
  172. s += "v: {:.2f} V\n".format(self.v / 1000)
  173. if self.i is not None:
  174. s += "i: {:.2f} A\n".format(self.i / 1000)
  175. # Return all but the last character of s to remove the trailing newline
  176. if s:
  177. return s[:-1]
  178. else:
  179. return "No configuration"
  180. def __eq__(self, other):
  181. if isinstance(other, self.__class__):
  182. if other.status is not self.status:
  183. return False
  184. if other.flags is not self.flags:
  185. return False
  186. if other.v != self.v:
  187. return False
  188. if other.i != self.i:
  189. return False
  190. return True
  191. return NotImplemented
  192. def __ne__(self, other):
  193. if isinstance(other, self.__class__):
  194. return not self.__eq__(other)
  195. return NotImplemented
  196. def __hash__(self):
  197. return hash(tuple(sorted(self.__dict__.items())))
  198. @classmethod
  199. def from_text(cls, text):
  200. """Creates a SinkConfig from text returned by Sink.send_command
  201. :returns: a new `SinkConfig` object.
  202. :raises: IndexError
  203. """
  204. # Assume the parameters will all be None
  205. status = None
  206. flags = None
  207. v = None
  208. i = None
  209. # Iterate over all lines of text
  210. for line in text:
  211. # If the configuration said invalid index, raise an IndexError
  212. if line.startswith(b"Invalid index"):
  213. raise IndexError("configuration index out of range")
  214. # If there is no configuration, return an empty SinkConfig
  215. elif line.startswith(b"No configuration"):
  216. return cls()
  217. # If this line is the status field
  218. elif line.startswith(b"status: "):
  219. line = line.split()[1:]
  220. if line[0] == b"empty":
  221. status = SinkStatus.EMPTY
  222. elif line[0] == b"valid":
  223. status = SinkStatus.VALID
  224. elif line[0] == b"invalid":
  225. status = SinkStatus.INVALID
  226. # If this line is the flags field
  227. elif line.startswith(b"flags: "):
  228. line = line.split()[1:]
  229. flags = SinkFlags.NONE
  230. for word in line:
  231. if word == b"(none)":
  232. # If there are no flags set, stop looking
  233. break
  234. elif word == b"GiveBack":
  235. flags |= SinkFlags.GIVEBACK
  236. # If this line is the v field
  237. elif line.startswith(b"v: "):
  238. word = line.split()[1]
  239. v = round(1000*float(word))
  240. # If this line is the i field
  241. elif line.startswith(b"i: "):
  242. word = line.split()[1]
  243. i = round(1000*float(word))
  244. # Create a new SinkConfig object with the values we just read
  245. return cls(status=status, flags=flags, v=v, i=i)
  246. class SinkStatus(enum.Enum):
  247. """Status field of a PD Buddy Sink configuration object"""
  248. EMPTY = 1
  249. VALID = 2
  250. INVALID = 3
  251. class SinkFlags(enum.Flag):
  252. """Flags field of a PD Buddy Sink configuration object"""
  253. NONE = 0
  254. GIVEBACK = enum.auto()