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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. """Python bindings for PD Buddy Sink configuration"""
  2. from collections import namedtuple
  3. try:
  4. # Try importing enum from the standard library
  5. import enum
  6. # Make sure Flag is available
  7. enum.Flag
  8. except (ImportError, NameError, AttributeError):
  9. # If something above failed, try aenum instead
  10. import aenum as enum
  11. import serial
  12. import serial.tools.list_ports
  13. class Sink:
  14. """Interface for configuring a PD Buddy Sink"""
  15. vid = 0x1209
  16. pid = 0x9DB5
  17. def __init__(self, sp):
  18. """Open a serial port to communicate with the PD Buddy Sink
  19. :param sp: the serial port of the device
  20. :type sp: str or `serial.tools.list_ports.ListPortInfo`
  21. """
  22. try:
  23. self._port = serial.Serial(sp, baudrate=115200)
  24. except ValueError:
  25. self._port = serial.Serial(sp.device, baudrate=115200)
  26. # Put communications in a known state, cancelling any partially-entered
  27. # command that may be sitting in the buffer.
  28. self.send_command("\x04", newline=False)
  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, newline=True):
  34. """Send a command to the PD Buddy Sink, returning the result
  35. :param cmd: the text to send to the Sink
  36. :param newline: whether to append a ``\r\n`` to the command
  37. :type cmd: str
  38. :type newline: bool
  39. :returns: a list of zero or more bytes objects, each being one line
  40. printed as a response to the command.
  41. """
  42. # Build the command
  43. cmd = cmd.encode("utf-8")
  44. if newline:
  45. cmd += b"\r\n"
  46. # Send the command
  47. self._port.write(cmd)
  48. self._port.flush()
  49. # Read the result
  50. answer = b""
  51. while not answer.endswith(b"PDBS) "):
  52. answer += self._port.read(1)
  53. answer = answer.split(b"\r\n")
  54. # Remove the echoed command and prompt
  55. answer = answer[1:-1]
  56. # Raise an exception if the command wasn't recognized
  57. if len(answer) and answer[0] == cmd.strip().split()[0] + b" ?":
  58. raise KeyError("command not found")
  59. return answer
  60. def close(self):
  61. """Close the serial port"""
  62. self._port.close()
  63. def help(self):
  64. """Returns the help text from the PD Buddy Sink"""
  65. return self.send_command("help")
  66. def license(self):
  67. """Returns the license text from the PD Buddy Sink"""
  68. return self.send_command("license")
  69. def boot(self):
  70. """Runs the PD Buddy Sink's DFU bootloader and closes the serial port"""
  71. self._port.write(b"boot\r\n")
  72. self._port.flush()
  73. self.close()
  74. def erase(self):
  75. """Synchronously erases all stored configuration from flash"""
  76. self.send_command("erase")
  77. def write(self):
  78. """Synchronously writes the contents of the configuration buffer to flash"""
  79. self.send_command("write")
  80. def load(self):
  81. """Loads the current configuration from flash into the buffer
  82. :raises: KeyError
  83. """
  84. text = self.send_command("load")
  85. if len(text) > 0 and text[0].startswith(b"No configuration"):
  86. raise KeyError("no configuration")
  87. def get_cfg(self, index=None):
  88. """Reads configuration from flash
  89. :param index: optional index of configuration object in flash to read
  90. :returns: a `SinkConfig` object
  91. """
  92. if index is None:
  93. cfg = self.send_command("get_cfg")
  94. else:
  95. cfg = self.send_command("get_cfg {}".format(index))
  96. return SinkConfig.from_text(cfg)
  97. def get_tmpcfg(self):
  98. """Reads the contents of the configuration buffer
  99. :returns: a `SinkConfig` object
  100. """
  101. cfg = self.send_command("get_tmpcfg")
  102. return SinkConfig.from_text(cfg)
  103. def clear_flags(self):
  104. """Clears all the flags in the configuration buffer"""
  105. self.send_command("clear_flags")
  106. def toggle_giveback(self):
  107. """Toggles the GiveBack flag in the configuration buffer"""
  108. self.send_command("toggle_giveback")
  109. def set_v(self, mv):
  110. """Sets the voltage of the configuration buffer, in millivolts"""
  111. out = self.send_command("set_v {}".format(mv))
  112. # If that command gave any output, that indicates an error. Raise an
  113. # exception to make that clear.
  114. if len(out):
  115. raise ValueError(out[0])
  116. def set_i(self, ma):
  117. """Sets the current of the configuration buffer, in milliamperes"""
  118. out = self.send_command("set_i {}".format(ma))
  119. # If that command gave any output, that indicates an error. Raise an
  120. # exception to make that clear.
  121. if len(out):
  122. raise ValueError(out[0])
  123. def identify(self):
  124. """Blinks the LED quickly"""
  125. self.send_command("identify")
  126. @property
  127. def output(self):
  128. """The state of the Sink's output
  129. Raises KeyError if the ``output`` command is not available on the Sink.
  130. Raises ValueError if an invalid output is read.
  131. """
  132. value = self.send_command("output")
  133. if value[0] == b"enabled":
  134. return True
  135. elif value[0] == b"disabled":
  136. return False
  137. else:
  138. # If unexpected text is returned, raise an exception indicating a
  139. # firmware error
  140. raise ValueError("unknown output state")
  141. @output.setter
  142. def output(self, state):
  143. if state:
  144. self.send_command("output enable")
  145. else:
  146. self.send_command("output disable")
  147. def get_source_cap(self):
  148. """Gets the most recent Source_Capabilities read by the Sink"""
  149. return read_pdo_list(self.send_command("get_source_cap"))
  150. def set_tmpcfg(self, sc):
  151. """Writes a SinkConfig object to the device's configuration buffer
  152. Note: the value of the status field is ignored; it will always be
  153. `SinkStatus.VALID`.
  154. """
  155. # Set flags
  156. self.clear_flags()
  157. if sc.flags & SinkFlags.GIVEBACK:
  158. self.toggle_giveback()
  159. # Set voltage
  160. self.set_v(sc.v)
  161. # Set current
  162. self.set_i(sc.i)
  163. @classmethod
  164. def get_devices(cls):
  165. """Get an iterable of PD Buddy Sink devices
  166. :returns: an iterable of `serial.tools.list_ports.ListPortInfo` objects
  167. """
  168. return serial.tools.list_ports.grep("{:04X}:{:04X}".format(cls.vid,
  169. cls.pid))
  170. class SinkConfig(namedtuple("SinkConfig", "status flags v vmin vmax i")):
  171. """Python representation of a PD Buddy Sink configuration object
  172. ``status`` should be a `SinkStatus` object. ``flags`` should be zero or
  173. more `SinkFlags` values. ``v``, ``vmin``, and ``vmax`` are voltages in
  174. millivolts, and ``i`` is the current in milliamperes. `None` is also an
  175. acceptible value for any of the fields.
  176. """
  177. __slots__ = ()
  178. def __str__(self):
  179. """Print the SinkStatus in the manner of the configuration shell"""
  180. s = ""
  181. if self.status is not None:
  182. s += "status: "
  183. if self.status is SinkStatus.EMPTY:
  184. s += "empty"
  185. elif self.status is SinkStatus.VALID:
  186. s += "valid"
  187. elif self.status is SinkStatus.INVALID:
  188. s += "invalid"
  189. s += "\n"
  190. if self.flags is not None:
  191. s += "flags: "
  192. if self.flags is SinkFlags.NONE:
  193. s += "(none)"
  194. else:
  195. if self.flags & SinkFlags.GIVEBACK:
  196. s += "GiveBack"
  197. if self.flags & SinkFlags.HV_PREFERRED:
  198. s += "HV_Preferred"
  199. s += "\n"
  200. if self.v is not None:
  201. s += "v: {:.3f} V\n".format(self.v / 1000.0)
  202. if self.vmin is not None:
  203. s += "vmin: {:.3f} V\n".format(self.vmin / 1000.0)
  204. if self.vmax is not None:
  205. s += "vmax: {:.3f} V\n".format(self.vmax / 1000.0)
  206. if self.i is not None:
  207. s += "i: {:.2f} A\n".format(self.i / 1000.0)
  208. # Return all but the last character of s to remove the trailing newline
  209. if s:
  210. return s[:-1]
  211. else:
  212. return "No configuration"
  213. @classmethod
  214. def from_text(cls, text):
  215. """Creates a SinkConfig from text returned by Sink.send_command
  216. :param text: the text to load
  217. :type text: a list of bytes objects
  218. :returns: a new `SinkConfig` object.
  219. :raises: IndexError
  220. """
  221. # Assume the parameters will all be None
  222. status = None
  223. flags = None
  224. v = None
  225. vmin = None
  226. vmax = 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(None, None, None, None, None, None)
  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. elif word == b"HV_Preferred":
  256. flags |= SinkFlags.HV_PREFERRED
  257. # If this line is the v field
  258. elif line.startswith(b"v: "):
  259. word = line.split()[1]
  260. v = round(1000*float(word))
  261. # If this line is the vmin field
  262. elif line.startswith(b"vmin: "):
  263. word = line.split()[1]
  264. vmin = round(1000*float(word))
  265. # If this line is the vmax field
  266. elif line.startswith(b"vmax: "):
  267. word = line.split()[1]
  268. vmax = round(1000*float(word))
  269. # If this line is the i field
  270. elif line.startswith(b"i: "):
  271. word = line.split()[1]
  272. i = round(1000*float(word))
  273. # Create a new SinkConfig object with the values we just read
  274. return cls(status=status, flags=flags, v=v, vmin=vmin, vmax=vmax, i=i)
  275. class SinkStatus(enum.Enum):
  276. """Status field of a PD Buddy Sink configuration object"""
  277. EMPTY = 1
  278. VALID = 2
  279. INVALID = 3
  280. class SinkFlags(enum.Flag):
  281. """Flags field of a PD Buddy Sink configuration object"""
  282. NONE = 0
  283. GIVEBACK = enum.auto()
  284. HV_PREFERRED = enum.auto()
  285. class UnknownPDO(namedtuple("UnknownPDO", "value")):
  286. """A PDO of an unknown type
  287. ``value`` should be a 32-bit integer representing the PDO exactly as
  288. transmitted.
  289. """
  290. __slots__ = ()
  291. pdo_type = "unknown"
  292. def __str__(self):
  293. """Print the UnknownPDO in the manner of the configuration shell"""
  294. return "{:08X}".format(self.value)
  295. class SrcFixedPDO(namedtuple("SrcFixedPDO", "dual_role_pwr usb_suspend "
  296. "unconstrained_pwr usb_comms dual_role_data unchunked_ext_msg peak_i "
  297. "v i")):
  298. """A Source Fixed PDO
  299. ``dual_role_pwr``, ``usb_suspend``, ``unconstrained_pwr``,
  300. ``usb_comms``, ``dual_role_data``, and ``unchunked_ext_msg`` should be
  301. booleans. ``peak_i`` should be an integer in the range [0, 3]. ``v``
  302. is the voltage in millivolts, and ``i`` is the maximum current in
  303. milliamperes.
  304. """
  305. __slots__ = ()
  306. pdo_type = "fixed"
  307. def __str__(self):
  308. """Print the SrcFixedPDO in the manner of the configuration shell"""
  309. s = self.pdo_type + "\n"
  310. if self.dual_role_pwr:
  311. s += "\tdual_role_pwr: 1\n"
  312. if self.usb_suspend:
  313. s += "\tusb_suspend: 1\n"
  314. if self.unconstrained_pwr:
  315. s += "\tunconstrained_pwr: 1\n"
  316. if self.usb_comms:
  317. s += "\tusb_comms: 1\n"
  318. if self.dual_role_data:
  319. s += "\tdual_role_data: 1\n"
  320. if self.unchunked_ext_msg:
  321. s += "\tunchunked_ext_msg: 1\n"
  322. if self.peak_i:
  323. s += "\tpeak_i: {}\n".format(self.peak_i)
  324. s += "\tv: {:.2f} V\n".format(self.v / 1000.0)
  325. s += "\ti: {:.2f} A".format(self.i / 1000.0)
  326. return s
  327. class TypeCVirtualPDO(namedtuple("TypeCVirtualPDO", "i")):
  328. """A Type-C Current Virtual PDO
  329. ``i`` is the advertised current in milliamperes.
  330. """
  331. __slots__ = ()
  332. pdo_type = "typec_virtual"
  333. def __str__(self):
  334. """Print the TypeCVirtualPDO in the manner of the configuration shell"""
  335. s = self.pdo_type + "\n"
  336. s += "\ti: {:.2f} A".format(self.i / 1000.0)
  337. return s
  338. def read_pdo(text):
  339. """Create a PDO object from partial text returned by Sink.send_command"""
  340. # First, determine the PDO type
  341. pdo_type = text[0].split(b":")[-1].strip().decode("utf-8")
  342. if pdo_type == SrcFixedPDO.pdo_type:
  343. # Set default values (n.b. there are none for v and i)
  344. dual_role_pwr = False
  345. usb_suspend = False
  346. unconstrained_pwr = False
  347. usb_comms = False
  348. dual_role_data = False
  349. unchunked_ext_msg = False
  350. peak_i = 0
  351. # Load a SrcFixedPDO
  352. for line in text[1:]:
  353. fields = line.split(b":")
  354. fields[0] = fields[0].strip()
  355. fields[1] = fields[1].strip()
  356. if fields[0] == b"dual_role_pwr":
  357. dual_role_pwr = (fields[1] == b"1")
  358. elif fields[0] == b"usb_suspend":
  359. usb_suspend = (fields[1] == b"1")
  360. elif fields[0] == b"unconstrained_pwr":
  361. unconstrained_pwr = (fields[1] == b"1")
  362. elif fields[0] == b"usb_comms":
  363. usb_comms = (fields[1] == b"1")
  364. elif fields[0] == b"dual_role_data":
  365. dual_role_data = (fields[1] == b"1")
  366. elif fields[0] == b"unchunked_ext_msg":
  367. unchunked_ext_msg = (fields[1] == b"1")
  368. elif fields[0] == b"peak_i":
  369. peak_i = int(fields[1])
  370. elif fields[0] == b"v":
  371. v = round(1000*float(fields[1].split()[0]))
  372. elif fields[0] == b"i":
  373. i = round(1000*float(fields[1].split()[0]))
  374. # Make the SrcFixedPDO
  375. return SrcFixedPDO(
  376. dual_role_pwr=dual_role_pwr,
  377. usb_suspend=usb_suspend,
  378. unconstrained_pwr=unconstrained_pwr,
  379. usb_comms=usb_comms,
  380. dual_role_data=dual_role_data,
  381. unchunked_ext_msg=unchunked_ext_msg,
  382. peak_i=peak_i,
  383. v=v,
  384. i=i)
  385. elif pdo_type == TypeCVirtualPDO.pdo_type:
  386. # Load a TypeCVirtualPDO
  387. for line in text[1:]:
  388. fields = line.split(b":")
  389. fields[0] = fields[0].strip()
  390. fields[1] = fields[1].strip()
  391. if fields[0] == b"i":
  392. i = round(1000*float(fields[1].split()[0]))
  393. # Make the TypeCVirtualPDO
  394. return TypeCVirtualPDO(i=i)
  395. elif pdo_type == "No Source_Capabilities":
  396. return None
  397. else:
  398. # Make an UnknownPDO
  399. return UnknownPDO(value=int(pdo_type, 16))
  400. def read_pdo_list(text):
  401. """Create a list of PDOs from text returned by Sink.send_command"""
  402. # Get the lines where PDOs start
  403. pdo_start_list = []
  404. for index, line in enumerate(text):
  405. if not line.startswith(b"\t"):
  406. pdo_start_list.append(index)
  407. # Append the number of lines so the last slice will work right
  408. pdo_start_list.append(len(text))
  409. # Read the PDOs
  410. pdo_list = []
  411. for start, end in zip(pdo_start_list[:-1], pdo_start_list[1:]):
  412. pdo = read_pdo(text[start:end])
  413. if pdo is not None:
  414. pdo_list.append(pdo)
  415. return pdo_list
  416. def calculate_pdp(pdo_list):
  417. """Calculate the PDP in watts of a list of PDOs
  418. The result is only guaranteed to be correct if the power supply follows
  419. the USB Power Delivery standard. Since quite a few power supplies
  420. unfortunately do not, this can really only be considered an estimate.
  421. """
  422. max_power = 0
  423. # The Source Power Rules make it so the PDP can be determined by the
  424. # highest power available from any fixed supply PDO.
  425. for pdo in pdo_list:
  426. if pdo.pdo_type == "fixed":
  427. max_power = max(max_power, pdo.v / 1000.0 * pdo.i / 1000.0)
  428. elif pdo.pdo_type == "typec_virtual":
  429. max_power = max(max_power, 5.0 * pdo.i / 1000.0)
  430. return max_power
  431. def follows_power_rules(pdo_list):
  432. """Test whether a list of PDOs follows the Power Rules for PD 2.0
  433. This function is a false-biased approximation; that is, when it returns
  434. False it is definitely correct, but when it returns True it might be
  435. incorrect.
  436. """
  437. # First, estimate the PDP assuming the rules are being followed
  438. pdp = calculate_pdp(pdo_list)
  439. # If there's a typec_virtual PDO, there's no Power Delivery so the Power
  440. # Rules cannot be violated. In truth they're not really being followed
  441. # either since they only apply to Power Delivery, but returning True here
  442. # seems like the safer option.
  443. if pdo_list and pdo_list[0].pdo_type == "typec_virtual":
  444. return True
  445. # Make sure nothing exceeds the PDP
  446. for pdo in pdo_list:
  447. if pdo.pdo_type == "fixed":
  448. if pdp < pdo.v / 1000.0 * pdo.i / 1000.0:
  449. return False
  450. # TODO: in the future, there will be more types of PDO checked here
  451. # Check that the fixed supply PDOs look right
  452. seen_5v = False
  453. seen_9v = False
  454. seen_15v = False
  455. seen_20v = False
  456. seen_normative_voltages = False
  457. if pdp == 0:
  458. # No power is fine
  459. seen_normative_voltages = True
  460. elif pdp <= 15:
  461. # Below 15 W, make sure the PDP is available at 5 V.
  462. for pdo in pdo_list:
  463. if pdo.pdo_type == "fixed" and pdo.v == 5000:
  464. seen_5v = True
  465. if pdo.v / 1000.0 * pdo.i / 1000.0 != pdp:
  466. return False
  467. seen_normative_voltages = seen_5v
  468. elif pdp <= 27:
  469. # Between 15 and 27 W, make sure at least 3 A is available at 5 V and
  470. # the PDP is available at 9 V.
  471. for pdo in pdo_list:
  472. if pdo.pdo_type == "fixed" and pdo.v == 5000:
  473. seen_5v = True
  474. if pdo.i < 3000.0:
  475. return False
  476. elif pdo.pdo_type == "fixed" and pdo.v == 9000:
  477. seen_9v = True
  478. if pdo.v / 1000.0 * pdo.i / 1000.0 != pdp:
  479. return False
  480. seen_normative_voltages = seen_5v and seen_9v
  481. elif pdp <= 45:
  482. # Between 27 and 45 W, make sure at least 3 A is available at 5 and
  483. # 9 V, and the PDP is available at 15 V.
  484. for pdo in pdo_list:
  485. if pdo.pdo_type == "fixed" and pdo.v == 5000:
  486. seen_5v = True
  487. if pdo.i < 3000.0:
  488. return False
  489. elif pdo.pdo_type == "fixed" and pdo.v == 9000:
  490. seen_9v = True
  491. if pdo.i < 3000.0:
  492. return False
  493. elif pdo.pdo_type == "fixed" and pdo.v == 15000:
  494. seen_15v = True
  495. if pdo.v / 1000.0 * pdo.i / 1000.0 != pdp:
  496. return False
  497. seen_normative_voltages = seen_5v and seen_9v and seen_15v
  498. else:
  499. # Above 45 W, make sure at least 3 A is available at 5, 9, and 15 V,
  500. # and the PDP is available at 20 V.
  501. for pdo in pdo_list:
  502. if pdo.pdo_type == "fixed" and pdo.v == 5000:
  503. seen_5v = True
  504. if pdo.i < 3000.0:
  505. return False
  506. elif pdo.pdo_type == "fixed" and pdo.v == 9000:
  507. seen_9v = True
  508. if pdo.i < 3000.0:
  509. return False
  510. elif pdo.pdo_type == "fixed" and pdo.v == 15000:
  511. seen_15v = True
  512. if pdo.i < 3000.0:
  513. return False
  514. elif pdo.pdo_type == "fixed" and pdo.v == 20000:
  515. seen_20v = True
  516. if pdo.v / 1000.0 * pdo.i / 1000.0 != pdp:
  517. return False
  518. seen_normative_voltages = seen_5v and seen_9v and seen_15v and seen_20v
  519. if not seen_normative_voltages:
  520. return False
  521. # TODO: there are several things this currently doesn't test, such as
  522. # variable and battery PDOs.
  523. return True