Python library for working with the PD Buddy Sink Serial Console Configuration Interface
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

__init__.py 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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 set_tmpcfg(self, sc):
  118. """Writes a SinkConfig object to the device's configuration buffer
  119. Note: the value of the status field is ignored; it will always be
  120. `SinkStatus.VALID`.
  121. """
  122. # Set flags
  123. self.clear_flags()
  124. if sc.flags & SinkFlags.GIVEBACK:
  125. self.toggle_giveback()
  126. # Set voltage
  127. self.set_v(sc.v)
  128. # Set current
  129. self.set_i(sc.i)
  130. @classmethod
  131. def get_devices(cls):
  132. """Get an iterable of PD Buddy Sink devices
  133. :returns: an iterable of `serial.tools.list_ports.ListPortInfo` objects
  134. """
  135. return serial.tools.list_ports.grep("{:04X}:{:04X}".format(cls.vid,
  136. cls.pid))
  137. class SinkConfig:
  138. """Python representation of a PD Buddy Sink configuration object"""
  139. def __init__(self, status=None, flags=None, v=None, i=None):
  140. """Create a SinkConfig object
  141. :param status: A `SinkStatus` value
  142. :param flags: Zero or more `SinkFlags` values
  143. :param v: Voltage in millivolts
  144. :param i: Current in milliamperes
  145. """
  146. self.status = status
  147. self.flags = flags
  148. self.v = v
  149. self.i = i
  150. def __repr__(self):
  151. s = self.__class__.__name__ + "("
  152. if self.status is not None:
  153. s += "status={}".format(self.status)
  154. if self.flags is not None:
  155. if not s.endswith("("):
  156. s += ", "
  157. s += "flags={}".format(self.flags)
  158. if self.v is not None:
  159. if not s.endswith("("):
  160. s += ", "
  161. s += "v={}".format(self.v)
  162. if self.i is not None:
  163. if not s.endswith("("):
  164. s += ", "
  165. s += "i={}".format(self.i)
  166. s += ")"
  167. return s
  168. def __str__(self):
  169. """Print the SinkStatus in the manner of the configuration shell"""
  170. s = ""
  171. if self.status is not None:
  172. s += "status: "
  173. if self.status is SinkStatus.EMPTY:
  174. s += "empty"
  175. elif self.status is SinkStatus.VALID:
  176. s += "valid"
  177. elif self.status is SinkStatus.INVALID:
  178. s += "invalid"
  179. s += "\n"
  180. if self.flags is not None:
  181. s += "flags: "
  182. if self.flags is SinkFlags.NONE:
  183. s += "(none)"
  184. else:
  185. if self.flags & SinkFlags.GIVEBACK:
  186. s += "GiveBack"
  187. s += "\n"
  188. if self.v is not None:
  189. s += "v: {:.2f} V\n".format(self.v / 1000)
  190. if self.i is not None:
  191. s += "i: {:.2f} A\n".format(self.i / 1000)
  192. # Return all but the last character of s to remove the trailing newline
  193. if s:
  194. return s[:-1]
  195. else:
  196. return "No configuration"
  197. def __eq__(self, other):
  198. if isinstance(other, self.__class__):
  199. if other.status is not self.status:
  200. return False
  201. if other.flags is not self.flags:
  202. return False
  203. if other.v != self.v:
  204. return False
  205. if other.i != self.i:
  206. return False
  207. return True
  208. return NotImplemented
  209. def __ne__(self, other):
  210. if isinstance(other, self.__class__):
  211. return not self.__eq__(other)
  212. return NotImplemented
  213. def __hash__(self):
  214. return hash(tuple(sorted(self.__dict__.items())))
  215. @classmethod
  216. def from_text(cls, text):
  217. """Creates a SinkConfig from text returned by Sink.send_command
  218. :param text: the text to load
  219. :type text: a list of bytes objects
  220. :returns: a new `SinkConfig` object.
  221. :raises: IndexError
  222. """
  223. # Assume the parameters will all be None
  224. status = None
  225. flags = None
  226. v = None
  227. i = None
  228. # Iterate over all lines of text
  229. for line in text:
  230. # If the configuration said invalid index, raise an IndexError
  231. if line.startswith(b"Invalid index"):
  232. raise IndexError("configuration index out of range")
  233. # If there is no configuration, return an empty SinkConfig
  234. elif line.startswith(b"No configuration"):
  235. return cls()
  236. # If this line is the status field
  237. elif line.startswith(b"status: "):
  238. line = line.split()[1:]
  239. if line[0] == b"empty":
  240. status = SinkStatus.EMPTY
  241. elif line[0] == b"valid":
  242. status = SinkStatus.VALID
  243. elif line[0] == b"invalid":
  244. status = SinkStatus.INVALID
  245. # If this line is the flags field
  246. elif line.startswith(b"flags: "):
  247. line = line.split()[1:]
  248. flags = SinkFlags.NONE
  249. for word in line:
  250. if word == b"(none)":
  251. # If there are no flags set, stop looking
  252. break
  253. elif word == b"GiveBack":
  254. flags |= SinkFlags.GIVEBACK
  255. # If this line is the v field
  256. elif line.startswith(b"v: "):
  257. word = line.split()[1]
  258. v = round(1000*float(word))
  259. # If this line is the i field
  260. elif line.startswith(b"i: "):
  261. word = line.split()[1]
  262. i = round(1000*float(word))
  263. # Create a new SinkConfig object with the values we just read
  264. return cls(status=status, flags=flags, v=v, i=i)
  265. class SinkStatus(enum.Enum):
  266. """Status field of a PD Buddy Sink configuration object"""
  267. EMPTY = 1
  268. VALID = 2
  269. INVALID = 3
  270. class SinkFlags(enum.Flag):
  271. """Flags field of a PD Buddy Sink configuration object"""
  272. NONE = 0
  273. GIVEBACK = enum.auto()