GTK+ GUI for configuring PD Buddy Sink devices
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

pd-buddy-gtk.py 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. #!/usr/bin/env python3
  2. import sys
  3. import serial
  4. import serial.tools.list_ports
  5. import gi
  6. gi.require_version('Gtk', '3.0')
  7. from gi.repository import Gtk, Gio, GObject, GLib
  8. def pdb_send_message(sp, message, window=None):
  9. """Send a message over the serial port and return the response"""
  10. try:
  11. # Open the serial port
  12. sp = serial.Serial(sp.device, baudrate=115200, timeout=0.01)
  13. sp.write(bytes(message, 'utf-8') + b'\r\n')
  14. sp.flush()
  15. answer = sp.readlines()
  16. sp.close()
  17. # Remove the echoed command and prompt
  18. answer = answer[1:-1]
  19. return answer
  20. except OSError as e:
  21. if window is not None:
  22. dialog = Gtk.MessageDialog(window, 0, Gtk.MessageType.ERROR,
  23. Gtk.ButtonsType.CLOSE, "Error communicating with device")
  24. dialog.format_secondary_text(e.strerror)
  25. dialog.run()
  26. dialog.destroy()
  27. raise
  28. class ListRowModel(GObject.GObject):
  29. def __init__(self, serport):
  30. GObject.GObject.__init__(self)
  31. self.serport = serport
  32. class SelectListStore(Gio.ListStore):
  33. def update_items(self):
  34. # Get a list of serial ports
  35. serports = list(serial.tools.list_ports.grep("1209:0001"))
  36. # Mark ports to remove or add
  37. remove_list = []
  38. list_len = self.get_n_items()
  39. for i in range(list_len):
  40. remove = True
  41. for j in range(len(serports)):
  42. if serports[j] is not None and self.get_item(i).serport == serports[j]:
  43. serports[j] = None
  44. remove = False
  45. if remove:
  46. remove_list.append(i)
  47. # Remove the missing ones
  48. for i in remove_list:
  49. self.remove(i)
  50. # Add any new ports
  51. for port in serports:
  52. if port is not None:
  53. self.append(ListRowModel(port))
  54. class SelectList(Gtk.Box):
  55. __gsignals__ = {
  56. 'row-activated': (GObject.SIGNAL_RUN_FIRST, None,
  57. (object,))
  58. }
  59. def __init__(self):
  60. Gtk.Box.__init__(self)
  61. self._model = None
  62. self._builder = Gtk.Builder()
  63. self._builder.add_from_file("data/select-stack.ui")
  64. self._builder.connect_signals(self)
  65. sl = self._builder.get_object("select-list")
  66. # Add separators to the list
  67. sl.set_header_func(self._update_header_func, None)
  68. self.pack_start(self._builder.get_object("select-stack"), True, True, 0)
  69. self.show_all()
  70. def _update_header_func(self, row, before, data):
  71. """Add a separator header to all rows but the first one"""
  72. if before is None:
  73. row.set_header(None)
  74. return
  75. current = row.get_header()
  76. if current is None:
  77. current = Gtk.Separator.new(Gtk.Orientation.HORIZONTAL)
  78. row.set_header(current)
  79. def bind_model(self, model, func):
  80. self._builder.get_object("select-list").bind_model(model, func)
  81. self._model = model
  82. self.reload()
  83. GLib.timeout_add(1000, self.reload)
  84. def reload(self):
  85. self._model.update_items()
  86. # Set the visible child
  87. stack = self._builder.get_object("select-stack")
  88. if self._model.get_n_items():
  89. stack.set_visible_child(self._builder.get_object("select-frame"))
  90. else:
  91. stack.set_visible_child(self._builder.get_object("select-none"))
  92. return True
  93. def on_select_list_row_activated(self, box, row):
  94. self.emit("row-activated", row.model.serport)
  95. class SelectListRow(Gtk.ListBoxRow):
  96. def __init__(self, model):
  97. Gtk.EventBox.__init__(self)
  98. self.model = model
  99. self._builder = Gtk.Builder()
  100. self._builder.add_from_file("data/select-list-row.ui")
  101. self._builder.connect_signals(self)
  102. name = self._builder.get_object("name")
  103. name.set_text(self.model.serport.description)
  104. device = self._builder.get_object("device")
  105. device.set_text(self.model.serport.device)
  106. self.add(self._builder.get_object("grid"))
  107. self.show_all()
  108. def on_identify_clicked(self, button):
  109. window = self.get_toplevel()
  110. try:
  111. pdb_send_message(self.model.serport, 'identify', window)
  112. except:
  113. return
  114. class Handler:
  115. def __init__(self, builder):
  116. self.builder = builder
  117. self.serial_port = None
  118. self.voltage = None
  119. self.current = None
  120. self.selectlist = None
  121. def on_pdb_window_realize(self, *args):
  122. # Get the list
  123. sb = self.builder.get_object("select-box")
  124. self.selectlist = SelectList()
  125. sb.pack_start(self.selectlist, True, True, 0)
  126. liststore = SelectListStore()
  127. self.selectlist.bind_model(liststore, SelectListRow)
  128. self.selectlist.connect("row-activated", self.on_select_list_row_activated)
  129. def on_pdb_window_delete_event(self, *args):
  130. Gtk.main_quit(*args)
  131. def on_select_list_row_activated(self, selectlist, serport):
  132. # Get voltage and current widgets
  133. voltage = self.builder.get_object("voltage-combobox")
  134. current = self.builder.get_object("current-spinbutton")
  135. self.serial_port = serport
  136. window = self.builder.get_object("pdb-window")
  137. try:
  138. pdb_send_message(self.serial_port, 'load', window)
  139. tmpcfg = pdb_send_message(self.serial_port, 'get_tmpcfg', window)
  140. except:
  141. return
  142. # Get voltage and current from device and load them into the GUI
  143. for line in tmpcfg:
  144. if line.startswith(b'v:'):
  145. v = line.split()[1]
  146. if v == b'5.00':
  147. voltage.set_active_id('voltage-five')
  148. elif v == b'9.00':
  149. voltage.set_active_id('voltage-nine')
  150. elif v == b'15.00':
  151. voltage.set_active_id('voltage-fifteen')
  152. if v == b'20.00':
  153. voltage.set_active_id('voltage-twenty')
  154. elif line.startswith(b'i:'):
  155. i = float(line.split()[1])
  156. current.set_value(i)
  157. self._store_device_settings()
  158. self._set_save_button_visibility()
  159. # Show the Sink page
  160. hst = self.builder.get_object("header-stack")
  161. hsink = self.builder.get_object("header-sink")
  162. hsink.set_subtitle(serport.device)
  163. hst.set_visible_child(hsink)
  164. st = self.builder.get_object("stack")
  165. sink = self.builder.get_object("sink")
  166. st.set_visible_child(sink)
  167. # Ping the Sink repeatedly
  168. GLib.timeout_add(1000, self._ping)
  169. def _ping(self):
  170. """Ping the device we're configuring, showing to the list on failure"""
  171. if self.serial_port is None:
  172. self.selectlist.reload()
  173. self.on_header_sink_back_clicked(None)
  174. return False
  175. try:
  176. pdb_send_message(self.serial_port, '')
  177. return True
  178. except:
  179. self.selectlist.reload()
  180. self.on_header_sink_back_clicked(None)
  181. return False
  182. def on_header_sink_back_clicked(self, data):
  183. self.serial_port = None
  184. # Show the Select page
  185. hst = self.builder.get_object("header-stack")
  186. hselect = self.builder.get_object("header-select")
  187. hst.set_visible_child(hselect)
  188. st = self.builder.get_object("stack")
  189. select = self.builder.get_object("select")
  190. st.set_visible_child(select)
  191. def on_header_sink_save_clicked(self, button):
  192. window = self.builder.get_object("pdb-window")
  193. try:
  194. pdb_send_message(self.serial_port, 'write', window)
  195. self._store_device_settings()
  196. self._set_save_button_visibility()
  197. except:
  198. self.on_header_sink_back_clicked(None)
  199. def _store_device_settings(self):
  200. """Store the settings that were loaded from the device"""
  201. # Get voltage and current widgets
  202. voltage = self.builder.get_object("voltage-combobox")
  203. current = self.builder.get_object("current-spinbutton")
  204. # Remember the loaded settings
  205. self.voltage = voltage.get_active_id()
  206. self.current = current.get_value()
  207. def _set_save_button_visibility(self):
  208. """Show the save button if there are new settings to save"""
  209. # Get relevant widgets
  210. voltage = self.builder.get_object("voltage-combobox")
  211. current = self.builder.get_object("current-spinbutton")
  212. rev = self.builder.get_object("header-sink-save-revealer")
  213. # Set visibility
  214. rev.set_reveal_child(voltage.get_active_id() != self.voltage
  215. or current.get_value() != self.current)
  216. def on_voltage_combobox_changed(self, combo):
  217. window = self.builder.get_object("pdb-window")
  218. try:
  219. pdb_send_message(self.serial_port,
  220. 'set_v {}'.format(int(combo.get_active_text())*1000),
  221. window)
  222. self._set_save_button_visibility()
  223. except:
  224. self.on_header_sink_back_clicked(None)
  225. def on_current_spinbutton_changed(self, spin):
  226. window = self.builder.get_object("pdb-window")
  227. try:
  228. pdb_send_message(self.serial_port,
  229. 'set_i {}'.format(int(spin.get_value()*1000)),
  230. window)
  231. self._set_save_button_visibility()
  232. except:
  233. self.on_header_sink_back_clicked(None)
  234. class Application(Gtk.Application):
  235. def __init__(self, *args, **kwargs):
  236. super().__init__(*args, application_id="com.clayhobbs.pd-buddy-gtk",
  237. **kwargs)
  238. self.window = None
  239. def do_startup(self):
  240. Gtk.Application.do_startup(self)
  241. self.builder = Gtk.Builder()
  242. self.builder.add_from_file("data/pd-buddy-gtk.ui")
  243. self.builder.connect_signals(Handler(self.builder))
  244. def do_activate(self):
  245. # We only allow a single window and raise any existing ones
  246. if not self.window:
  247. # Windows are associated with the application
  248. # when the last one is closed the application shuts down
  249. self.window = self.builder.get_object("pdb-window")
  250. self.add_window(self.window)
  251. self.window.set_wmclass("PD Buddy Configuration",
  252. "PD Buddy Configuration")
  253. self.window.present()
  254. if __name__ == "__main__":
  255. app = Application()
  256. app.run(sys.argv)