コード例 #1
0
    def _plot(self):
        """ Network performance graph """
        setConfigOption('background', '#FF000000')
        _graph = PlotWidget()
        _graph.setMenuEnabled(enableMenu=False)
        _graph.setMouseEnabled(x=False, y=False)
        _graph.hideButtons()

        self._out_curve = _graph.getPlotItem().plot()
        self._inc_curve = _graph.getPlotItem().plot()

        self._legend = LegendItem(offset=(50, 10))
        self._legend.setParentItem(_graph.getPlotItem())
        self._legend.addItem(self._out_curve, self._lang.NetworkGraphOutgoing)
        self._legend.addItem(self._inc_curve, self._lang.NetworkGraphIncoming)

        self._base.net_perf_lyt.addWidget(_graph)

        self._menu_popup = QMenu()
        _action = QAction(QIcon('icon/reload.png'), self._lang.PopupReload,
                          self._base.net_perf_box)
        _action.triggered.connect(self.reload)
        self._menu_popup.addAction(_action)

        self._base.net_perf_box.setContextMenuPolicy(Qt.CustomContextMenu)
        self._base.net_perf_box.customContextMenuRequested.connect(
            self._popup_show)
コード例 #2
0
class Ui_plotWindow(object):
    def setupUi(self, plotWindow):
        plotWindow.setObjectName(_fromUtf8("plotWindow"))
        plotWindow.resize(540, 350)
        plotWindow.setMaximumSize(QtCore.QSize(16777215, 16777215))

        self.gridLayout = QtGui.QGridLayout(plotWindow)
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))

        self.graphicsView = PlotWidget(plotWindow)

        self.graphicsView.hideButtons()
        self.graphicsView.showGrid(True, True)
        self.graphicsView.setMenuEnabled(False)
        self.graphicsView.setMouseEnabled(False, False)

        self.graphicsView.setFrameShadow(QtGui.QFrame.Plain)
        self.graphicsView.setFrameShape(QtGui.QFrame.StyledPanel)
        self.graphicsView.setObjectName(_fromUtf8("graphicsView"))

        self.gridLayout.addWidget(self.graphicsView, 0, 1, 1, 1)

        self.treeWidget = QtGui.QTreeWidget(plotWindow)
        self.treeWidget.setMaximumSize(QtCore.QSize(200, 16777215))
        self.treeWidget.setHorizontalScrollBarPolicy(
            QtCore.Qt.ScrollBarAlwaysOff)
        self.treeWidget.setRootIsDecorated(False)
        self.treeWidget.setItemsExpandable(False)
        self.treeWidget.setExpandsOnDoubleClick(False)
        self.treeWidget.setColumnCount(3)
        self.treeWidget.setObjectName(_fromUtf8("treeWidget"))
        self.treeWidget.header().setVisible(True)
        self.treeWidget.header().setDefaultSectionSize(80)

        self.gridLayout.addWidget(self.treeWidget, 0, 0, 1, 1)

        self.retranslateUi(plotWindow)
        QtCore.QMetaObject.connectSlotsByName(plotWindow)

    def retranslateUi(self, plotWindow):
        plotWindow.setWindowTitle(
            QtGui.QApplication.translate("plotWindow", "Form", None,
                                         QtGui.QApplication.UnicodeUTF8))
        self.treeWidget.headerItem().setText(
            0,
            QtGui.QApplication.translate("plotWindow", "Legend", None,
                                         QtGui.QApplication.UnicodeUTF8))
        self.treeWidget.headerItem().setText(
            1,
            QtGui.QApplication.translate("plotWindow", "Name", None,
                                         QtGui.QApplication.UnicodeUTF8))
        self.treeWidget.headerItem().setText(
            2,
            QtGui.QApplication.translate("plotWindow", "Value", None,
                                         QtGui.QApplication.UnicodeUTF8))
コード例 #3
0
class Ui_plotWindow(object):
    def setupUi(self, plotWindow):
        plotWindow.setObjectName(_fromUtf8("plotWindow"))
        plotWindow.resize(540, 350)
        plotWindow.setMaximumSize(QtCore.QSize(16777215, 16777215))

        self.gridLayout = QtGui.QGridLayout(plotWindow)
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))


        self.graphicsView = PlotWidget(plotWindow)

        self.graphicsView.hideButtons()
        self.graphicsView.showGrid(True, True)
        self.graphicsView.setMenuEnabled(False)
        self.graphicsView.setMouseEnabled(False, False)

        self.graphicsView.setFrameShadow(QtGui.QFrame.Plain)
        self.graphicsView.setFrameShape(QtGui.QFrame.StyledPanel)
        self.graphicsView.setObjectName(_fromUtf8("graphicsView"))

        self.gridLayout.addWidget(self.graphicsView, 0, 1, 1, 1)


        self.treeWidget = QtGui.QTreeWidget(plotWindow)
        self.treeWidget.setMaximumSize(QtCore.QSize(200, 16777215))
        self.treeWidget.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.treeWidget.setRootIsDecorated(False)
        self.treeWidget.setItemsExpandable(False)
        self.treeWidget.setExpandsOnDoubleClick(False)
        self.treeWidget.setColumnCount(3)
        self.treeWidget.setObjectName(_fromUtf8("treeWidget"))
        self.treeWidget.header().setVisible(True)
        self.treeWidget.header().setDefaultSectionSize(80)

        self.gridLayout.addWidget(self.treeWidget, 0, 0, 1, 1)

        self.retranslateUi(plotWindow)
        QtCore.QMetaObject.connectSlotsByName(plotWindow)

    def retranslateUi(self, plotWindow):
        plotWindow.setWindowTitle(QtGui.QApplication.translate("plotWindow", "Form", None, QtGui.QApplication.UnicodeUTF8))
        self.treeWidget.headerItem().setText(0, QtGui.QApplication.translate("plotWindow", "Legend", None, QtGui.QApplication.UnicodeUTF8))
        self.treeWidget.headerItem().setText(1, QtGui.QApplication.translate("plotWindow", "Name", None, QtGui.QApplication.UnicodeUTF8))
        self.treeWidget.headerItem().setText(2, QtGui.QApplication.translate("plotWindow", "Value", None, QtGui.QApplication.UnicodeUTF8))
コード例 #4
0
    def __init__(self, atri_plot: PlotWidget, vent_plot: PlotWidget, data_size: int):
        print("Graphs handler init")

        # noinspection PyArgumentList
        atri_plot.setRange(xRange=[-1, data_size], yRange=[-0.5, 5.5], padding=0)
        atri_plot.setLimits(xMin=-1, xMax=data_size, maxXRange=data_size + 1, yMin=-0.5, yMax=5.5)
        atri_plot.setMouseEnabled(x=True, y=False)
        atri_plot.enableAutoRange(x=False, y=True)
        atri_plot.setAutoVisible(x=False, y=True)
        atri_plot.showGrid(x=True, y=True)
        atri_plot.hideButtons()
        atri_plot.setMenuEnabled(False)
        atri_plot.setLabel('left', "Amplitude", units='V', **{'color': '#FFF', 'font-size': '10pt'})
        atri_plot.setLabel('bottom', "Time", units='s', **{'color': '#FFF', 'font-size': '10pt'})
        atri_plot.getAxis('bottom').setHeight(30)
        # noinspection PyArgumentList
        vent_plot.setRange(xRange=[-1, data_size], yRange=[-0.5, 5.5], padding=0)
        vent_plot.setLimits(xMin=-1, xMax=data_size, maxXRange=data_size + 1, yMin=-0.5, yMax=5.5)
        vent_plot.setMouseEnabled(x=True, y=False)
        vent_plot.enableAutoRange(x=False, y=True)
        vent_plot.setAutoVisible(x=False, y=True)
        vent_plot.showGrid(x=True, y=True)
        vent_plot.hideButtons()
        vent_plot.setMenuEnabled(False)
        vent_plot.setLabel('left', "Amplitude", units='V', **{'color': '#FFF', 'font-size': '10pt'})
        vent_plot.setLabel('bottom', "Time", units='s', **{'color': '#FFF', 'font-size': '10pt'})
        vent_plot.getAxis('bottom').setHeight(30)

        # Initialize graphs to 0
        self._atri_data = np.zeros(data_size)
        self._vent_data = np.zeros(data_size)

        # Create new sense plots for the atrial and ventricular graphs, in blue
        self._atri_plot = atri_plot.plot(pen=(0, 229, 255))
        self._vent_plot = vent_plot.plot(pen=(0, 229, 255))

        self._plot_data()
