-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathview.py
382 lines (318 loc) · 15.5 KB
/
view.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
#!/usr/bin/env python3
from time import sleep
import sys
import queue
import threading
from functools import partial
from datetime import datetime
import itertools
from time import time
import glob
from random import randint
from datetime import date, datetime
from p3lib.pconfig import ConfigManager
from controller import ETMXXXXPError, ETMXXXXP
from bokeh.server.server import Server
from bokeh.application import Application
from bokeh.application.handlers.function import FunctionHandler
from bokeh.plotting import figure, ColumnDataSource
from bokeh.models import Range1d
from bokeh.palettes import Category20_20 as palette
from bokeh.plotting import save, output_file
from bokeh.layouts import gridplot, column, row
from bokeh.models.widgets import CheckboxGroup
from bokeh.models.widgets.buttons import Button
from bokeh.models.widgets import TextInput
from bokeh.models import TextAreaInput
from bokeh.models import Panel, Tabs
from bokeh.models.widgets import Select
from bokeh.models import Spinner
from bokeh.models import Toggle
from bokeh.colors import named
from bokeh.models import DataTable, DateFormatter, TableColumn
from bokeh.models import CustomJS
from bokeh import events
from bokeh.models.layouts import Row
from bokeh.themes import built_in_themes
from bokeh.io.doc import curdoc, set_curdoc
from p3lib.bokeh_gui import TabbedGUI, StatusBarWrapper, ReadOnlyTableWrapper, ShutdownButtonWrapper, UpdateEvent
from pickle import NONE
#PJA TODO
# - Update README.md
class PSUGUIUpdateEvent(UpdateEvent):
"""@brief Responsible for holding the state of an event sent from a non GUI thread
to the GUI thread context in order to update the GUI in some way."""
# UPDATE_STATUS_TEXT = 1 # Implemented in parent class
CONNECTING_TO_PSU = 2
CONNECTED_TO_PSU = 3
PSU_CONNECT_FAILED = 4
TURNING_PSU_OFF = 5
PSU_OFF = 6
SET_PSU_STATE = 7
SHUTDOWN_SERVER = 8
def __init__(self, id, argList=None):
"""@brief Constructor
@param id An integer event ID
@param argList A list of arguments associated with the event"""
super().__init__(id, argList)
class PSUGUI(TabbedGUI):
"""@brief Responsible for plotting data on tab 0 with no other tabs."""
CFG_FILENAME = ".RS310P_GUI.cfg"
AMPS = "amps"
VOLTS = "volts"
PLOT_SECONDS = "plotSeconds"
CFG_DICT = {
VOLTS: 5,
AMPS: 1,
PLOT_SECONDS: 300
}
def __init__(self, docTitle, serialPort, bokehPort=12000):
"""@brief Constructor
@param docTitle The title of the bokeh server web page.
@param The serial port as defined on the command line."""
super().__init__(docTitle, bokehPort=bokehPort)
self._serialPort = serialPort
self._figTable=[[]]
self._grid = None
self._textBuffer = ""
self._psu = None
self._on = False
self._addressInput = None
self._tcpPortSpinner = None
def info(self, msg):
"""@brief Display an info level message."""
self.statusBarWrapper.setStatus("INFO: "+msg)
def error(self, msg):
"""@brief Display an error level message."""
self.statusBarWrapper.setStatus("ERROR: "+msg)
def debug(self, msg):
"""@brief Display an error level message."""
pass
def addRow(self):
"""@brief Add an empty row to the figures."""
self._figTable.append([])
def addToRow(self, fig):
"""@brief Add a figure to the end of the current row of figues.
@param fig The figure to add."""
self._figTable[-1].append(fig)
def createPlot(self, doc, ):
"""@brief create a plot figure.
@param doc The document to add the plot to."""
self._doc = doc
self._doc.title = "RS310P PSU Controller"
self.statusBarWrapper = StatusBarWrapper()
self._pconfig = ConfigManager(self, PSUGUI.CFG_FILENAME, PSUGUI.CFG_DICT)
self._pconfig.load()
plotPanel = self._getPlotPanel()
self._tabList.append( Panel(child=plotPanel, title="DC Power Supply Control") )
self._doc.add_root( Tabs(tabs=self._tabList) )
self._doc.add_periodic_callback(self._viewUpdate, 500)
def _viewUpdate(self):
if self._on:
volts, amps, watts = self._psu.getOutputStats()
self._opTableWrapper.setRows( [[volts, amps, watts]] )
self._updatePlot(volts, amps, watts)
def _updatePlot(self, volts, amps, watts):
"""@brief called periodically to update the plot trace."""
plotPoints = int(self.plotHistorySpinner.value*2)
now = datetime.now()
newVolts = {'x': [now],
'y': [volts]}
self._voltsSource.stream(newVolts, rollover=plotPoints)
newAmps = {'x': [now],
'y': [amps]}
self._ampsSource.stream(newAmps, rollover=plotPoints)
newWatts = {'x': [now],
'y': [watts]}
self._wattsSource.stream(newWatts, rollover=plotPoints)
def _getPlotPanel(self):
"""@brief Add tab that shows plot data updates."""
self._figTable.append([])
self._voltsSource = ColumnDataSource({'x': [], 'y': []})
self._ampsSource = ColumnDataSource({'x': [], 'y': []})
self._wattsSource = ColumnDataSource({'x': [], 'y': []})
fig = figure(toolbar_location='above', x_axis_type="datetime", x_axis_location="below")
fig.line(source=self._voltsSource, line_color = "blue", legend_label = "Volts")
fig.line(source=self._ampsSource, line_color = "green", legend_label = "Amps")
fig.line(source=self._wattsSource, line_color = "red", legend_label = "Watts")
fig.legend.location = 'top_left'
self._figTable[-1].append(fig)
self._grid = gridplot(children = self._figTable, sizing_mode = 'scale_both', toolbar_location='right')
remotePanel = None
if self._isSerialPortRemote():
self._addressInput = TextInput(value=self._serialPort[0], title="Address:", width=200)
self._tcpPortSpinner = Spinner(title="TCP Port", low=1, high=65535, value=self._serialPort[1], step=1, width=100)
remotePanel = row([self._addressInput, self._tcpPortSpinner])
else:
self.selectSerialPort = Select(title="Local Serial Port:")
self.selectSerialPort.options = glob.glob('/dev/ttyU*')
self.outputVoltageSpinner = Spinner(title="Output Voltage (Volts)", low=0, high=40, step=0.5, value=float(self._pconfig.getAttr(PSUGUI.VOLTS)))
self.currentLimitSpinner = Spinner(title="Currnet Limit (Amps)", low=0, high=10, step=0.25, value=float(self._pconfig.getAttr(PSUGUI.AMPS)))
self.plotHistorySpinner = Spinner(title="Plot History (Seconds)", low=1, high=10000, step=1, value=float(self._pconfig.getAttr(PSUGUI.PLOT_SECONDS)))
self._setButton = Button(label="Set")
self._setButton.on_click(self._setHandler)
self._setButton.disabled=True
self._onButton = Button(label="On")
self._onButton.on_click(self._psuOnHandler)
shutdownButtonWrapper = ShutdownButtonWrapper(self._quit)
if remotePanel:
controlPanel = column([remotePanel, self._onButton, self.outputVoltageSpinner, self.currentLimitSpinner, self._setButton, self.plotHistorySpinner, shutdownButtonWrapper.getWidget()])
else:
controlPanel = column([self.selectSerialPort, self._onButton, self.outputVoltageSpinner, self.currentLimitSpinner, self._setButton, self.plotHistorySpinner, shutdownButtonWrapper.getWidget()])
self._opTableWrapper = ReadOnlyTableWrapper( ("volts","amps","watts"), heightPolicy="fixed", height=65, showLastRows=0 )
plotPanel = column([self._grid, self._opTableWrapper.getWidget()])
panel2 = row([controlPanel, plotPanel])
plotPanel = column([panel2, self.statusBarWrapper.getWidget()])
return plotPanel
def _quit(self):
if self._on:
self._psuOff()
self._run(self._delayedShutdown)
self._doc.clear()
def _delayedShutdown(self):
"""@brief Allow time for browser page to clear before shutdown."""
volts = self.outputVoltageSpinner.value
amps = self.currentLimitSpinner.value
self._pconfig.addAttr(PSUGUI.VOLTS, volts)
self._pconfig.addAttr(PSUGUI.AMPS, amps)
self._pconfig.addAttr(PSUGUI.PLOT_SECONDS, self.plotHistorySpinner.value)
self._pconfig.store()
sleep(0.5)
self._sendUpdateEvent( PSUGUIUpdateEvent(PSUGUIUpdateEvent.SHUTDOWN_SERVER) )
def _psuOnHandler(self):
"""@brief event handler."""
#Stop the user from clicking the button again until this click has been processed.
self._onButton.disabled = True
#Turn the PSUon/off method outside GUI thread
self._run(self._powerOnOff)
def _setHandler(self):
"""@brief event handler."""
#Turn the PSUon/off method outside GUI thread
self._run(self._setPSU)
def _rxUpdateEvent(self, updateEvent):
"""@brief Receive an event into the GUI context to update the GUI.
@param updateEvent An PSUGUIUpdateEvent instance."""
if updateEvent.id == PSUGUIUpdateEvent.UPDATE_STATUS_TEXT:
self.statusBarWrapper.setStatus(updateEvent.argList[0])
elif updateEvent.id == PSUGUIUpdateEvent.CONNECTING_TO_PSU:
self._onButton.button_type = "success"
self._onButton.disabled = True
self.statusBarWrapper.setStatus(updateEvent.argList[0])
elif updateEvent.id == PSUGUIUpdateEvent.PSU_CONNECT_FAILED:
self._onButton.button_type = "default"
self._onButton.disabled = False
self._setButton.disabled = True
self._setButton.button_type = "default"
self.statusBarWrapper.setStatus(updateEvent.argList[0])
elif updateEvent.id == PSUGUIUpdateEvent.CONNECTED_TO_PSU:
self._setButton.button_type = "success"
self._setButton.disabled = False
self._onButton.button_type = "success"
self._onButton.disabled = False
self._onButton.label = "Off"
self.statusBarWrapper.setStatus("PSU ON")
self._pconfig.addAttr(PSUGUI.VOLTS, self.outputVoltageSpinner.value)
self._pconfig.addAttr(PSUGUI.AMPS, self.currentLimitSpinner.value)
self._pconfig.addAttr(PSUGUI.PLOT_SECONDS, self.plotHistorySpinner.value)
self._pconfig.store()
elif updateEvent.id == PSUGUIUpdateEvent.TURNING_PSU_OFF:
self._onButton.button_type = "default"
self._setButton.disabled = True
self._onButton.disabled = True
self._setButton.button_type = "default"
self.statusBarWrapper.setStatus("Turning PSU OFF")
elif updateEvent.id == PSUGUIUpdateEvent.PSU_OFF:
self._onButton.button_type = "default"
self._onButton.disabled = False
self._onButton.label = "On"
self.statusBarWrapper.setStatus("PSU OFF")
elif updateEvent.id == PSUGUIUpdateEvent.SET_PSU_STATE:
volts = self.outputVoltageSpinner.value
amps = self.currentLimitSpinner.value
self._pconfig.addAttr(PSUGUI.VOLTS, volts)
self._pconfig.addAttr(PSUGUI.AMPS, amps)
self._pconfig.addAttr(PSUGUI.PLOT_SECONDS, self.plotHistorySpinner.value)
self._pconfig.store()
self.statusBarWrapper.setStatus("Set {:.2f} volts with a {:.3f} amp current limit".format(volts, amps))
elif updateEvent.id == PSUGUIUpdateEvent.SHUTDOWN_SERVER:
self.stopServer()
print("PJA: SERVER SHUTDOWN.")
def _powerOnOff(self):
"""@brief Called to turn the PSU on/off"""
if self._on:
self._psuOff()
else:
self._psuOn()
def _setPSU(self):
"""@brief Called when the PSU is on to set the state of the PSU."""
volts = self.outputVoltageSpinner.value
amps = self.currentLimitSpinner.value
self._psu.setVoltage(volts)
self._psu.setCurrentLimit(amps)
self._sendUpdateEvent( UpdateEvent(PSUGUIUpdateEvent.SET_PSU_STATE) )
def _isSerialPortRemote(self):
"""@brief Determine if the serial port is remote.
@return True if the serial port is remote."""
remoterSerial = False
# If the user set an address and port on the command line rather
# than using a local serial port.
if isinstance(self._serialPort, tuple):
remoterSerial = True
return remoterSerial
def getSelectedSerialPort(self):
"""@brief Get the selected serial port.
@return the selected Serial port or None if not selected."""
selectedSerialPort = None
if self._isSerialPortRemote():
selectedSerialPort = [self._addressInput.value, self._tcpPortSpinner.value]
else:
# If only one serial port is available select it. This may not be selected.
if len(self.selectSerialPort.options) == 1:
selectedSerialPort = self.selectSerialPort.options[0]
# If more than one is available then use the selected port.
elif self.selectSerialPort.value:
selectedSerialPort = self.selectSerialPort.value
# Handle bokeh unselected port which may occur due to the sequence that
# bokeh callbacks are called.
if not selectedSerialPort and len(self.selectSerialPort.options) > 0:
selectedSerialPort = self.selectSerialPort.options[0]
return selectedSerialPort
def _psuOff(self):
"""@brief Turn the PSU off."""
self._sendUpdateEvent( UpdateEvent(PSUGUIUpdateEvent.TURNING_PSU_OFF) )
self._on = False
self._psu.setOutput(False)
self._psu.disconnect()
self._psu = None
self._sendUpdateEvent( UpdateEvent(PSUGUIUpdateEvent.PSU_OFF) )
def _psuOn(self):
"""@brief Connect to the PDU.
@return True if successfully connected to a PSU."""
serialPort = None
try:
serialPort = self.getSelectedSerialPort()
if serialPort:
self._sendUpdateEvent( UpdateEvent(PSUGUIUpdateEvent.CONNECTING_TO_PSU, ("Connecting to {}".format(serialPort),)) )
self._psu = ETMXXXXP(serialPort)
self._psu.connect()
self._psu.getOutput()
#Ensure the voltage comes up from a low voltage rather than down
#from a previously higher voltage
self._psu.setVoltage(0)
self._psu.setVoltage(self.outputVoltageSpinner.value)
self._psu.setCurrentLimit(self.currentLimitSpinner.value)
self._psu.setOutput(True)
self._on = True
self._sendUpdateEvent( UpdateEvent(PSUGUIUpdateEvent.CONNECTED_TO_PSU) )
else:
self._sendUpdateEvent( UpdateEvent(PSUGUIUpdateEvent.PSU_CONNECT_FAILED, ("Failed to to connect to PSU as no serial port was selected.",) ) )
except Exception as ex:
print(ex)
if self._psu:
self._psu.disconnect()
self._psu = None
if serialPort:
self._sendUpdateEvent( UpdateEvent(PSUGUIUpdateEvent.PSU_CONNECT_FAILED, ("Failed to connect to PSU on {}".format(serialPort),) ) )
else:
self._sendUpdateEvent( UpdateEvent(PSUGUIUpdateEvent.PSU_CONNECT_FAILED, ("Failed to connect to PSU on {}".format(serialPort),) ) )
self.setStatus("Failed to connect to PSU.")