Python library for working with the PD Buddy Sink Serial Console Configuration Interface
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

__init__.py 9.7KB

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