コード例 #5
0
class Ui_MainWindow(QtWidgets.QMainWindow):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setFixedSize(800, 618)

        MainWindow.setStyleSheet('background:#e8e8e8')

        #here starts widget setup, mostly just assigning locations and various properties
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.topDisplayDivider = QtWidgets.QFrame(self.centralwidget)
        self.topDisplayDivider.setGeometry(QtCore.QRect(0, 90, 801, 16))
        self.topDisplayDivider.setFrameShape(QtWidgets.QFrame.HLine)
        self.topDisplayDivider.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.topDisplayDivider.setObjectName("topDisplayDivider")
        self.menuDivider = QtWidgets.QFrame(self.centralwidget)
        self.menuDivider.setGeometry(QtCore.QRect(110, 100, 16, 501))
        self.menuDivider.setFrameShape(QtWidgets.QFrame.VLine)
        self.menuDivider.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.menuDivider.setObjectName("menuDivider")
        self.pushHistory = QtWidgets.QPushButton(self.centralwidget)
        self.pushHistory.setGeometry(QtCore.QRect(20, 140, 75, 23))
        self.pushHistory.setObjectName("pushHistory")
        self.pushHistory.setStyleSheet("border: 1px solid grey;")
        self.pushAnalytics = QtWidgets.QPushButton(self.centralwidget)
        self.pushAnalytics.setGeometry(QtCore.QRect(20, 210, 75, 23))
        self.pushAnalytics.setObjectName("pushAnalytics")
        self.pushExport = QtWidgets.QPushButton(self.centralwidget)
        self.pushExport.setGeometry(QtCore.QRect(20, 280, 75, 23))
        self.pushExport.setObjectName("pushExport")
        self.pushOptions = QtWidgets.QPushButton(self.centralwidget)
        self.pushOptions.setGeometry(QtCore.QRect(20, 350, 75, 23))
        self.pushOptions.setObjectName("pushOptions")

        self.pushLive = QtWidgets.QPushButton(self.centralwidget)
        self.pushLive.setGeometry(QtCore.QRect(20, 550, 75, 23))
        self.pushLive.setObjectName("pushLive")

        self.pushGraph = QtWidgets.QPushButton(self.centralwidget)
        self.pushGraph.setGeometry(QtCore.QRect(200, 550, 75, 23))
        self.pushGraph.setObjectName("pushGraph")

        self.pushGraph2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushGraph2.setGeometry(QtCore.QRect(300, 550, 75, 23))
        self.pushGraph2.setObjectName("pushGraph2")

        self.liveDisplay_1 = QtWidgets.QLabel(self.centralwidget)
        self.liveDisplay_1.setGeometry(QtCore.QRect(710, 20, 61, 61))
        self.liveDisplay_1.setObjectName("liveDisplay_1")
        self.liveDisplay_1.setStyleSheet("font: 30pt Arial MS")

        self.liveDisplay_2 = QtWidgets.QLabel(self.centralwidget)
        self.liveDisplay_2.setGeometry(QtCore.QRect(570, 20, 61, 61))
        self.liveDisplay_2.setObjectName("liveDisplay_2")
        self.liveDisplay_2.setStyleSheet("font: 30pt Arial MS")

        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(500, 20, 61, 61))
        self.label.setText("")
        self.label.setPixmap(QtGui.QPixmap("heart.png"))
        self.label.setScaledContents(True)
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(640, 20, 61, 61))
        self.label_2.setText("")
        self.label_2.setPixmap(QtGui.QPixmap("o2.png"))
        self.label_2.setScaledContents(True)
        self.label_2.setObjectName("label_2")
        self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox.setGeometry(QtCore.QRect(140, 120, 631, 311))
        self.groupBox.setObjectName("groupBox")
        self.label_3 = QtWidgets.QLabel(self.groupBox)
        self.label_3.setGeometry(QtCore.QRect(210, 110, 151, 31))
        self.label_3.setObjectName("label_3")

        self.dateTimeEdit = QtWidgets.QDateEdit(self.centralwidget)
        self.dateTimeEdit.setGeometry(QtCore.QRect(190, 490, 194, 22))
        self.dateTimeEdit.setObjectName("dateTimeEdit")
        self.dateTimeEdit.setDate(QDate.currentDate())

        self.label_6 = QtWidgets.QLabel(self.centralwidget)
        self.label_6.setGeometry(QtCore.QRect(40, 20, 251, 41))
        font = QtGui.QFont()
        font.setPointSize(19)
        self.label_6.setFont(font)
        self.label_6.setObjectName("label_6")

        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        #creating graphs
        self.graphWidgetLive = PlotWidget(self.centralwidget)
        self.graphWidgetLive.setGeometry(QtCore.QRect(40, 10, 400, 70))
        self.graphWidgetLive.setObjectName("graphWidgetLive")
        self.graphWidgetLive.getPlotItem().hideAxis('bottom')
        self.graphWidgetLive.setMouseEnabled(x=False, y=False)
        self.graphWidgetLive.setYRange(0, 150, padding=0.2)
        self.graphWidgetLive.getPlotItem().hideAxis('bottom')

        self.graphWidgetMain = PlotWidget(self.centralwidget)
        self.graphWidgetMain.setGeometry(QtCore.QRect(150, 140, 600, 275))
        self.graphWidgetMain.setObjectName("graphWidgetLive")
        self.graphWidgetMain.setMouseEnabled(x=True, y=False)
        self.graphWidgetMain.setYRange(50, 150, padding=0)
        self.graphWidgetMain.getPlotItem().hideAxis('bottom')

        self.graphWidgetLive.setBackground('w')

        pen = pg.mkPen(color=(255, 0, 0), width=2)
        pen2 = pg.mkPen(color=(0, 0, 255), width=2)
        time = [1, 2, 3, 4]
        heartRate = [90, 87, 88, 85]
        oxygenLevel = [100, 99, 99, 98]
        self.graphWidgetMain.setBackground('w')
        self.graphWidgetMain.plot(time, heartRate, pen=pen)
        self.graphWidgetMain.plot(time, oxygenLevel, pen=pen2)

        #these two values can be changed in options and are parameters for the windows notifications
        self.notifThresh = [120, 95]
        self.notifCooldown = 25

        self.serialInput = False

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        #connecting buttons
        self.pushAnalytics.clicked.connect(self.show_Analysis)

        self.pushExport.clicked.connect(self.show_export)

        self.pushOptions.clicked.connect(self.show_popOptions)

        self.pushLive.setCheckable(True)
        self.pushLive.clicked.connect(self.show_graphLive)

        self.pushGraph.clicked.connect(self.fromFile)
        self.pushGraph2.clicked.connect(self.fromDate)

    def update_plot_data(self):

        #this is used to update the live graph by reading from serial or the debugging simulator

        self.timeLive = self.timeLive[1:]  # Remove the first y element.
        self.timeLive.append(self.timeLive[-1] +
                             1)  # Add a new value 1 higher than the last.

        if self.serialInput == True:
            serialData = serial_connection.getSerial()
        else:
            serialData = (singleGenerate(79, 3), singleGenerate(97, 1))

        if serialData[0] != 0:
            self.liveHR = self.liveHR[1:]  # Remove the first
            self.liveHR.append(serialData[0])
            self.liveDisplay_2.setText(str(self.liveHR[99]))

        if serialData[1] != 0:
            self.liveO2 = self.liveO2[1:]  # Remove the first
            self.liveO2.append(serialData[1])
            self.liveDisplay_1.setText(str(self.liveO2[99]))

        if not (serialData[0] == 0 & serialData[1] == 0):
            datasystem.data_store(serialData[0], serialData[1])

        a = datetime.datetime.now()
        b = self.startTime
        c = a - b
        print(c.total_seconds())
        if c.total_seconds() > self.notifCooldown:
            if self.notifThresh[0] < serialData[0]:
                windowsalert.sendNotifH()
                self.startTime = datetime.datetime.now()

            if self.notifThresh[1] > serialData[1] & serialData[1] != 0:
                windowsalert.sendNotifO()
                self.startTime = datetime.datetime.now()

        self.data_line_1.setData(self.timeLive,
                                 self.liveHR)  # Update the data.
        self.data_line_2.setData(self.timeLive,
                                 self.liveO2)  # Update the data.

    def show_export(self):
        #used to call the zipping function in datasystem.py, and the file dialog
        options = QFileDialog.Options() | QFileDialog.DontUseNativeDialog
        fileName = QFileDialog.getSaveFileName(self,
                                               "Select an export location",
                                               "",
                                               "Zip Files (*.zip)",
                                               options=options)
        datasystem.data_zip(fileName[0] + '.zip')

    def show_graphLive(self):
        #connects to the button for live, and also controls if the graph/reading is enabled

        self.timeLive = list(range(100))  # 100 time points
        self.liveHR = [0] * 100
        self.liveO2 = [0] * 100
        self.startTime = datetime.datetime.now() - datetime.timedelta(
            seconds=self.notifCooldown)
        print(self.startTime)

        pen = pg.mkPen(color=(255, 0, 0), width=2)
        pen2 = pg.mkPen(color=(0, 0, 255), width=2)

        self.liveDisplay_2.setText('0')
        self.liveDisplay_1.setText('0')

        if self.pushLive.isChecked():
            self.data_line_1 = self.graphWidgetLive.plot(self.timeLive,
                                                         self.liveHR,
                                                         pen=pen)
            self.data_line_2 = self.graphWidgetLive.plot(self.timeLive,
                                                         self.liveO2,
                                                         pen=pen2)
            self.timer = QtCore.QTimer()
            self.timer.setInterval(250)
            self.timer.timeout.connect(self.update_plot_data)
            self.timer.start()
            self.pushLive.setText('Stop')
        else:
            self.timer.stop()
            self.graphWidgetLive.clear()
            self.pushLive.setText('Start')

    def fromDate(self):
        #used to connect the date picker to the main graph
        x = self.dateTimeEdit.date().toPyDate()
        date = 'vitals' + str(x)
        directory = os.getcwd()
        foldername = directory + '\\vitalsmouse_userdata'
        self.importfile = foldername + '\\' + date + '.csv'

        self.show_graphMain()

    def fromFile(self):
        #used to connect the file dialog to the main graph
        options = QFileDialog.Options() | QFileDialog.DontUseNativeDialog
        fileName = QFileDialog.getOpenFileName(self,
                                               "Select a file to view",
                                               "",
                                               "CSV Files (*.csv)",
                                               options=options)
        self.importfile = fileName[0]

        self.show_graphMain()

    def show_graphMain(self):
        #loads the data from a file and displays it on the main graph

        print(self.importfile)

        self.graphWidgetMain.clear()

        maindata = datasystem.data_get(self.importfile)

        mainTime = maindata[0]
        mainHR = maindata[1]
        mainO2 = maindata[2]

        pen = pg.mkPen(color=(255, 0, 0), width=2)
        pen2 = pg.mkPen(color=(0, 0, 255), width=2)
        self.graphWidgetMain.setBackground('w')
        self.graphWidgetMain.plot(mainTime, mainHR, pen=pen)
        self.graphWidgetMain.plot(mainTime, mainO2, pen=pen2)

    def show_popOptions(self):
        #secondary window for options
        self.Options = QDialog()
        self.Options.resize(200, 250)

        self.input_label = QtWidgets.QLabel(self.Options)
        self.input_label.setGeometry(QtCore.QRect(10, 10, 61, 51))
        self.input_label.setObjectName("input_label")

        self.inputBox = QtWidgets.QComboBox(self.Options)
        self.inputBox.setGeometry(QtCore.QRect(80, 30, 69, 22))
        self.inputBox.setObjectName("inputBox")
        self.inputBox.addItem('Debug')
        self.inputBox.addItem('USB')

        self.notificationsBox = QtWidgets.QGroupBox(self.Options)
        self.notificationsBox.setGeometry(QtCore.QRect(0, 90, 211, 131))
        self.notificationsBox.setObjectName("notificationsBox")
        self.lineEdit = QtWidgets.QLineEdit(self.notificationsBox)
        self.lineEdit.setGeometry(QtCore.QRect(130, 30, 61, 20))
        self.lineEdit.setObjectName("lineEdit")
        self.hr_label = QtWidgets.QLabel(self.notificationsBox)
        self.hr_label.setGeometry(QtCore.QRect(6, 30, 111, 20))
        self.hr_label.setObjectName("hr_label")
        self.lineEdit_2 = QtWidgets.QLineEdit(self.notificationsBox)
        self.lineEdit_2.setGeometry(QtCore.QRect(130, 60, 61, 20))
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.lineEdit_3 = QtWidgets.QLineEdit(self.notificationsBox)
        self.lineEdit_3.setGeometry(QtCore.QRect(130, 90, 61, 20))
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.o2_label = QtWidgets.QLabel(self.notificationsBox)
        self.o2_label.setGeometry(QtCore.QRect(10, 60, 111, 20))
        self.o2_label.setObjectName("o2_label")
        self.cooldown_label = QtWidgets.QLabel(self.notificationsBox)
        self.cooldown_label.setGeometry(QtCore.QRect(10, 90, 111, 20))
        self.cooldown_label.setObjectName("cooldown_label")

        self.input_label.setText("Input mode")
        self.notificationsBox.setTitle(("Notifications"))
        self.lineEdit.setText(("110"))
        self.hr_label.setText(("Heartrate threshold"))
        self.lineEdit_2.setText(("95"))
        self.lineEdit_3.setText(("20"))
        self.o2_label.setText(("Oxygen threshold"))
        self.cooldown_label.setText(("Cooldown(seconds)"))

        self.Options.setWindowTitle("Options")
        self.Options.exec_()

        h = self.inputBox.currentText()

        if h == 'USB':
            self.serialInput = True
        else:
            self.serialInput = False

        heartThresh = self.lineEdit.text()
        o2Thresh = self.lineEdit_2.text()
        cool = self.lineEdit_3.text()

        self.notifThresh = (int(heartThresh), int(o2Thresh))
        self.notifCooldown = int(cool)

    def show_Analysis(self):
        #secondary window for analysis
        self.Analysis = QDialog()
        self.Analysis.resize(400, 400)

        self.dailyLine = QtWidgets.QLineEdit(self.Analysis)
        self.dailyLine.setGeometry(QtCore.QRect(210, 60, 113, 20))
        self.dailyLine.setReadOnly(True)
        self.dailyLine.setObjectName("dailyLine")
        self.yearly_label = QtWidgets.QLabel(self.Analysis)
        self.yearly_label.setGeometry(QtCore.QRect(40, 140, 101, 16))
        self.yearly_label.setObjectName("yearly_label")
        self.monthly_label = QtWidgets.QLabel(self.Analysis)
        self.monthly_label.setGeometry(QtCore.QRect(40, 100, 111, 16))
        self.monthly_label.setObjectName("monthly_label")
        self.monthlyLine = QtWidgets.QLineEdit(self.Analysis)
        self.monthlyLine.setGeometry(QtCore.QRect(210, 100, 113, 20))
        self.monthlyLine.setReadOnly(True)
        self.monthlyLine.setObjectName("monthlyLine")
        self.daily_label = QtWidgets.QLabel(self.Analysis)
        self.daily_label.setGeometry(QtCore.QRect(40, 60, 111, 16))
        self.daily_label.setObjectName("daily_label")
        self.yearlyLine = QtWidgets.QLineEdit(self.Analysis)
        self.yearlyLine.setGeometry(QtCore.QRect(210, 140, 113, 20))
        self.yearlyLine.setReadOnly(True)
        self.yearlyLine.setObjectName("yearlyLine")

        self.legend_label = QtWidgets.QLabel(self.Analysis)
        self.legend_label.setGeometry(QtCore.QRect(220, 20, 113, 20))
        self.legend_label.setObjectName("legend_label")
        self.legend_label.setText("Heartrate, Oxygen")

        self.graphWidgetAnalysis = PlotWidget(self.Analysis)
        self.graphWidgetAnalysis.setGeometry(QtCore.QRect(50, 200, 300, 150))
        self.graphWidgetAnalysis.setObjectName("graphWidgetLive")
        self.graphWidgetAnalysis.setMouseEnabled(x=False, y=False)
        self.graphWidgetAnalysis.setYRange(50, 150, padding=0)
        self.graphWidgetAnalysis.getPlotItem().hideAxis('bottom')

        analysis_data = datasystem.data_analysis()

        pen = pg.mkPen(color=(255, 0, 0), width=2)
        pen2 = pg.mkPen(color=(0, 0, 255), width=2)

        heartRate = analysis_data[3][0]
        oxygenLevel = analysis_data[3][1]

        length = len(heartRate)
        time = [int(z) for z in range(length)]
        self.graphWidgetAnalysis.setBackground('w')
        self.graphWidgetAnalysis.plot(time, heartRate, pen=pen)
        self.graphWidgetAnalysis.plot(time, oxygenLevel, pen=pen2)

        self.dailyLine.setText(
            str(round(analysis_data[0][0], 2)) + ', ' +
            str(round(analysis_data[0][1], 2)))
        self.monthlyLine.setText(
            str(round(analysis_data[1][0], 2)) + ', ' +
            str(round(analysis_data[1][1], 2)))
        self.yearlyLine.setText(
            str(round(analysis_data[2][0], 2)) + ', ' +
            str(round(analysis_data[2][1], 2)))

        self.yearly_label.setText("Yearly Average")
        self.monthly_label.setText("Monthly Average")
        self.daily_label.setText("Daily Average")

        self.Analysis.setWindowTitle("Analysis")

        self.Analysis.exec_()

    def retranslateUi(self, MainWindow):
        #this is a holdover from using pyuic5, not normally used like this
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushHistory.setText(_translate("MainWindow", "History"))
        self.pushAnalytics.setText(_translate("MainWindow", "Analytics"))
        self.pushExport.setText(_translate("MainWindow", "Export"))
        self.pushOptions.setText(_translate("MainWindow", "Options"))
        self.pushLive.setText(_translate("MainWindow", "Start"))
        self.pushGraph.setText(_translate("MainWindow", "From file"))
        self.pushGraph2.setText(_translate("MainWindow", "From date"))
        self.liveDisplay_1.setText("##")
        self.liveDisplay_2.setText("##")
        self.groupBox.setTitle(_translate("MainWindow", "History"))
