GTK+ GUI for configuring PD Buddy Sink devices
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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.giveback = None
  121. self.selectlist = None
  122. def on_pdb_window_realize(self, *args):
  123. # Get the list
  124. sb = self.builder.get_object("select-box")
  125. self.selectlist = SelectList()
  126. sb.pack_start(self.selectlist, True, True, 0)
  127. liststore = SelectListStore()
  128. self.selectlist.bind_model(liststore, SelectListRow)
  129. self.selectlist.connect("row-activated", self.on_select_list_row_activated)
  130. def on_pdb_window_delete_event(self, *args):
  131. Gtk.main_quit(*args)
  132. def on_select_list_row_activated(self, selectlist, serport):
  133. # Get voltage and current widgets
  134. voltage = self.builder.get_object("voltage-combobox")
  135. current = self.builder.get_object("current-spinbutton")
  136. giveback = self.builder.get_object("giveback-toggle")
  137. self.serial_port = serport
  138. window = self.builder.get_object("pdb-window")
  139. try:
  140. pdb_send_message(self.serial_port, 'load', window)
  141. tmpcfg = pdb_send_message(self.serial_port, 'get_tmpcfg', window)
  142. except:
  143. return
  144. # Get voltage and current from device and load them into the GUI
  145. for line in tmpcfg:
  146. if line.startswith(b'flags:'):
  147. line = line.split()[1:]
  148. try:
  149. line.index(b'GiveBack')
  150. giveback.set_active(True)
  151. except:
  152. giveback.set_active(False)
  153. elif line.startswith(b'v:'):
  154. v = line.split()[1]
  155. if v == b'5.00':
  156. voltage.set_active_id('voltage-five')
  157. elif v == b'9.00':
  158. voltage.set_active_id('voltage-nine')
  159. elif v == b'15.00':
  160. voltage.set_active_id('voltage-fifteen')
  161. if v == b'20.00':
  162. voltage.set_active_id('voltage-twenty')
  163. elif line.startswith(b'i:'):
  164. i = float(line.split()[1])
  165. current.set_value(i)
  166. self._store_device_settings()
  167. self._set_save_button_visibility()
  168. # Show the Sink page
  169. hst = self.builder.get_object("header-stack")
  170. hsink = self.builder.get_object("header-sink")
  171. hsink.set_subtitle(serport.device)
  172. hst.set_visible_child(hsink)
  173. st = self.builder.get_object("stack")
  174. sink = self.builder.get_object("sink")
  175. st.set_visible_child(sink)
  176. # Ping the Sink repeatedly
  177. GLib.timeout_add(1000, self._ping)
  178. def _ping(self):
  179. """Ping the device we're configuring, showing to the list on failure"""
  180. if self.serial_port is None:
  181. self.selectlist.reload()
  182. self.on_header_sink_back_clicked(None)
  183. return False
  184. try:
  185. pdb_send_message(self.serial_port, '')
  186. return True
  187. except:
  188. self.selectlist.reload()
  189. self.on_header_sink_back_clicked(None)
  190. return False
  191. def on_header_sink_back_clicked(self, data):
  192. self.serial_port = None
  193. # Show the Select page
  194. hst = self.builder.get_object("header-stack")
  195. hselect = self.builder.get_object("header-select")
  196. hst.set_visible_child(hselect)
  197. st = self.builder.get_object("stack")
  198. select = self.builder.get_object("select")
  199. st.set_visible_child(select)
  200. def on_header_sink_save_clicked(self, button):
  201. window = self.builder.get_object("pdb-window")
  202. try:
  203. pdb_send_message(self.serial_port, 'write', window)
  204. self._store_device_settings()
  205. self._set_save_button_visibility()
  206. except:
  207. self.on_header_sink_back_clicked(None)
  208. def _store_device_settings(self):
  209. """Store the settings that were loaded from the device"""
  210. # Get voltage and current widgets
  211. voltage = self.builder.get_object("voltage-combobox")
  212. current = self.builder.get_object("current-spinbutton")
  213. giveback = self.builder.get_object("giveback-toggle")
  214. # Remember the loaded settings
  215. self.voltage = voltage.get_active_id()
  216. self.current = current.get_value()
  217. self.giveback = giveback.get_active()
  218. def _set_save_button_visibility(self):
  219. """Show the save button if there are new settings to save"""
  220. # Get relevant widgets
  221. voltage = self.builder.get_object("voltage-combobox")
  222. current = self.builder.get_object("current-spinbutton")
  223. giveback = self.builder.get_object("giveback-toggle")
  224. rev = self.builder.get_object("header-sink-save-revealer")
  225. # Set visibility
  226. rev.set_reveal_child(voltage.get_active_id() != self.voltage
  227. or current.get_value() != self.current
  228. or giveback.get_active() != self.giveback)
  229. def on_voltage_combobox_changed(self, combo):
  230. window = self.builder.get_object("pdb-window")
  231. try:
  232. pdb_send_message(self.serial_port,
  233. 'set_v {}'.format(int(combo.get_active_text())*1000),
  234. window)
  235. self._set_save_button_visibility()
  236. except:
  237. self.on_header_sink_back_clicked(None)
  238. def on_current_spinbutton_changed(self, spin):
  239. window = self.builder.get_object("pdb-window")
  240. try:
  241. pdb_send_message(self.serial_port,
  242. 'set_i {}'.format(int(spin.get_value()*1000)),
  243. window)
  244. self._set_save_button_visibility()
  245. except:
  246. self.on_header_sink_back_clicked(None)
  247. def on_giveback_toggle_toggled(self, toggle):
  248. window = self.builder.get_object("pdb-window")
  249. try:
  250. pdb_send_message(self.serial_port, 'toggle_giveback', window)
  251. self._set_save_button_visibility()
  252. except:
  253. self.on_header_sink_back_clicked(None)
  254. class Application(Gtk.Application):
  255. def __init__(self, *args, **kwargs):
  256. super().__init__(*args, application_id="com.clayhobbs.pd-buddy-gtk",
  257. **kwargs)
  258. self.window = None
  259. def do_startup(self):
  260. Gtk.Application.do_startup(self)
  261. self.builder = Gtk.Builder()
  262. self.builder.add_from_file("data/pd-buddy-gtk.ui")
  263. self.builder.connect_signals(Handler(self.builder))
  264. def do_activate(self):
  265. # We only allow a single window and raise any existing ones
  266. if not self.window:
  267. # Windows are associated with the application
  268. # when the last one is closed the application shuts down
  269. self.window = self.builder.get_object("pdb-window")
  270. self.add_window(self.window)
  271. self.window.set_wmclass("PD Buddy Configuration",
  272. "PD Buddy Configuration")
  273. self.window.present()
  274. if __name__ == "__main__":
  275. app = Application()
  276. app.run(sys.argv)