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

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