コード例 #6
0
class Window(QtGui.QWidget):

    # Default application settings.
    period = 30
    analog_channel = 0
    trigger_channel = 8
    rate_index = 0
    out_string = 'Data'
    directory = os.path.dirname(os.path.realpath(__file__)) + '/data'
    settings_port = ''

    # Initialization of application variables.
    volts = []
    times = []
    port_name = ''
    last_multiple = period
    time = 0
    sweep = 0
    reading = False

    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # Replace default settings with settings from file.
        self.readSettings()

        # Initialize serial communication.
        self.ser = Serial()
        self.ser.baudrate = BAUD_RATE
        self.ser.timeout = TIMEOUT

        # Create graph for plotting data. Disable mouse by default.
        self.graph = PlotWidget()
        self.graph.hideAxis('bottom')
        self.graph.showAxis('bottom')
        self.graph.setMouseEnabled(False, False)
        self.graph.hideButtons()
        self.graph.setYRange(0, GRAPH_RANGE_Y)
        self.graph.setXRange(0, self.period)

        # Create user interface elements and connect them to corresponding functions.
        self.start_button = QtGui.QPushButton('Start')
        self.start_button.clicked.connect(self.startPlot)

        self.stop_button = QtGui.QPushButton('Stop')
        self.stop_button.clicked.connect(self.stopPlot)
        self.stop_button.setEnabled(False)
        self.stop_button.setCheckable(True)

        channel_label = QtGui.QLabel('Analog Channel')

        self.channel_box = QtGui.QSpinBox()
        self.channel_box.setValue(self.analog_channel)
        self.channel_box.valueChanged.connect(self.channel)
        self.channel(self.analog_channel)

        trigger_label = QtGui.QLabel('Trigger Channel')

        self.trigger_box = QtGui.QSpinBox()
        self.trigger_box.setValue(self.trigger_channel)
        self.trigger_box.valueChanged.connect(self.trigger)
        self.trigger(self.trigger_channel)

        rate_label = QtGui.QLabel('Data Acquisition Rate (Hz)')

        self.rate_box = QtGui.QComboBox()
        self.rate_box.addItems(['10', '20', '50', '100', '200', '250', '500'])
        self.rate_box.setCurrentIndex(self.rate_index)
        self.rate_box.currentIndexChanged.connect(self.refresh)
        self.refresh(self.rate_index)

        port_label = QtGui.QLabel('Serial Port')

        self.port_box = QtGui.QComboBox()
        # Find valid ports.
        self.refreshPorts()
        self.port_box.currentIndexChanged.connect(self.portChanged)
        # Check if previously used port is still valid.
        if self.settings_port != '':
            index = self.port_box.findText(self.settings_port)
            if index > -1:
                self.port_box.setCurrentIndex(index)
            else:
                self.port_name = ''

        self.refresh_button = QtGui.QPushButton('Refresh Ports')
        self.refresh_button.clicked.connect(self.refreshPorts)

        period_label = QtGui.QLabel('Graph Period (s)')

        self.period_box = QtGui.QSpinBox()
        self.period_box.setMaximum(1000000)
        self.period_box.setValue(self.period)
        self.period_box.valueChanged.connect(self.changePeriod)

        output_label = QtGui.QLabel('Data Output Prefix')

        self.output_edit = QtGui.QLineEdit()
        self.output_edit.setText(self.out_string)
        self.output_edit.editingFinished.connect(self.outputString)

        self.dir_button = QtGui.QPushButton('Choose Data Directory')
        self.dir_button.clicked.connect(self.chooseDirectory)

        # Add user interface elements to panel.
        button_box = QtGui.QVBoxLayout()
        button_box.addWidget(port_label)
        button_box.addWidget(self.port_box)
        button_box.addWidget(self.refresh_button)
        button_box.addWidget(channel_label)
        button_box.addWidget(self.channel_box)
        button_box.addWidget(trigger_label)
        button_box.addWidget(self.trigger_box)
        button_box.addWidget(rate_label)
        button_box.addWidget(self.rate_box)
        button_box.addWidget(period_label)
        button_box.addWidget(self.period_box)
        button_box.addWidget(output_label)
        button_box.addWidget(self.output_edit)
        button_box.addWidget(self.dir_button)
        # Displace start and stop buttons to bottom of panel.
        button_box.addStretch(1)
        button_box.addWidget(self.start_button)
        button_box.addWidget(self.stop_button)

        # Place panel on left side of application and graph on right.
        layout = QtGui.QHBoxLayout()
        layout.addLayout(button_box)
        layout.addWidget(self.graph, 1)

        self.setLayout(layout)

        # Create timers to control repeating functions.
        self.plot_timer = QtCore.QTimer(self)
        self.plot_timer.timeout.connect(self.plot)

        self.read_timer = QtCore.QTimer(self)
        self.read_timer.timeout.connect(self.read)

        self.trigger_timer = QtCore.QTimer(self)
        self.trigger_timer.timeout.connect(self.checkTrigger)
        self.trigger_timer.start()

    def refreshPorts(self):
        # Loop through com ports and try to open each.
        self.port_box.clear()
        for p in serial.tools.list_ports.comports():
            try:
                self.openPort(p[0])
                # If the port opened, add it to the list.
                if (self.ser.read() == READY_COMMAND):
                    self.port_box.addItem(p[0])
            except:
                pass
        if self.port_box.count() == 0:
            self.port_name = ''

    def closeEvent(self, event):
        # When user closes application, stop reading and save settings.
        if self.reading:
            self.stopPlot()

        settings = open(
            os.path.dirname(os.path.realpath(__file__)) + '/settings.dat',
            'w+')

        settings.write('PORT=' + self.port_name + '\n')
        settings.write('ANALOG_CHANNEL=' + str(self.analog_channel) + '\n')
        settings.write('DATA_RATE=' + str(self.rate_index) + '\n')
        settings.write('PERIOD=' + str(self.period) + '\n')
        settings.write('PREFIX=' + self.out_string + '\n')
        settings.write('DIRECTORY=' + self.directory + '\n')

        settings.close()
        event.accept()

    def read(self):
        # If full transmission of 6 bytes is available, read data from arduino.
        #print(self.ser.inWaiting())
        if (self.ser.inWaiting() >= 6):
            # Convert reading to voltage by using conversion factor 1 bit = 0.125 mV.
            volt = (4.096 * int(binascii.hexlify(self.ser.read(2)), 16) /
                    32768.0)
            #volt = 4.096*(int(self.ser.read(2).encode('hex'), 16)/32768.0)

            # Convert time reading from microseconds to seconds.
            #self.time += (int(self.ser.read(4).encode('hex'), 16)/1000000.0)
            self.time += (int(binascii.hexlify(self.ser.read(4)), 16) /
                          1000000.0)

            # If graph has reached edge, reset with new sweep.
            if (self.time > self.last_multiple):
                self.last_multiple += self.period
                self.newSweep()

            # Add readings to lists of readings.
            self.times.append(self.time)
            self.volts.append(volt)

    def plot(self):
        # Plot current lists of data on graph after clearing previous graph.
        self.graph.plot(self.times, self.volts, clear=True)

    def startPlot(self):
        if self.port_name == '':
            # If no ports are available, inform user and end function.
            warn = QtGui.QMessageBox()
            warn.setWindowTitle('Warning')
            warn.setText('No open ports.')
            warn.exec_()
            return
        if not self.ping():
            # If currently selected port is not open, warn user and end function.
            warn = QtGui.QMessageBox()
            warn.setWindowTitle('Warning')
            warn.setText('Could not connect to port: ' + self.ser.port)
            warn.exec_()
            return
        if (self.period *
                int(self.rate_box.itemText(self.rate_box.currentIndex())) >
                20000):
            # If the user chose too large of a period, inform user and end function.
            # This is in place to avoid memory issues caused by overly large lists of data.
            warn = QtGui.QMessageBox()
            warn.setWindowTitle('Warning')
            warn.setText('Period too large for current data acquisition rate.\n\n'\
                    'Maximum Periods:\n'\
                    '10\tHz\t\t\t2,000\ts\n'\
                    '20\tHz\t\t\t1,000\ts\n'\
                    '50\tHz\t\t\t400\ts\n'\
                    '100\tHz\t\t\t200\ts\n'\
                    '200\tHz\t\t\t100\ts\n'\
                    '250\tHz\t\t\t80\ts\n'\
                    '500\tHz\t\t\t40\ts')
            warn.exec_()
            return

        self.reading = True

        # Send current pin and data rate to the arduino.
        self.ser.write(PIN_COMMAND)
        self.ser.write(bytes(str(self.analog_channel), 'utf_8'))
        self.ser.write(b'\n')

        self.ser.write(RATE_COMMAND)
        self.ser.write(
            bytes(str(int(self.rate_box.itemText(self.rate_index))), 'utf_8'))
        self.ser.write(b'\n')

        # Reset data lists and graph variables to starting values.
        self.volts = []
        self.times = []
        self.sweep = 0
        self.time = 0
        self.last_multiple = self.period
        self.graph.setXRange(0, self.period)

        # Disable all user interface elements that should not be changed while acquiring data.
        self.start_button.setEnabled(False)
        self.channel_box.setEnabled(False)
        self.trigger_box.setEnabled(False)
        self.rate_box.setEnabled(False)
        self.period_box.setEnabled(False)
        self.port_box.setEnabled(False)
        self.output_edit.setEnabled(False)
        self.dir_button.setEnabled(False)

        # Enable stop button.
        self.stop_button.setEnabled(True)

        # Tell arduino to start reading, and start the timers to read and plot data.
        self.ser.write(READ_COMMAND)
        self.ser.flushInput()
        # Graph updates at 50 Hz to smoothly graph while avoiding performance issues.
        self.plot_timer.start(20)
        self.read_timer.start()

    def stopPlot(self):
        # Export the current sweep to data file.
        self.autoExport()
        if self.reading:
            # Stop timers from reading and plotting data.
            #self.plot_timer.stop()
            #self.read_timer.stop()
            self.reading = False

        # Re-enable user interface.
        self.start_button.setEnabled(True)
        self.channel_box.setEnabled(True)
        self.trigger_box.setEnabled(True)
        self.rate_box.setEnabled(True)
        self.period_box.setEnabled(True)
        self.port_box.setEnabled(True)
        self.output_edit.setEnabled(True)
        self.dir_button.setEnabled(True)

        # Disable stop button.
        self.stop_button.setEnabled(False)

        # If connection was not lost, tell arduino to stop reading.
        try:
            self.ser.write(READ_COMMAND)
            #self.ser.write(b'\n')
        except:
            pass

        # Stop timers from reading and plotting data.
        self.plot_timer.stop()
        self.read_timer.stop()

    def channel(self, new_channel):
        # Controls which channel arduino should read from.
        self.analog_channel = new_channel

    def trigger(self, new_channel):
        # Controls which channel arduino should read trigger from.
        self.trigger_channel = new_channel
        if self.ping():
            self.ser.write(TRIGGER_COMMAND)
            self.ser.write(bytes(self.trigger_channel))
            self.ser.write(b'\n')

    def refresh(self, rate_index):
        # Controls rate arduino should read at.
        self.rate_index = rate_index

    def openPort(self, port_name):
        # Close current port, reinitialize to new port, and attempt to open new port.
        self.ser.close()
        self.port_name = port_name
        self.ser.port = port_name
        self.ser.open()

    def portChanged(self, port_index):
        # When new port is chosen from list, try to open it.
        try:
            name = str(self.port_box.itemText(port_index))
            if self.port_name != name:
                self.openPort(name)
        except:
            pass

    def newSweep(self):
        # When graph reaches edge, dump data to file and reset for new sweep.
        self.autoExport()
        self.times = []
        self.volts = []
        self.sweep += 1
        self.graph.setXRange(self.period * self.sweep,
                             self.period * (self.sweep + 1))

    def autoExport(self):
        # Checks specified directory for data. If it doesn't exist, it is created.
        dir = self.directory + '/' + self.out_string
        if not os.path.exists(dir):
            os.makedirs(dir)
        # Creates or opens data file corresponding to current sweep of graph.
        f = open(
            dir + '/' + self.out_string + '_' + ('%03d' % self.sweep) + '.txt',
            'w')
        # Writes data to that file.
        for time, volt in zip(self.times, self.volts):
            f.write(str(time) + '\t' + str(volt) + '\n')
        f.close()

    def changePeriod(self, new_period):
        # Changes period of graph and sweep.
        self.period = new_period
        self.last_multiple = new_period
        self.graph.setXRange(0, new_period)

    def outputString(self):
        # Changes prefix of data files.
        self.out_string = str(self.output_edit.text())

    def chooseDirectory(self):
        # Opens dialog for user to choose where to save data.
        new_dir = str(
            QtGui.QFileDialog.getExistingDirectory(self, 'Select Directory'))
        if (new_dir):
            self.directory = new_dir

    def readSettings(self):
        # Open or create settings file.
        path = os.path.dirname(os.path.realpath(__file__)) + '/settings.dat'
        if os.path.exists(path):
            settings = open(path, 'r+')
        else:
            settings = open(path, 'w+')
        # Parse through file and read settings.
        for line in settings.readlines():
            key, value = line.split('=')
            value = value.rstrip()
            if (key == 'PORT'):
                self.settings_port = value
            elif (key == 'ANALOG_CHANNEL'):
                self.analog_channel = int(value)
            elif (key == 'DATA_RATE'):
                self.rate_index = int(value)
            elif (key == 'PERIOD'):
                self.period = int(value)
            elif (key == 'PREFIX'):
                self.out_string = value
            elif (key == 'DIRECTORY'):
                self.directory = value
        settings.close()

    def ping(self):
        # Check if arduino is still connected.
        try:
            self.ser.write(READY_COMMAND)
            return True
        except:
            return False

    def checkTrigger(self):
        #print(self.reading)
        '''
    #print(self.plot_timer.timerId())
    while self.reading == False and self.port_name != '':
      print("this stopped")
      #print(self.ser.inWaiting())
      self.plot_timer.stop()
      self.read_timer.stop()
      self.reading = False
      #if self.plot_timer.timerId() == -1 and self.read_timer.timerId() == -1 and self.ser.inWaiting:
      #  break
    #  if not self.ser.inWaiting():
    #    break
    '''

        if not self.reading and self.port_name != '' and self.ser.inWaiting(
        ) and not self.stop_button.isChecked():
            if self.ser.read() == READ_COMMAND:
                self.startPlot()
                self.ser.flushInput()
コード例 #7
0
class widget_mfi_lon_plot(QWidget):

    #-----------------------------------------------------------------------
    # DEFINE THE INITIALIZATION FUNCTION.
    #-----------------------------------------------------------------------

    def __init__(self, core):

        # Inherit all attributes of an instance of "QWidget".

        super(widget_mfi_lon_plot, self).__init__()

        # Store the Janus core.

        self.core = core

        # Prepare to respond to signals received from the core.

        self.connect(self.core, SIGNAL('janus_rset'), self.resp_rset)
        self.connect(self.core, SIGNAL('janus_chng_mfi'), self.resp_chng_mfi)

        # Initialize this widget's instance of "PlotWidget", which will
        # contain the plot of MFI magnetic field data.

        # Note.  The "QGridLayout" object given to this widget as its
        #        layout is essentially a dummy.  I could have just had
        #        this class inherit "PlotWidget", but I think that this
        #        gives me a bit more control (and a similar structure
        #        "janus_widget_fc_cup").

        self.setLayout(QGridLayout())

        self.plt = PlotWidget()
        self.layout().addWidget(self.plt)

        self.layout().setContentsMargins(0, 0, 0, 0)

        # Extract the individual elements of the "PlotWidget" object
        # (e.g., it's axes) for more convenient access later.

        self.vbx = self.plt.getViewBox()

        self.axs_x = self.plt.getAxis('bottom')
        self.axs_y = self.plt.getAxis('left')

        self.ptm = self.plt.getPlotItem()

        # Initialize and store the pens and fonts.

        self.pen_vbx = mkPen(color='k')
        self.pen_crv_lon = mkPen(color='#FFD700')

        self.fnt = self.core.app.font()

        # Configure the plot: disable automatic adjustments and
        # adjustments made by the user, change the background and
        # foreground colors, enable grid lines for both axes, label the
        # axes, adjust the tick font size, adjust the "AxisItem" sizes,
        # and add a margin around the entire plot.

        self.plt.disableAutoRange()
        self.plt.setMouseEnabled(False, False)
        self.plt.setMenuEnabled(False)
        self.plt.hideButtons()

        self.plt.setBackground('w')
        setConfigOption('foreground', 'k')

        #####self.plt.showGrid( True, True )

        labelStyle = {'color': 'k'}
        self.axs_x.setLabel('Time [s]', **labelStyle)
        self.axs_y.setLabel('Azim. [deg]', **labelStyle)

        self.axs_x.label.setFont(self.fnt)
        self.axs_y.label.setFont(self.fnt)

        self.axs_x.setTickFont(self.fnt)
        self.axs_y.setTickFont(self.fnt)

        self.axs_x.setHeight(35)
        self.axs_y.setWidth(40)

        self.vbx.border = self.pen_vbx

        self.ptm.setContentsMargins(5, 5, 5, 5)

        # Initialize the curves that will be added to this plot.

        self.crv_lon = None

        # Populate this plot and adjust it's settings.

        self.make_plt()

    #-----------------------------------------------------------------------
    # DEFINE THE FUNCTION FOR POPULATING THE PLOT.
    #-----------------------------------------------------------------------

    def make_plt(self):

        # Reset the plot (i.e., remove all plot elements).

        self.rset_plt()

        # Establish the ranges of its time and magnetic field values.
        # If the core contains no data or only a single datum,
        # improvise (for the purpose of later establishing axis limits).

        if (self.core.n_mfi >= 1):

            # Establish the domain of the plot.

            t_min = min(amin(self.core.mfi_s), 0.)
            t_max = max(amax(self.core.mfi_s), self.core.fc_spec['dur'])

            # Establish the range of the plot.  As part of this,
            # ensure that the range satisfies a minimum size and has
            # sufficient padding.

            ang_max = max(self.core.mfi_b_lon)
            ang_min = min(self.core.mfi_b_lon)

            ang_max = 5. + ang_max
            ang_min = -5. + ang_min

            d_t_0 = t_max - t_min

            d_t = max(1.5 + d_t_0, 3.)

            t_max = t_min + d_t

        else:

            t_min = 0.001
            t_max = 3.500

            ang_min = -360
            ang_max = 360

        # Set the range of the axis of each plot.

        self.plt.setXRange(t_min, t_max, padding=0.0)
        self.plt.setYRange(ang_min, ang_max, padding=0.0)

        # If the core contains no Wind/MFI magnetic field data, return.

        if (self.core.n_mfi <= 0):
            return

        # Generate and display each curve for the plot.

        self.crv_lon = PlotDataItem(self.core.mfi_s,
                                    self.core.mfi_b_lon,
                                    pen=self.pen_crv_lon)

        self.plt.addItem(self.crv_lon)

    #-----------------------------------------------------------------------
    # DEFINE THE FUNCTION FOR RESETTING THIS PLOT (CLEARING ALL ELEMENTS).
    #-----------------------------------------------------------------------

    def rset_plt(self):

        # Hide and remove each of this plot's elements.

        if (self.crv_lon is not None):
            self.plt.removeItem(self.crv_lon)

        # Permanently delete this plot's elements by setting each of the
        # variables that store them to "None".

        self.crv_lon = None

    #-----------------------------------------------------------------------
    # DEFINE THE FUNCTION FOR RESPONDING TO THE "rset" SIGNAL.
    #-----------------------------------------------------------------------

    def resp_rset(self):

        # Reset the plot.

        self.rset_plt()

    #-----------------------------------------------------------------------
    # DEFINE THE FUNCTION FOR RESPONDING TO THE "chng_mfi" SIGNAL.
    #-----------------------------------------------------------------------

    def resp_chng_mfi(self):

        # Regenerate the plot.

        self.make_plt()
コード例 #8
0
class widget_mfi_lin_plot(QWidget):

    #-----------------------------------------------------------------------
    # DEFINE THE INITIALIZATION FUNCTION.
    #-----------------------------------------------------------------------

    def __init__(self, core):

        # Inherit all attributes of an instance of "QWidget".

        super(widget_mfi_lin_plot, self).__init__()

        # Store the Janus core.

        self.core = core

        # Prepare to respond to signals received from the core.

        self.connect(self.core, SIGNAL('janus_rset'), self.resp_rset)
        self.connect(self.core, SIGNAL('janus_chng_mfi'), self.resp_chng_mfi)

        # Initialize this widget's instance of "PlotWidget", which will
        # contain the plot of MFI magnetic field data.

        # Note.  The "QGridLayout" object given to this widget as its
        #        layout is essentially a dummy.  I could have just had
        #        this class inherit "PlotWidget", but I think that this
        #        gives me a bit more control (and a similar structure
        #        "janus_widget_fc_cup").

        self.setLayout(QGridLayout())

        self.plt = PlotWidget()
        self.layout().addWidget(self.plt)

        self.layout().setContentsMargins(0, 0, 0, 0)

        # Extract the individual elements of the "PlotWidget" object
        # (e.g., it's axes) for more convenient access later.

        self.vbx = self.plt.getViewBox()

        self.axs_x = self.plt.getAxis('bottom')
        self.axs_y = self.plt.getAxis('left')

        self.ptm = self.plt.getPlotItem()

        # Initialize and store the pens and fonts.

        self.pen_vbx = mkPen(color='k')
        self.pen_crv_m = mkPen(color='k')
        self.pen_crv_n = mkPen(color='k')
        self.pen_crv_x = mkPen(color='r')
        self.pen_crv_y = mkPen(color='g')
        self.pen_crv_z = mkPen(color='b')

        self.fnt = self.core.app.font()

        # Configure the plot: disable automatic adjustments and
        # adjustments made by the user, change the background and
        # foreground colors, enable grid lines for both axes, label the
        # axes, adjust the tick font size, adjust the "AxisItem" sizes,
        # and add a margin around the entire plot.

        self.plt.disableAutoRange()
        self.plt.setMouseEnabled(False, False)
        self.plt.setMenuEnabled(False)
        self.plt.hideButtons()

        self.plt.setBackground('w')
        setConfigOption('foreground', 'k')

        #####self.plt.showGrid( True, True )

        labelStyle = {'color': 'k'}
        self.axs_x.setLabel('Time [s]', **labelStyle)
        self.axs_y.setLabel('Magnetic Field [nT]', **labelStyle)

        self.axs_x.label.setFont(self.fnt)
        self.axs_y.label.setFont(self.fnt)

        self.axs_x.setTickFont(self.fnt)
        self.axs_y.setTickFont(self.fnt)

        self.axs_x.setHeight(35)
        self.axs_y.setWidth(40)

        self.vbx.border = self.pen_vbx

        self.ptm.setContentsMargins(5, 5, 5, 5)

        # Initialize the curves that will be added to this plot.

        self.crv_m = None
        self.crv_n = None
        self.crv_x = None
        self.crv_y = None
        self.crv_z = None
        self.pl = []

        # Populate this plot and adjust it's settings.

        self.make_plt()

    #-----------------------------------------------------------------------
    # DEFINE THE FUNCTION FOR POPULATING THE PLOT.
    #-----------------------------------------------------------------------

    def make_plt(self):

        # Reset the plot (i.e., remove all plot elements).

        self.rset_plt()

        # Establish the ranges of its time and magnetic field values.
        # If the core contains no data or only a single datum,
        # improvise (for the purpose of later establishing axis limits).

        if (self.core.n_mfi >= 1):

            # Establish the domain of the plot.

            t_min = min(amin(self.core.mfi_s), 0.)
            t_max = max(amax(self.core.mfi_s), self.core.fc_spec['dur'])

            # Establish the range of the plot.  As part of this,
            # ensure that the range satisfies a minimum size and has
            # sufficient padding.

            b_max = amax(self.core.mfi_b)
            b_min = -b_max

            d_t_0 = t_max - t_min
            d_b_0 = b_max - b_min

            d_t = max(1.5 + d_t_0, 3.)
            d_b = max(1.2 * d_b_0, 5.)

            t_max = t_min + d_t

            b_min = b_min - (d_b - d_b_0) / 2.
            b_max = b_max + (d_b - d_b_0) / 2.

        else:

            t_min = 0.001
            t_max = 3.500

            b_min = -2.5
            b_max = 2.5

        # Set the range of the axis of each plot.

        self.plt.setXRange(t_min, t_max, padding=0.0)
        self.plt.setYRange(b_min, b_max, padding=0.0)

        # Set the PESA-L pen with a width corresponding to one rotation
        # Note: For some reason, the lines are not wide enough unless 5
        #       is added to the scaled width of the rotation time

        rot = 3.05 * self.axs_x.width() / (t_max - t_min) + 5

        self.pen_pl = mkPen(color=(245, 245, 245), width=rot)

        # If the core contains no Wind/MFI magnetic field data, return.

        if (self.core.n_mfi <= 0):
            return

        # Generate and display each curve for the plot.

        self.crv_m = PlotDataItem(self.core.mfi_s,
                                  self.core.mfi_b,
                                  pen=self.pen_crv_m)
        self.crv_n = PlotDataItem(self.core.mfi_s,
                                  [-b for b in self.core.mfi_b],
                                  pen=self.pen_crv_n)
        self.crv_x = PlotDataItem(self.core.mfi_s,
                                  self.core.mfi_b_x,
                                  pen=self.pen_crv_x)
        self.crv_y = PlotDataItem(self.core.mfi_s,
                                  self.core.mfi_b_y,
                                  pen=self.pen_crv_y)
        self.crv_z = PlotDataItem(self.core.mfi_s,
                                  self.core.mfi_b_z,
                                  pen=self.pen_crv_z)

        # If PESA-L spectra were loaded, add the vertical indicators
        # showing their time relative to the start of the FC spectrum

        for n in range(len(self.core.pl_spec_arr)):

            time = self.core.pl_spec_arr[n]['time'][0]

            t_0 = self.core.fc_spec['time']

            delta_t = (time - t_0).total_seconds()

            self.pl += [
                InfiniteLine(delta_t + self.core.fc_spec['rot'] / 2.,
                             pen=self.pen_pl)
            ]

        for i in range(len(self.pl)):

            self.plt.addItem(self.pl[i])

        self.plt.addItem(self.crv_m)
        self.plt.addItem(self.crv_n)
        self.plt.addItem(self.crv_x)
        self.plt.addItem(self.crv_y)
        self.plt.addItem(self.crv_z)

    #-----------------------------------------------------------------------
    # DEFINE THE FUNCTION FOR RESETTING THIS PLOT (CLEARING ALL ELEMENTS).
    #-----------------------------------------------------------------------

    def rset_plt(self):

        # Hide and remove each of this plot's elements.

        if (self.crv_m is not None):
            self.plt.removeItem(self.crv_m)

        if (self.crv_n is not None):
            self.plt.removeItem(self.crv_n)

        if (self.crv_x is not None):
            self.plt.removeItem(self.crv_x)

        if (self.crv_y is not None):
            self.plt.removeItem(self.crv_y)

        if (self.crv_z is not None):
            self.plt.removeItem(self.crv_z)

        if (self.pl != []):

            for i in range(len(self.pl)):

                self.plt.removeItem(self.pl[i])

        # if ( self.crv_colat is not None ) :
        # 	self.plt.removeItem( self.crv_colat )

        # if ( self.crv_lon is not None ) :
        # 	self.plt.removeItem( self.crv_lon )

        # Permanently delete this plot's elements by setting each of the
        # variables that store them to "None".

        self.crv_m = None
        self.crv_n = None
        self.crv_x = None
        self.crv_y = None
        self.crv_z = None
        self.pl = []

    #-----------------------------------------------------------------------
    # DEFINE THE FUNCTION FOR RESPONDING TO THE "rset" SIGNAL.
    #-----------------------------------------------------------------------

    def resp_rset(self):

        # Reset the plot.

        self.rset_plt()

    #-----------------------------------------------------------------------
    # DEFINE THE FUNCTION FOR RESPONDING TO THE "chng_mfi" SIGNAL.
    #-----------------------------------------------------------------------

    def resp_chng_mfi(self):

        # Regenerate the plot.

        self.make_plt()
コード例 #9
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1103, 561)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.Connect_box = QtWidgets.QGroupBox(self.centralwidget)
        self.Connect_box.setGeometry(QtCore.QRect(10, 10, 191, 121))
        font = QtGui.QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.Connect_box.setFont(font)
        self.Connect_box.setObjectName("Connect_box")
        self.COM = QtWidgets.QComboBox(self.Connect_box)
        self.COM.setGeometry(QtCore.QRect(50, 30, 131, 22))
        font = QtGui.QFont()
        font.setPointSize(8)
        font.setBold(False)
        font.setWeight(50)
        self.COM.setFont(font)
        self.COM.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.COM.setObjectName("COM")
        self.COM.addItem("")
        self.COM.addItem("")
        self.COM.addItem("")
        self.COM.addItem("")
        self.COM.addItem("")
        self.COM.addItem("")
        self.connect = QtWidgets.QPushButton(self.Connect_box)
        self.connect.setGeometry(QtCore.QRect(20, 70, 151, 41))
        font = QtGui.QFont()
        font.setPointSize(9)
        font.setBold(False)
        font.setWeight(50)
        self.connect.setFont(font)
        self.connect.setObjectName("connect")
        self.label = QtWidgets.QLabel(self.Connect_box)
        self.label.setGeometry(QtCore.QRect(10, 30, 31, 21))
        font = QtGui.QFont()
        font.setPointSize(8)
        font.setBold(False)
        font.setWeight(50)
        self.label.setFont(font)
        self.label.setObjectName("label")
        self.Mode_box = QtWidgets.QGroupBox(self.centralwidget)
        self.Mode_box.setGeometry(QtCore.QRect(200, 10, 481, 121))
        font = QtGui.QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.Mode_box.setFont(font)
        self.Mode_box.setObjectName("Mode_box")
        self.Start = QtWidgets.QPushButton(self.Mode_box)
        self.Start.setGeometry(QtCore.QRect(10, 40, 101, 51))
        font = QtGui.QFont()
        font.setPointSize(9)
        font.setBold(False)
        font.setWeight(50)
        self.Start.setFont(font)
        self.Start.setObjectName("Start")
        self.Stop = QtWidgets.QPushButton(self.Mode_box)
        self.Stop.setGeometry(QtCore.QRect(130, 40, 101, 51))
        font = QtGui.QFont()
        font.setPointSize(9)
        font.setBold(False)
        font.setWeight(50)
        self.Stop.setFont(font)
        self.Stop.setObjectName("Stop")
        self.Reset = QtWidgets.QPushButton(self.Mode_box)
        self.Reset.setGeometry(QtCore.QRect(250, 40, 101, 51))
        font = QtGui.QFont()
        font.setPointSize(9)
        font.setBold(False)
        font.setWeight(50)
        self.Reset.setFont(font)
        self.Reset.setObjectName("Reset")
        self.draw_graph = QtWidgets.QPushButton(self.Mode_box)
        self.draw_graph.setGeometry(QtCore.QRect(370, 40, 101, 51))
        font = QtGui.QFont()
        font.setPointSize(10)
        font.setBold(False)
        font.setWeight(50)
        self.draw_graph.setFont(font)
        self.draw_graph.setObjectName("draw_graph")
        self.PIDStatus_box = QtWidgets.QGroupBox(self.centralwidget)
        self.PIDStatus_box.setGeometry(QtCore.QRect(680, 10, 411, 121))
        font = QtGui.QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.PIDStatus_box.setFont(font)
        self.PIDStatus_box.setObjectName("PIDStatus_box")
        self.label_6 = QtWidgets.QLabel(self.PIDStatus_box)
        self.label_6.setGeometry(QtCore.QRect(20, 30, 31, 31))
        font = QtGui.QFont()
        font.setFamily("MS Shell Dlg 2")
        font.setPointSize(10)
        font.setBold(False)
        font.setWeight(50)
        self.label_6.setFont(font)
        self.label_6.setObjectName("label_6")
        self.Kp_data = QtWidgets.QTextEdit(self.PIDStatus_box)
        self.Kp_data.setGeometry(QtCore.QRect(60, 30, 71, 31))
        font = QtGui.QFont()
        font.setBold(False)
        font.setWeight(50)
        self.Kp_data.setFont(font)
        self.Kp_data.setObjectName("Kp_data")
        self.label_7 = QtWidgets.QLabel(self.PIDStatus_box)
        self.label_7.setGeometry(QtCore.QRect(20, 80, 31, 31))
        font = QtGui.QFont()
        font.setFamily("MS Shell Dlg 2")
        font.setPointSize(10)
        font.setBold(False)
        font.setWeight(50)
        self.label_7.setFont(font)
        self.label_7.setObjectName("label_7")
        self.Ki_data = QtWidgets.QTextEdit(self.PIDStatus_box)
        self.Ki_data.setGeometry(QtCore.QRect(60, 80, 71, 31))
        font = QtGui.QFont()
        font.setBold(False)
        font.setWeight(50)
        self.Ki_data.setFont(font)
        self.Ki_data.setObjectName("Ki_data")
        self.label_8 = QtWidgets.QLabel(self.PIDStatus_box)
        self.label_8.setGeometry(QtCore.QRect(190, 30, 31, 31))
        font = QtGui.QFont()
        font.setFamily("MS Shell Dlg 2")
        font.setPointSize(10)
        font.setBold(False)
        font.setWeight(50)
        self.label_8.setFont(font)
        self.label_8.setObjectName("label_8")
        self.Kd_data = QtWidgets.QTextEdit(self.PIDStatus_box)
        self.Kd_data.setGeometry(QtCore.QRect(230, 30, 71, 31))
        font = QtGui.QFont()
        font.setBold(False)
        font.setWeight(50)
        self.Kd_data.setFont(font)
        self.Kd_data.setObjectName("Kd_data")
        self.label_9 = QtWidgets.QLabel(self.PIDStatus_box)
        self.label_9.setGeometry(QtCore.QRect(160, 80, 71, 31))
        font = QtGui.QFont()
        font.setFamily("MS Shell Dlg 2")
        font.setPointSize(10)
        font.setBold(False)
        font.setWeight(50)
        self.label_9.setFont(font)
        self.label_9.setObjectName("label_9")
        self.Setpoint_data = QtWidgets.QTextEdit(self.PIDStatus_box)
        self.Setpoint_data.setGeometry(QtCore.QRect(230, 80, 71, 31))
        font = QtGui.QFont()
        font.setBold(False)
        font.setWeight(50)
        self.Setpoint_data.setFont(font)
        self.Setpoint_data.setObjectName("Setpoint_data")
        self.send_PID = QtWidgets.QPushButton(self.PIDStatus_box)
        self.send_PID.setGeometry(QtCore.QRect(320, 80, 81, 31))
        font = QtGui.QFont()
        font.setPointSize(8)
        font.setBold(False)
        font.setWeight(50)
        self.send_PID.setFont(font)
        self.send_PID.setObjectName("send_PID")
        self.get_PID = QtWidgets.QPushButton(self.PIDStatus_box)
        self.get_PID.setGeometry(QtCore.QRect(320, 30, 81, 31))
        font = QtGui.QFont()
        font.setPointSize(8)
        font.setBold(False)
        font.setWeight(50)
        self.get_PID.setFont(font)
        self.get_PID.setObjectName("get_PID")
        self.Graph_box = QtWidgets.QGroupBox(self.centralwidget)
        self.Graph_box.setGeometry(QtCore.QRect(10, 130, 761, 401))
        font = QtGui.QFont()
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.Graph_box.setFont(font)
        self.Graph_box.setObjectName("Graph_box")
        self.tabWidget = QtWidgets.QTabWidget(self.Graph_box)
        self.tabWidget.setGeometry(QtCore.QRect(0, 20, 761, 381))
        self.tabWidget.setObjectName("tabWidget")
        self.Velocity_tab = QtWidgets.QWidget()
        self.Velocity_tab.setObjectName("Velocity_tab")
        self.Velocity_graph = PlotWidget(self.Velocity_tab)
        self.Velocity_graph.setGeometry(QtCore.QRect(10, 10, 741, 331))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
                                           QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.Velocity_graph.sizePolicy().hasHeightForWidth())
        self.Velocity_graph.setSizePolicy(sizePolicy)
        self.Velocity_graph.setObjectName("Velocity_graph")
        self.tabWidget.addTab(self.Velocity_tab, "")
        self.Position_tab = QtWidgets.QWidget()
        self.Position_tab.setObjectName("Position_tab")
        self.Position_graph = PlotWidget(self.Position_tab)
        self.Position_graph.setGeometry(QtCore.QRect(10, 10, 741, 331))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
                                           QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.Position_graph.sizePolicy().hasHeightForWidth())
        self.Position_graph.setSizePolicy(sizePolicy)
        self.Position_graph.setObjectName("Position_graph")
        self.tabWidget.addTab(self.Position_tab, "")
        self.groupBox_10 = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox_10.setGeometry(QtCore.QRect(770, 130, 321, 311))
        font = QtGui.QFont()
        font.setFamily("MS Shell Dlg 2")
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.groupBox_10.setFont(font)
        self.groupBox_10.setObjectName("groupBox_10")
        self.re_se_data = QtWidgets.QTextBrowser(self.groupBox_10)
        self.re_se_data.setEnabled(True)
        self.re_se_data.setGeometry(QtCore.QRect(10, 20, 301, 241))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed,
                                           QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.re_se_data.sizePolicy().hasHeightForWidth())
        self.re_se_data.setSizePolicy(sizePolicy)
        font = QtGui.QFont()
        font.setPointSize(8)
        font.setBold(False)
        font.setWeight(50)
        self.re_se_data.setFont(font)
        self.re_se_data.setObjectName("re_se_data")
        self.testsend = QtWidgets.QTextEdit(self.groupBox_10)
        self.testsend.setGeometry(QtCore.QRect(10, 270, 231, 31))
        font = QtGui.QFont()
        font.setPointSize(8)
        font.setBold(False)
        font.setWeight(50)
        self.testsend.setFont(font)
        self.testsend.setObjectName("testsend")
        self.send = QtWidgets.QPushButton(self.groupBox_10)
        self.send.setGeometry(QtCore.QRect(250, 270, 61, 31))
        font = QtGui.QFont()
        font.setPointSize(8)
        font.setBold(False)
        font.setWeight(50)
        self.send.setFont(font)
        self.send.setObjectName("send")
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.ser = serial.Serial()
        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(0)

        #connect serial
        self.connect.clicked.connect(self.clickedCONNECT)

        #enter mode
        self.Start.clicked.connect(self.clickedStart)
        self.Stop.clicked.connect(self.clickedStop)
        self.Reset.clicked.connect(self.clickedReset)

        #draw graph
        self.draw_graph.clicked.connect(self.clickeddrawgraph)

        #set up Position_graph
        self.Position_graph.setBackground('w')
        self.Position_graph.showGrid(x=True, y=True)
        self.Position_graph.setYRange(Y_min, Y_max, padding=0)
        self.Position_graph.setMouseEnabled(x=False, y=False)

        #set up Velocity_graph
        self.Velocity_graph.setBackground('w')
        self.Velocity_graph.showGrid(x=True, y=True)
        self.Velocity_graph.setYRange(Y_min, Y_max, padding=0)
        self.Velocity_graph.setMouseEnabled(x=False, y=False)

        #get PID status
        self.get_PID.clicked.connect(self.clickedgetPID)

        #transmit data
        # self.send.clicked.connect(self.clickedSEND)
        self.send_PID.clicked.connect(self.clickedsendPID)

        #set time for recive function
        self.timer_getdata = QtCore.QTimer()
        self.timer_getdata.setInterval(100)
        self.timer_getdata.timeout.connect(self.recive)

        #set time run system
        self.timer_run = QtCore.QTimer()
        self.timer_run.setInterval(1500)
        self.timer_run.timeout.connect(self.clickedCONNECT)

        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.Connect_box.setTitle(_translate("MainWindow", "Connect"))
        self.COM.setCurrentText(_translate("MainWindow", "COM1"))
        self.COM.setItemText(0, _translate("MainWindow", "COM1"))
        self.COM.setItemText(1, _translate("MainWindow", "COM2"))
        self.COM.setItemText(2, _translate("MainWindow", "COM3"))
        self.COM.setItemText(3, _translate("MainWindow", "COM4"))
        self.COM.setItemText(4, _translate("MainWindow", "COM5"))
        self.COM.setItemText(5, _translate("MainWindow", "COM6"))
        self.connect.setText(_translate("MainWindow", "CONNECT"))
        self.label.setText(_translate("MainWindow", "COM:"))
        self.Mode_box.setTitle(_translate("MainWindow", "Mode"))
        self.Start.setText(_translate("MainWindow", "START"))
        self.Stop.setText(_translate("MainWindow", "STOP"))
        self.Reset.setText(_translate("MainWindow", "RESET"))
        self.draw_graph.setText(_translate("MainWindow", "DRAW"))
        self.PIDStatus_box.setTitle(_translate("MainWindow", "PID Status"))
        self.label_6.setText(_translate("MainWindow", "Kp:"))
        self.Kp_data.setHtml(
            _translate(
                "MainWindow",
                "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
                "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
                "p, li { white-space: pre-wrap; }\n"
                "</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:10pt; font-weight:400; font-style:normal;\">\n"
                "<p align=\"center\" style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-weight:600;\"><br /></p></body></html>"
            ))
        self.label_7.setText(_translate("MainWindow", "Ki:"))
        self.Ki_data.setHtml(
            _translate(
                "MainWindow",
                "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
                "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
                "p, li { white-space: pre-wrap; }\n"
                "</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:10pt; font-weight:400; font-style:normal;\">\n"
                "<p align=\"center\" style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-weight:600;\"><br /></p></body></html>"
            ))
        self.label_8.setText(_translate("MainWindow", "Kd:"))
        self.Kd_data.setHtml(
            _translate(
                "MainWindow",
                "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
                "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
                "p, li { white-space: pre-wrap; }\n"
                "</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:10pt; font-weight:400; font-style:normal;\">\n"
                "<p align=\"center\" style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-weight:600;\"><br /></p></body></html>"
            ))
        self.label_9.setText(_translate("MainWindow", "Setpoint:"))
        self.Setpoint_data.setHtml(
            _translate(
                "MainWindow",
                "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
                "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
                "p, li { white-space: pre-wrap; }\n"
                "</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:10pt; font-weight:400; font-style:normal;\">\n"
                "<p align=\"center\" style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-weight:600;\"><br /></p></body></html>"
            ))
        self.send_PID.setText(_translate("MainWindow", "Send PID"))
        self.get_PID.setText(_translate("MainWindow", "Get PID"))
        self.Graph_box.setTitle(_translate("MainWindow", "Graph"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.Velocity_tab),
                                  _translate("MainWindow", "Velocity"))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.Position_tab),
                                  _translate("MainWindow", "Position"))
        self.groupBox_10.setTitle(
            _translate("MainWindow", "Received/Send data"))
        self.re_se_data.setHtml(
            _translate(
                "MainWindow",
                "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
                "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
                "p, li { white-space: pre-wrap; }\n"
                "</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8pt; font-weight:400; font-style:normal;\">\n"
                "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:8.25pt;\"><br /></p></body></html>"
            ))
        self.send.setText(_translate("MainWindow", "SEND"))

        #disable button, box
        self.Start.setEnabled(False)
        self.Stop.setEnabled(False)
        self.Reset.setEnabled(False)
        self.testsend.setEnabled(False)
        self.send.setEnabled(False)
        self.re_se_data.setEnabled(False)
        self.send_PID.setEnabled(False)
        # self.draw_graph.setEnabled(False)

    def clickedCONNECT(self):
        global comconnect, ser, i
        NameCOM = self.COM.currentText()
        try:
            if (comconnect == False):
                self.ser = serial.Serial(NameCOM, 115200, timeout=2.5)
                self.COM.setEnabled(False)
                self.Start.setEnabled(True)
                self.Stop.setEnabled(True)
                self.Reset.setEnabled(True)
                self.re_se_data.setEnabled(True)
                self.testsend.setEnabled(True)
                self.send.setEnabled(True)
                self.send_PID.setEnabled(True)
                self.draw_graph.setEnabled(False)
                self.connect.setText('DISCONNECT')
                self.connect.setStyleSheet('QPushButton {color: red;}')
                self.re_se_data.append('Serial port ' + NameCOM + ' opened')
                self.timer_getdata.start()
                comconnect = True
            else:
                self.COM.setEnabled(True)
                self.ser.close()
                self.Start.setEnabled(False)
                self.Stop.setEnabled(False)
                self.Reset.setEnabled(False)
                self.re_se_data.setEnabled(False)
                self.testsend.setEnabled(False)
                self.send.setEnabled(False)
                self.send_PID.setEnabled(False)
                self.draw_graph.setEnabled(True)
                self.connect.setText('CONNECT')
                self.connect.setStyleSheet('QPushButton {color: green;}')
                self.re_se_data.append('Serial port ' + NameCOM + ' closed')
                self.timer_getdata.stop()
                self.timer_run.stop()
                comconnect = False
                i = 0
        except IOError:
            if (comconnect == False):
                self.re_se_data.append('Serial port ' + NameCOM +
                                       ' opening error')
            else:
                self.re_se_data.append('Serial port ' + NameCOM +
                                       ' closing error')

    def clickedStart(self):
        self.re_se_data.append('Motor is runing')
        strs_tmp = ['0', '0', '\n']
        Startdata_send = ' '.join(strs_tmp)
        self.ser.write(Startdata_send.encode())
        #self.timer_run.start()

    def clickedStop(self):
        self.re_se_data.append('Motor stopped')
        strs_tmp = ['0', '1', '\n']
        Stopdata_send = ' '.join(strs_tmp)
        self.ser.write(Stopdata_send.encode())

    def clickedReset(self):
        global i, axis
        self.Position_graph.clear()
        self.Velocity_graph.clear()
        i = 1
        axis = []
        self.re_se_data.append('System reseted')
        strs_tmp = ['0', '2', '\n']
        Resetdata_send = ' '.join(strs_tmp)
        self.ser.write(Resetdata_send.encode())

    # def clickedSEND(self):
    #     datasend = self.testsend.toPlainText()
    #     self.re_se_data.append(datasend)
    #     self.ser.write('2'.encode())   #recognize the data test
    #     self.ser.write(datasend.encode())

    def clickedgetPID(self):
        global Kp_send, Ki_send, Kd_send, Setpoint_send, PID_send
        Kp_send = self.Kp_data.toPlainText()
        Ki_send = self.Ki_data.toPlainText()
        Kd_send = self.Kd_data.toPlainText()
        Setpoint_send = self.Setpoint_data.toPlainText()
        strs_tmp = ['1', Kp_send, Ki_send, Kd_send, Setpoint_send, '\n']
        PID_send = ' '.join(strs_tmp)

    def clickedsendPID(self):
        global Kp_send, Ki_send, Kd_send, Setpoint_send, PID_send
        self.ser.write(PID_send.encode())

    def recive(self):
        global axis, ser, i
        bytetoread = self.ser.inWaiting()
        try:
            if bytetoread > 0:
                receive_data = self.ser.read(bytetoread)
                axis = receive_data.split()
                axis_Velocity[i] = int(str(axis[0], 'UTF-8'))
                axis_Position[i] = int(str(axis[1], 'UTF-8'))
                self.re_se_data.append(str(axis[0], 'UTF-8'))
                self.re_se_data.append(str(axis[1], 'UTF-8'))
                i += 1
        except:
            self.re_se_data.append('bug roi con ga')

    def clickeddrawgraph(self):
        global axis_Position, axis_Velocity
        pen = pg.mkPen(color=(255, 0, 0), width=3)
        self.Velocity_graph.plot(time, axis_Velocity, pen=pen)
        self.Position_graph.plot(time, axis_Position, pen=pen)
コード例 #10
0
class StatsWindow(QWidget):

    def __init__(self):
        super().__init__()
        self.setGeometry(150 + 1024, 150, 800, 600)

        main_box = QVBoxLayout()

        self.graph_rfi = PlotWidget()
        self.graph_rfi.setBackground("w")
        self.graph_rfi.setTitle("RFI", color="k")
        self.graph_rfi.plot = self.graph_rfi.plot([0,0], [0],
                                                  pen=mkPen('k', width=1),
                                                  stepMode=True)
        self.graph_cand = PlotWidget()
        self.graph_cand.setBackground("w")
        self.graph_cand.setTitle("Candidates", color="k")
        self.graph_cand.plot = self.graph_cand.plot([0,0], [0],
                                                  pen=mkPen('k', width=1),
                                                  stepMode=True)

        self.dist_plot = PlotWidget()
        self.dist_plot.setMouseEnabled(y=False)
        self.dist_plot.setBackground("w")
        self.dist_plot.setTitle("Full distribution", color="k")
        self.dist_plot.plot = self.dist_plot.plot([0,0], [0],
                                                  pen=mkPen('k', width=1),
                                                  stepMode=True)


        plots_box = QHBoxLayout()
        plots_box.addWidget(self.graph_rfi)
        plots_box.addWidget(self.graph_cand)
        main_box.addLayout(plots_box)
        main_box.addWidget(self.dist_plot)

        limits_box = QHBoxLayout()
        limits_box.setAlignment(Qt.AlignLeft)
        
        self.limits_choice = QComboBox()
        self.limits_choice.addItems(["DM", "MJD"])
        self.limits_choice.setFixedWidth(100)
        limits_box.addWidget(self.limits_choice)
        self.start_limit = QLineEdit()
        self.start_limit.setPlaceholderText("from")
        self.start_limit.setFixedWidth(150)
        limits_box.addWidget(self.start_limit)
        self.end_limit = QLineEdit()
        self.end_limit.setPlaceholderText("to")
        self.end_limit.setFixedWidth(150)
        limits_box.addWidget(self.end_limit)
        self.apply_limits_button = QPushButton()
        self.apply_limits_button.setFixedWidth(150)
        self.apply_limits_button.setText("Remove limits")
        limits_box.addWidget(self.apply_limits_button)
        self.remove_label = QLabel()
        limits_box.addWidget(self.remove_label)
        main_box.addLayout(limits_box)
        

        self.setLayout(main_box)

    def _update(self, rfi_data, cand_data):

        y_rfi, x_rfi = histogram([cand[1] for cand in rfi_data],
                                 bins=min(len(rfi_data) + 1, 100))
        self.graph_rfi.plot.setData(x_rfi, y_rfi)

        y_cand, x_cand = histogram([cand[1] for cand in cand_data],
                                   bins=min(len(cand_data) + 1, 100))
        self.graph_cand.plot.setData(x_cand, y_cand)

    def update_dist_plot(self, data, extra_dec=False):

        y_dist, x_dist = histogram(data, bins=100)
        ax = self.dist_plot.getAxis("bottom")

        min_val = min(data)
        max_val = max(data)
        tick_vals = linspace(min_val, max_val, num=6)
        decimals = 2 + extra_dec * 4
        ticks = [(val, "{:.{dec}f}".format(val, dec=decimals)) for val in tick_vals]
        ax.setTicks( [ticks, []])
        ax.setStyle(tickLength=-5)
        self.dist_plot.plot.setData(x_dist, y_dist)
        self.dist_plot.autoRange()
コード例 #11
0
    def __init__(self, main_loop):
        # noinspection PyArgumentList
        super(ProgramUI, self).__init__()
        uic.loadUi("ui/USBIPManager.ui", self)
        self.show()
        # Setting application icon
        self.setWindowIcon(QIcon("icon/logo.png"))
        # Application main loop
        self.main_loop = main_loop
        # Getting the configuration from config.ini file
        self.config = config.get_config()

        self.cancel_process = CancelProcessButton(
            self.frameGeometry().width(),
            self.frameGeometry().height())
        self.cancel_process.setParent(None)

        # Setting actions for main menu buttons
        self.auto_find_button.clicked.connect(
            partial(ApplicationMenu.auto_find, self))
        self.add_server_button.clicked.connect(
            partial(ApplicationMenu.add_server, self))
        self.search_all_button.clicked.connect(
            partial(ApplicationMenu.search_all, self))
        self.connect_all_button.clicked.connect(
            partial(ApplicationMenu.connect_all, self))
        self.disconnect_all_button.clicked.connect(
            partial(ApplicationMenu.disconnect_all, self, config.usbip_array))
        self.settings_button.clicked.connect(
            partial(ApplicationMenu.settings, self))

        #
        self.log.setContextMenuPolicy(Qt.CustomContextMenu)
        self.log.customContextMenuRequested.connect(self.log_context_menu)

        # Setting context menu for the server list box
        self.server_box.setContextMenuPolicy(Qt.CustomContextMenu)
        self.server_box.customContextMenuRequested.connect(
            partial(SRVArea.box_context_menu, self))

        # Setting default context menu for the connected device tree box
        self.device_tree_menu = dict()
        self.device_tree_menu["menu"] = QMenu()
        self.device_tree_menu["action"] = dict()

        # Enabling data capture context action
        self.device_tree_menu["action"]["enable"] = \
            QAction(QIcon("icon/enable.png"), _("Enable data capturing"), self)
        self.device_tree_menu["action"]["enable"].setEnabled(False)

        # Resetting data capture context action
        self.device_tree_menu["action"]["reset"] = \
            QAction(QIcon("icon/reset.png"), _("Reset data capturing"), self)
        self.device_tree_menu["action"]["reset"].setEnabled(False)

        # Disabling data capture context action
        self.device_tree_menu["action"]["disable"] = \
            QAction(QIcon("icon/disable.png"), _("Disable data capturing"), self)
        self.device_tree_menu["action"]["disable"].setEnabled(False)

        #
        self.device_box.setContextMenuPolicy(Qt.CustomContextMenu)
        self.device_box.customContextMenuRequested.connect(
            partial(DevTreeMenu.box_context_menu, self))

        # Setting activity plot
        setConfigOption("background", "#FF000000")
        activity_graph = PlotWidget()
        activity_graph.setMenuEnabled(enableMenu=False)
        activity_graph.setMouseEnabled(x=False, y=False)
        activity_graph.showGrid(x=True, y=True)
        activity_graph.hideButtons()
        # Defining sent and received activity curves
        self.sent_curve = activity_graph.getPlotItem().plot()
        self.recv_curve = activity_graph.getPlotItem().plot()
        # Setting activity box layout and adding activity plot to the program window
        activity_layout = QGridLayout()
        self.activity_box.setLayout(activity_layout)
        activity_layout.addWidget(activity_graph)
        self.activity_box.setContextMenuPolicy(Qt.CustomContextMenu)
        self.activity_box.customContextMenuRequested.connect(
            partial(NetworkActivity.box_context_menu, self))

        # Getting the configuration and filling the server list with the found servers
        SRVArea.srv_get(self)
        # Starting checking servers availability process
        self.srv_checking = self.main_loop.create_task(
            SRVArea.async_srv_check(self))
        # Starting checking software cpu and memory usage process
        self.usage_checking = self.main_loop.create_task(async_sw_usage(self))
        # Starting checking network activity process
        self.activity_checking = self.main_loop.create_task(
            NetworkActivity.async_get_activity(self))

        if config.watchdog_enable:
            # Setting watchdog event handler as PyQt Object signal
            event_handler = ConfigWatchdog()
            event_handler.fileUpdated.connect(self.config_change_action)
            # Starting observer thread that schedules file watching and dispatches calls to event handler
            observer = Observer()
            observer.schedule(event_handler,
                              path=path.dirname(path.abspath(__file__)),
                              recursive=False)
            observer.start()