Esempio n. 1
0
class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.Start_PB.clicked.connect(self.setup_browserThread)

    def setup_browserSignals(self):
        self.txtBrowser.timer_done.connect(lambda: self.txtBrowser.update())
        self.txtBrowser.timer_stop.connect(self.txtBrowser.stop_timer)
        self.txtBrowser.error.connect(self.print_err)
        self.txtBrowser.finished.connect(self.thread.quit)
        #self.txtBrowser.finished.connect(self.txtBrowser.deleteLater)

    def setup_browserThread(self):
        self.txtBrowser = Browser(self.ui.Display_Brws, 1)
        self.ui.Stop_PB.clicked.connect(lambda: self.txtBrowser.stop())
        self.thread = QtCore.QThread()
        self.txtBrowser.moveToThread(self.thread)
        self.thread.started.connect(self.txtBrowser.start)
        self.thread.finished.connect(self.thread.deleteLater)
        self.setup_browserSignals()
        self.thread.start()

    @QtCore.Slot(str)
    def print_err(self, err: str):
        print(f"message from print_err: {err}")
Esempio n. 2
0
class logic_main(QMainWindow):
    signal_write_msg = QtCore.pyqtSignal(str, str)
    signal_operation_msg = QtCore.pyqtSignal(str, str)
    signal_query_msg = QtCore.pyqtSignal(str, str)
    def __init__(self, parent=None):
        #global tabNumber
        super().__init__(parent)
        self._mainui=Ui_MainWindow()
        self._mainui.setupUi(self)
        self.initUI()
        self.tcp_socket = None
        self.udp_socket = None
        self.client_socket_list = list()
        self.client_udpsocket_list = list()
        self.sever_th = None
        self.sever_thudp = None

        
    def initUI(self):
        self._mainui.actionaddcell.triggered.connect(cellnumdialog.show)
        self._mainui.actionlink.triggered.connect(linkdialog.show)
        self._mainui.actionchongqi.triggered.connect(rebootdialog.show)
        self._mainui.actionIMSI.triggered.connect(imsilistframe.initUI)
        self._mainui.actionnew_tab.triggered.connect(tabadd)
        self._mainui.cellcfgquery.triggered.connect(cellcfgquery)
        self._mainui.cellstatequery.triggered.connect(cellstatequery)
        self._mainui.pwrquery.triggered.connect(pwrquery)
        self._mainui.workmodequery.triggered.connect(workmodequery)
        #self._mainui.cellcfgf003.triggered.connect(cellcfgdialog.show)
        self._mainui.workmodef006.triggered.connect(workmodedialog.show)
        cellnumdialog._cellnum.pushButton_cellnum.clicked.connect(cellnumClicked)
        linkdialog._linkui.pushButton_link.clicked.connect(linkClicked)
        linkdialog._linkui.pushButton_dislink.clicked.connect(dislinkClicked)
        rebootdialog._rebootui.pushButton_reboot_ok.clicked.connect(rebootClicked)
        rebootdialog._rebootui.pushButton_reboot_cancel.clicked.connect(rebootdialog.close)
        cellcfgdialog._cellcfgui.pushButton_cellcfg_ok.clicked.connect(cellcfgClicked)
        cellcfgdialog._cellcfgui.pushButton_cellcfg_cancel.clicked.connect(cellcfgdialog.close)
        workmodedialog._workmodeui.pushButton_wl_work_ok.clicked.connect(workmodecfgClicked)
        workmodedialog._workmodeui.pushButton_wl_work_cancel.clicked.connect(workmodedialog.close)
        workmodedialog._workmodeui.pushButton_dw_work_ok.clicked.connect(workmodedwClicked)
        workmodedialog._workmodeui.pushButton_dw_work_cancel.clicked.connect(workmodedialog.close)
        self.signal_write_msg.connect(write_msg_heart)
        self.signal_operation_msg.connect(write_msg_operation)
        self.signal_query_msg.connect(write_msg_query)
        self.highlighter1 = Highlighter(self._mainui.plainTextEdit_5_tab1.document())
        self.highlighter2 = Highlighter(self._mainui.plainTextEdit_5_tab2.document())
        self.highlighter3 = Highlighter(self._mainui.plainTextEdit_5_tab3.document())
        self.highlighter21 = Highlighter(self._mainui.plainTextEdit_4_tab1.document())
        self.highlighter22 = Highlighter(self._mainui.plainTextEdit_4_tab2.document())
        self.highlighter23 = Highlighter(self._mainui.plainTextEdit_4_tab3.document())
        self.highlighter31 = Highlighter(self._mainui.plainTextEdit_3_tab1.document())
        self.highlighter32 = Highlighter(self._mainui.plainTextEdit_3_tab2.document())
        self.highlighter33 = Highlighter(self._mainui.plainTextEdit_3_tab3.document())
Esempio n. 3
0
    def __init__(self):
        super().__init__()
        Ui_MainWindow.setupUi(self, self)

        # model/state(scene)
        n1 = ShellEN(QPoint(200, 200), False)
        n2 = ShellIN(QPoint(300, 400), False)
        n1.connects.append(Neuron.Connect(10, 1, n2))
        group = Group([n1, n2])
        #~ s = group.serialize()
        #~ print(Group.unserialize(s))
        self.scene = MyScene(group, True)

        self.button_design.hide()
        self.button_pause.hide()
        self.mod = None  # 统一初始化,是个麻烦的问题

        self.d_or_t = 0  # design
        self.canvas.setScene(self.scene)

        self.t = 0

        self.toolbar = self.addToolBar('mytoolbar')
        self.toolbar.setMovable(False)

        serializeAction = QAction('&储存', self)  # QAction放哪都诡异
        serializeAction.setShortcut('Ctrl+S')
        serializeAction.setStatusTip('Serialize application')
        self.toolbar.addAction(serializeAction)

        serializeAction.triggered.connect(self.scene.serialize)

        unserializeAction = QAction('&读取', self)
        unserializeAction.setShortcut('Ctrl+O')
        unserializeAction.setStatusTip('Unserialize application')
        unserializeAction.triggered.connect(self.scene.unserialize)
        self.toolbar.addAction(unserializeAction)

        self.label.hide()  # 这些按钮是首屏不显示的
        self.label_2.hide()
        self.button_next.hide()
        self.button_continue.hide()

        self.choose_button(0)
Esempio n. 4
0
class PIDTuneMainWindow(QtGui.QMainWindow):
    """ Class wrapper for main window ui """
    def __init__(self):
        super(PIDTuneMainWindow, self).__init__()
        # Init vars
        self.closed_loop = None  # Closed Loop tf
        self.open_loop = None  # Open Loop tf
        # init
        self.setupUI()
        #init plot widgets
        self._proccess_plot = plt_.PlotWidget('Time Domain Proccess Graphs',
                                              x_label='t',
                                              y_label='mag')
        self._proccess_bode_plot = plt_.PlotWidget(
            'Freq Domain Proccess Graphs', 'log', x_label='w', y_label='mag')
        self._cl_plot = plt_.PlotWidget('Closed Loop Time Domain Graphs',
                                        x_label='t',
                                        y_label='mag')
        self._cl_bode_plot = plt_.PlotWidget('Closed Loop Freq Domain Graphs',
                                             'log',
                                             x_label='w',
                                             y_label='mag')
        self._cl_nyquist_plot = plt_.PlotWidget('Closed Loop Nyquist Graph',
                                                x_label='real',
                                                y_label='imag')

    def setupUI(self):
        # create window from ui
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.lblProccess.setStyleSheet(
            'QLabel {background-color : white; color : black;}')
        self.ui.lblPID.setStyleSheet(
            'QLabel {background-color : white; color : black;}')
        # setup toolbar
        # Proccess
        self.ui.mainToolBar.addAction(self.ui.actionProccessTF)
        self.ui.mainToolBar.addAction(self.ui.actionTime_Domain_Graph)
        self.ui.mainToolBar.addAction(self.ui.actionFreq_Domain_Graph)
        self.ui.mainToolBar.addSeparator()
        # PID
        self.ui.mainToolBar.addAction(self.ui.actionPID_Controller)
        self.ui.mainToolBar.addSeparator()
        # Closed Loop
        self.ui.mainToolBar.addAction(self.ui.actionCLTime_Domain_Graph)
        self.ui.mainToolBar.addAction(self.ui.actionCLFreq_Domain_Graph)
        self.ui.mainToolBar.addAction(self.ui.actionCLNyquist_Graph)
        self.ui.mainToolBar.addSeparator()
        # Var
        self.ui.mainToolBar.addAction(self.ui.actionReset_Models)
        self.ui.mainToolBar.addAction(self.ui.actionAbout)
        self.ui.mainToolBar.addAction(self.ui.actionExit)
        # setup dialogs
        self._about_dlg = PIDTuneAboutWindow()
        self._proccess_model_dlg = PIDProccessModelWindow()
        self._pid_ctrl_model_dlg = PIDCtrlModelWindow()
        # signals-slots
        self.ui.actionAbout.triggered.connect(self._about_dlg.show)
        self.ui.actionProccessTF.triggered.connect(
            self._proccess_model_dlg.open)
        self.connect(self._proccess_model_dlg,
                     QtCore.SIGNAL("proccess_tf_changed"),
                     self._proccess_model_changed)
        self.ui.actionPID_Controller.triggered.connect(
            self._pid_ctrl_model_dlg.open)
        self.connect(self._pid_ctrl_model_dlg, QtCore.SIGNAL("pid_tf_changed"),
                     self._pid_model_changed)
        self.ui.actionReset_Models.triggered.connect(self._reset_models)
        self.ui.actionTime_Domain_Graph.triggered.connect(
            self._proccess_time_graphs)
        self.ui.actionFreq_Domain_Graph.triggered.connect(
            self._proccess_freq_graphs)
        self.ui.actionCLTime_Domain_Graph.triggered.connect(
            self._cl_time_graphs)
        self.ui.actionCLFreq_Domain_Graph.triggered.connect(
            self._cl_freq_graphs)
        self.ui.actionCLNyquist_Graph.triggered.connect(self._cl_nyquist_graph)
        # show window
        self.show()
        logger.info("Main Window SetUp finished.")

    def _reset_models(self):
        ''' reset models '''
        # reset proccess model
        self._proccess_model_dlg.k = 0.0
        self._proccess_model_dlg.v1 = []
        self._proccess_model_dlg.v2 = []
        self._proccess_model_dlg.delay = 0.0
        self._proccess_model_dlg.pade = 1
        self._proccess_model_dlg.pade_tf = None
        self._proccess_model_dlg.tf = None
        self._proccess_model_changed()
        # reset pid
        self._pid_ctrl_model_dlg.kc = 0.0
        self._pid_ctrl_model_dlg.ti = 0.0
        self._pid_ctrl_model_dlg.td = 0.0
        self._pid_ctrl_model_dlg.tf = None
        self._pid_model_changed()

    def _proccess_model_changed(self):
        ''' proccess model changed '''
        self.ui.lblProccess.setText(
            str(self._proccess_model_dlg.tf) +
            '\nDelay : {0} s'.format(self._proccess_model_dlg.delay) +
            ', Pade : {0}'.format(self._proccess_model_dlg.pade_order))
        self._pid_ctrl_model_dlg.tf_proccess = self._proccess_model_dlg.tf
        self._cl_model_changed()
        if (self._proccess_plot.plot_dlg.isVisible()):
            self._proccess_time_graphs()
        if (self._proccess_bode_plot.plot_dlg.isVisible()):
            self._proccess_freq_graphs()
        logger.info("Proccess model changed.")

    def _pid_model_changed(self):
        ''' pid model changed '''
        self.ui.lblPID.setText(str(self._pid_ctrl_model_dlg.tf))
        self._cl_model_changed()
        logger.info("PID model changed.")

    def _cl_model_changed(self):
        ''' closed loop model changed
        FB(s) = Proccess * PID / (1 + Proccess * PID)
        open loop model changed
        FB(s) = Proccess * PID
        '''
        if (self._proccess_model_dlg.tf and self._pid_ctrl_model_dlg.tf):
            self.closed_loop = ctrl.TransferFunction()
            self.closed_loop.set_lti(
                ctrl.closed_loop_lti(self._proccess_model_dlg.tf.lti,
                                     self._pid_ctrl_model_dlg.tf.lti))
            self.open_loop = ctrl.TransferFunction()
            self.open_loop.set_lti(
                ctrl.mul_lti(self._proccess_model_dlg.tf.lti,
                             self._pid_ctrl_model_dlg.tf.lti))
        else:
            self.closed_loop = None
            self.open_loop = None
        if (self._cl_plot.plot_dlg.isVisible()):
            self._cl_time_graphs()
        if (self._cl_bode_plot.plot_dlg.isVisible()):
            self._cl_freq_graphs()
        if (self._cl_nyquist_plot.plot_dlg.isVisible()):
            self._cl_nyquist_graph()
        if (self.closed_loop):
            logger.info("Closed loop model changed.")
            logger.info("Closed loop Transfer Function = {0}".format(
                str(self.closed_loop)))
            logger.info("Open loop Transfer Function = {0}".format(
                str(self.open_loop)))

    def _proccess_time_graphs(self):
        ''' proccess model time domain graphs '''
        if (self._proccess_model_dlg.tf):
            self._proccess_plot.del_curves()
            t, y = self._proccess_model_dlg.tf.step()
            self._proccess_plot.add_curve(t, y, 'Step', 'b')
            t, y = self._proccess_model_dlg.tf.impulse()
            self._proccess_plot.add_curve(t, y, 'Impulse', 'r')
            self._proccess_plot.show()
            logger.info("Proccess Time Graphs opened.")
        else:
            logger.warning(
                "Proccess Time Graphs failed > Invalid Proccess Model.")
            Utils.errorMessageBox("Invalid Proccess Model")

    def _proccess_freq_graphs(self):
        ''' proccess model freq domain graphs '''
        if (self._proccess_model_dlg.tf):
            self._proccess_bode_plot.del_curves()
            w, mag, phase = self._proccess_model_dlg.tf.bode()
            self._proccess_bode_plot.add_curve(w, mag, 'Mag', 'b')
            self._proccess_bode_plot.add_curve(w, phase, 'Phase', 'r')
            self._proccess_bode_plot.show()
            logger.info("Proccess Freq Graphs opened.")
        else:
            logger.warning(
                "Proccess Freq Graphs failed > Invalid Proccess Model.")
            Utils.errorMessageBox("Invalid Proccess Model")

    def _cl_time_graphs(self):
        ''' closed loop model time domain graphs '''
        if (self.closed_loop):
            self._cl_plot.del_curves()
            t, y = self.closed_loop.step()
            self._cl_plot.add_curve(t, y, 'Step', 'b')
            t, y = self.closed_loop.impulse()
            self._cl_plot.add_curve(t, y, 'Impulse', 'r')
            self._cl_plot.show()
            logger.info("Closed loop Time Graphs opened.")
        else:
            logger.warning(
                "Closed loop Time Graphs failed > Invalid Proccess Model.")
            Utils.errorMessageBox("Invalid Closed Loop Model")

    def _cl_freq_graphs(self):
        ''' closed loop model freq domain graphs '''
        if (self.open_loop):
            self._cl_bode_plot.del_curves()
            w, mag, phase = self.open_loop.bode()
            self._cl_bode_plot.add_curve(w, mag, 'Mag', 'b')
            self._cl_bode_plot.add_curve(w, phase, 'Phase', 'r')
            self._cl_bode_plot.show()
            logger.info("Closed loop Freq Graphs opened.")
        else:
            logger.warning(
                "Closed loop Freq Graphs failed > Invalid Proccess Model.")
            Utils.errorMessageBox("Invalid Closed Loop Model")

    def _cl_nyquist_graph(self):
        ''' closed loop model nyquist graph '''
        if (self.open_loop):
            self._cl_nyquist_plot.del_curves()
            w, H = self.open_loop.nyquist()
            self._cl_nyquist_plot.add_curve(H.real, H.imag, 'Nyquist', 'b')
            self._cl_nyquist_plot.show()
            logger.info("Closed loop nyquist Graph opened.")
        else:
            logger.warning(
                "Closed loop nyquist Graph failed > Invalid Proccess Model.")
            Utils.errorMessageBox("Invalid Closed Loop Model")

    def closeEvent(self, event):
        ''' main window is closing '''
        logger.info("Main Window is closing.")
Esempio n. 5
0
class MainWindow(QMainWindow):
    def __init__(self, conn_file, nodes, chnlgrp, config):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        self.ui.splitter_cmdinfo.setStretchFactor(0, 1)
        self.ui.splitter_h.setStretchFactor(0, 1)
        self.ui.splitter_v.setStretchFactor(0, 1)
        self.__rightSideBar_isShrinked = False
        self.__rightSideBar_lastIndex = self.ui.tabWidget_rightSideBar.currentIndex()
        self.__bottomSideBar_isShrinked = False
        self.__bottomSideBar_lastIndex = self.ui.tabWidget_bottomSideBar.currentIndex()
        
        self.node = nodes
        self.config = config
        self.highlight = {}
        
        node = nodes['mnode'][0]
        root = QTreeWidgetItem(None, [node])
        if nodes['mnode'][1]:
            color = getattr(Qt, nodes['mnode'][1])
            self.highlight[node] = color
            root.setBackground(0, color)
        self.ui.treeWidget_node.addTopLevelItem(root)
        for k, v in nodes['node'].items():
            item = QTreeWidgetItem(root, [k])
            item.setTextAlignment(0, Qt.AlignRight)
            nodes['node'][k]['item'] = item
            if v['color']:
                color = getattr(Qt, v['color'])
                item.setBackground(0, color)
                self.highlight[k] = color
            self.ui.treeWidget_node.addTopLevelItem(item)
        if nodes['xnode']:
            root = QTreeWidgetItem(None, ['xnode'])
            root.setTextAlignment(0, Qt.AlignRight)
            self.ui.treeWidget_node.addTopLevelItem(root)
            for k, v in nodes['xnode'].items():
                item = QTreeWidgetItem(root, [k])
                if v:
                    color = getattr(Qt, v)
                    item.setBackground(0, color)
                    self.highlight[k] = color
                self.ui.treeWidget_node.addTopLevelItem(item)
        self.ui.treeWidget_node.expandAll()
        for i in range(self.ui.treeWidget_node.columnCount()):
             self.ui.treeWidget_node.resizeColumnToContents(i)

        if os.path.exists(config['rdebug']['mapfile']):
            self.rdbglst = rdebug.get_xval(config['rdebug']['mapfile'])
            for i in self.rdbglst:
                item = QTreeWidgetItem(None, [i[0], '%04X'%i[1],  str(i[2])])
                self.ui.treeWidget_rdbglst.addTopLevelItem(item)
                if i[0] == 'gParamData':
                    self.ui.treeWidget_rdbglst.setCurrentItem(item)
                    self.on_treeWidget_rdbglst_itemClicked(item, 0)
            for i in range(self.ui.treeWidget_rdbglst.columnCount()):
                 self.ui.treeWidget_rdbglst.resizeColumnToContents(i)
             
        self.rdbgidx = 0
        self.ui.comboBox_cmd.keyReleaseEvent = self.keyReleaseEvent
        
        self.buf = []
        self.conn = None
        if conn_file:
            if isinstance(conn_file, str):
                if os.path.exists(conn_file):
                    self.load_file(conn_file)
            else:
                self.conn = conn_file
                self.ui.comboBox_chnlgrp.setEnabled(True)
                self.ui.pushButton_parsepkt.setEnabled(True)
                self.ui.pushButton_rdbgsend.setEnabled(True)
                self.timer = QTimer(self)
                self.timer.timeout.connect(self.update)
                self.timer.start(100)     
                self.upgsrc = self.config['upgrade']['srcaddr'][:12].lstrip('0')
                self.txtimer = QTimer(self)
                self.txtimer.setSingleShot(True)
                self.txtimer.timeout.connect(self.txpacket)
                self.ui.comboBox_chnlgrp.setCurrentIndex(chnlgrp)
                sendchnls = config['DEFAULT']['sendchannel']
                self.__sendchnl = int(sendchnls, 16 if sendchnls.startswith('0x') else 10)

        self.__whosyourdaddy = os.path.exists('whosyourdaddy')
        if not self.__whosyourdaddy:
            self.ui.pushButton_rdbgsend.setEnabled(False)
            self.ui.pushButton_rfplcsw.setEnabled(False)
            

    def load_file(self, file):
        with open(file, 'rb') as f:
            self.buf = pickle.load(f)
            self.ui.treeWidget.clear()
            for i in self.buf:
                self.add_treeitem(i)
            for i in range(self.ui.treeWidget.columnCount()):
                 self.ui.treeWidget.resizeColumnToContents(i)

    def add_treeitem(self, rdata):
        item = QTreeWidgetItem(None, rdata[0])
        for i in range(6, 6+len(rdata[0][6:10])):
            if rdata[0][i] in self.highlight:
                item.setBackground(i, QBrush(self.highlight[rdata[0][i]]))
            item.setTextAlignment(i, Qt.AlignRight)
        self.ui.treeWidget.addTopLevelItem(item)
        # rowdata[0][?]: 6 - mdst, 7 - msrc, 8 - ndst, 9 - nsrc.
        if rdata[0][2] == 'acRdNdCfgUp':
            if rdata[0][9] in self.node['node']:
                self.node['node'][rdata[0][9]]['item'] .setText(1, rdata[1]['sVer'])
                self.ui.treeWidget_node.resizeColumnToContents(1)
        elif rdata[0][2] == 'acxRdVerInfoUp':
            if rdata[0][9] in self.node['node']:
                self.node['node'][rdata[0][9]]['item'] .setText(1, rdata[1]['sver'])
                self.node['node'][rdata[0][9]]['item'] .setText(2, rdata[1]['date'])
                self.node['node'][rdata[0][9]]['item'] .setText(3, rdata[1]['time'])
                self.ui.treeWidget_node.resizeColumnToContents(1)
                self.ui.treeWidget_node.resizeColumnToContents(2)
                self.ui.treeWidget_node.resizeColumnToContents(3)
        elif rdata[0][2].startswith('mcDbg'):
            if rdata[0][7] in self.node['node']:
                self.ui.plainTextEdit_rdbgresp.setPlainText(rdata[1]['dat'])
        
        #plainTextEdit
    def update(self):
        if self.conn.poll():
            msg = self.conn.recv()
            if msg[0] == 'pkt':
                if msg[1][0] == 'parsepkt':
                    if self.ui.treeWidget.topLevelItemCount() and self.ui.treeWidget.topLevelItem(0).text(0) == 'parsepkt':
                        self.ui.treeWidget.takeTopLevelItem(0)
                    item = QTreeWidgetItem(None, msg[1])
                    for i in range(self.ui.treeWidget.columnCount()):
                        item.setBackground(i, QBrush(Qt.green))
                        if 5 < i < 10:
                            item.setTextAlignment(i, Qt.AlignRight)
                    self.ui.treeWidget.insertTopLevelItem(0, item)
                    self.ui.treeWidget.scrollToTop()
                    self.parsepkt = msg[1:]
                else:
                    self.buf.append(msg[1:])
                    self.add_treeitem(msg[1:])
                    if self.ui.checkBox_autoscroll.isChecked():
                        self.ui.treeWidget.scrollToBottom()
                for i in range(self.ui.treeWidget.columnCount()):
                     self.ui.treeWidget.resizeColumnToContents(i)
            elif msg[0] == 'msg':
                self.ui.plainTextEdit_log.appendPlainText('[msg]%s.' % msg[1])
            elif msg[0] == 'err':
                self.ui.plainTextEdit_log.appendPlainText(msg[1])
            
    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_itemClicked(self, item, column):
        index = self.ui.treeWidget.indexOfTopLevelItem(item)
        self.ui.treeWidget_cmdinfo.clear()
        if self.ui.treeWidget.topLevelItem(0).text(0) == 'parsepkt':
            if index == 0:
                pktinfo = self.parsepkt
            else:
                pktinfo = self.buf[index-1]
        else:
            pktinfo = self.buf[index]
        if pktinfo[1]:
            self.ui.treeWidget_cmdinfo.addTopLevelItem(QTreeWidgetItem(None, ('cmdType', item.text(2))))
            self.ui.treeWidget_cmdinfo.addTopLevelItem(QTreeWidgetItem(None, ('--', '--')))
            for i in pktinfo[1].items():
                self.ui.treeWidget_cmdinfo.addTopLevelItem(QTreeWidgetItem(None, i))
            self.ui.treeWidget_cmdinfo.resizeColumnToContents(0)
        # routeLsg
        if column == 12:
            self.ui.plainTextEdit_pktdata.setPlainText(item.text(column))
        else:
            self.ui.plainTextEdit_pktdata.setPlainText(pktinfo[2])
        
    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_cmdinfo_itemClicked(self, item, column):
        self.ui.plainTextEdit_pktdata.setPlainText(item.text(1))
 
    @pyqtSlot(QPoint)
    def on_treeWidget_customContextMenuRequested(self, pos):
        popMenu =QMenu(self)
        if self.ui.treeWidget.itemAt(pos):
            column = self.ui.treeWidget.header().logicalIndexAt(pos)
            if 6 <= column <= 9:
                popMenu.addAction(self.ui.actionHighlight)  
                popMenu.addSeparator()
        if self.ui.treeWidget.topLevelItemCount():
            popMenu.addAction(self.ui.actionSaveAs)
            popMenu.addAction(self.ui.actionLoad)
            popMenu.addSeparator()
            popMenu.addAction(self.ui.actionClear)
        else:
            popMenu.addAction(self.ui.actionLoad)
        if self.ui.treeWidget.topLevelItemCount() and self.ui.treeWidget.topLevelItem(0).text(0) == 'parsepkt':
            popMenu.addSeparator()
            popMenu.addAction(self.ui.actionRmParsed)
        popMenu.popup(QCursor.pos())
        
    @pyqtSlot()
    def on_actionClear_triggered(self):
        self.buf = []
        self.ui.treeWidget.clear()
        
    @pyqtSlot()
    def on_actionSaveAs_triggered(self):
        t = datetime.now().strftime('%y-%m-%d_%H-%M-%S')
        file = QFileDialog.getSaveFileName(self, 'Save file', './dat/' + t, 'data file(*.dat)')[0]
        if file:
            with open(file, 'wb') as f:
                pickle.dump(self.buf, f)
            
    @pyqtSlot()
    def on_actionLoad_triggered(self):
        file = QFileDialog.getOpenFileName(self, 'Load file',  './dat',  'data file(*.dat)')[0]
        if file:
            self.load_file(file)
            
    @pyqtSlot()
    def on_actionHighlight_triggered(self):
        color = QColorDialog.getColor(parent=self)
        if color.isValid(): 
            item = self.ui.treeWidget.currentItem()
            column = self.ui.treeWidget.currentColumn()
            addr = item.text(column)
            self.highlight[addr] = color
            for i in range(self.ui.treeWidget.topLevelItemCount()):
                item = self.ui.treeWidget.topLevelItem(i)
                for j in range(6, 10):
                    if addr ==  item.text(j):
                        item.setBackground(j, color)

    @pyqtSlot()
    def on_actionRmParsed_triggered(self):
        self.ui.treeWidget.takeTopLevelItem(0)
        
    @pyqtSlot()
    def on_pushButton_parsepkt_clicked(self):
        text = self.ui.plainTextEdit_pktdata.toPlainText()
        self.conn.send(['parsepkt', bytearray.fromhex(text)])
            
    @pyqtSlot()
    def on_actionRdSnCfg_triggered(self):    
        if self.txtimer.isActive():
            self.ui.plainTextEdit_log.appendPlainText('Tx busy.')
            return
        self.txpkt = []
        for item in self.ui.treeWidget_node.selectedItems():
            addr = item.text(0)
            if addr in self.node['node']:
                self.txpkt.append(upgrade.mk_rdsncfg(addr, self.upgsrc))
                item.setText(1, '')
        if self.txpkt:
            self.txtimer.start(1000)
    
    @pyqtSlot()
    def on_actionRdVerInfo_triggered(self): 
        if self.txtimer.isActive():
            self.ui.plainTextEdit_log.appendPlainText('Tx busy.')
            return
        self.txpkt = []
        for item in self.ui.treeWidget_node.selectedItems():
            addr = item.text(0)
            if addr in self.node['node']:
                self.txpkt.append(upgrade.mk_rdverinfo(addr, self.upgsrc))
                item.setText(1, '')
        if self.txpkt:
            self.txtimer.start(1000)

    @pyqtSlot()
    def on_actionRdbgPoolType_triggered(self):
        self.ui.plainTextEdit_rdbgresp.setPlainText('') 
        items = self.ui.treeWidget_node.selectedItems()     
        if items:
            addr = items[0].text(0)
            self.rdbgidx += 1
            pkt = rdebug.mk_pooltype(addr, self.upgsrc, self.rdbgidx % 128)
            self.conn.send(['send',  self.__sendchnl, pkt])
            self.ui.plainTextEdit_log.appendPlainText('Tx:'+' '.join(['%02X'%i for i in pkt]))

    @pyqtSlot()
    def on_actionEraseParam_triggered(self):
        self.ui.plainTextEdit_rdbgresp.setPlainText('') 
        items = self.ui.treeWidget_node.selectedItems()     
        if items:
            addr = items[0].text(0)
            self.rdbgidx += 1
            pkt = rdebug.mk_eraseparam(addr, self.upgsrc, self.rdbgidx % 128)
            self.conn.send(['send',  self.__sendchnl, pkt])
            self.ui.plainTextEdit_log.appendPlainText('Tx:'+' '.join(['%02X'%i for i in pkt]))

    def txpacket(self):
        if self.txpkt:
            self.conn.send(['send',  self.__sendchnl, self.txpkt[0]])
            self.ui.plainTextEdit_log.appendPlainText('Tx:'+' '.join(['%02X'%i for i in self.txpkt[0]]))
            del self.txpkt[0]
            self.txtimer.start(1000)

    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_node_itemClicked(self, item, column):
        self.ui.lineEdit_curnode.setText(item.text(0))

    @pyqtSlot(QPoint)
    def on_treeWidget_node_customContextMenuRequested(self, pos):
        if self.conn and self.ui.treeWidget_node.selectedItems():
            popMenu =QMenu(self)
            popMenu.addAction(self.ui.actionRdSnCfg)
            popMenu.addAction(self.ui.actionRdVerInfo)
            if self.__whosyourdaddy:
                popMenu.addAction(self.ui.actionRdbgPoolType)
                popMenu.addSeparator()
                popMenu.addAction(self.ui.actionEraseParam)
            popMenu.popup(QCursor.pos())

    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_rdbglst_itemClicked(self, item, column):
        row = self.ui.treeWidget_rdbglst.indexOfTopLevelItem(item)
        self.ui.spinBox_rdbgaddr.setValue(self.rdbglst[row][1])
        len = self.rdbglst[row][2]
        val = len if len < 128 else 128
        self.ui.spinBox_rdbglen.setValue(val)

    @pyqtSlot()
    def on_pushButton_rdbgsend_clicked(self):
        self.ui.plainTextEdit_rdbgresp.setPlainText('')
        items = self.ui.treeWidget_node.selectedItems()    
        if items:
            addr = items[0].text(0)
            self.rdbgidx += 1
            pkt = rdebug.mk_rxval(addr, self.upgsrc, self.rdbgidx % 128, 
                self.ui.spinBox_rdbgaddr.value(), self.ui.spinBox_rdbglen.value())
            self.conn.send(['send',  self.__sendchnl, pkt])
            self.ui.plainTextEdit_log.appendPlainText('Tx:'+' '.join(['%02X'%i for i in pkt]))
        else:
            self.ui.plainTextEdit_log.appendPlainText('[rdbg]read xdata: Need select a node.')
            
    @pyqtSlot(int)
    def on_comboBox_chnlgrp_currentIndexChanged(self, index):
        self.conn.send(['setchnlgrp', index])
        self.ui.plainTextEdit_log.appendPlainText('[msg]channel group set to %i.' % index)

    @pyqtSlot()
    def on_pushButton_rfplcsw_clicked(self):
        rfplc = 0
        if self.ui.checkBox_rf.isChecked():
            rfplc += 1
        if self.ui.checkBox_plc.isChecked():
            rfplc += 2
        if rfplc:
            self.rdbgidx += 1
            pkt = rdebug.mk_rfplcswitch(self.ui.lineEdit_curnode.text(), self.upgsrc,  self.rdbgidx % 128, rfplc)
            self.conn.send(['send',  self.__sendchnl, pkt])
            self.ui.plainTextEdit_log.appendPlainText('Tx:'+' '.join(['%02X'%i for i in pkt]))
        else:
            self.ui.plainTextEdit_log.appendPlainText('[err]must select one in rf and plc.')

    def _CmdPro(self, s):
        if s.startswith('send '):
            cmd = s.split(maxsplit=2)
            if len(cmd) > 1:
#                try:
                    cmd[1] = int(cmd[1], 16)
                    cmd[2] = bytearray.fromhex(cmd[2])
                    self.conn.send(cmd)
                    self.ui.plainTextEdit_log.appendPlainText(
                        '[Tx]chnl(%i) %s.' % (cmd[1], ' '.join('%02X'%ii for ii in cmd[2])))
#                except:
#                    self.ui.plainTextEdit_log.appendPlainText('[error]send data error.\n')
        elif s.startswith('sendx '):
            cmd = s.split(maxsplit=3)
            if len(cmd) > 1:
#                        try:
                        cmd[1] = int(cmd[1], 16)
                        cmd[2] = int(cmd[2])
                        cmd[3] = bytearray.fromhex(cmd[3])
                        self.conn.send(cmd)
                        self.ui.plainTextEdit_log.appendPlainText(
                            '[Tx]chnl(%02X-%i) %s.' % (cmd[1], cmd[2], ' '.join('%02X'%ii for ii in cmd[3])))
#                        except:
#                            self.ui.plainTextEdit_log.appendPlainText('[error]send data error.\n')

    def keyReleaseEvent(self, e):
        key = e.key()
        if key == Qt.Key_Return:
            self._CmdPro(self.ui.comboBox_cmd.currentText())
            self.ui.comboBox_cmd.setCurrentText('')

    @pyqtSlot()
    def on_pushButton_send_clicked(self):
        if self.ui.pushButton_send.text() == '发送':
            if self.ui.checkBox_autosend.isChecked():
                self.autosendtimer = QTimer(self)
                self.autosendtimer.timeout.connect(self._AutoSend)  
                self.autosendtimer.start(self.ui.spinBox_sendInterval.value() * 1000)
                self.ui.pushButton_send.setText('停止')
            else:
                self._AutoSend()
        else:
            self.autosendtimer.stop()
            self.ui.pushButton_send.setText('发送')

    def _AutoSend(self):
        self._CmdPro(self.ui.comboBox_cmd.currentText())
    
    @pyqtSlot(int)
    def on_tabWidget_rightSideBar_tabBarClicked(self, index):        
        if self.__rightSideBar_isShrinked:
            self.ui.tabWidget_rightSideBar.resize(self.__rightSideBar_bigSize)
            minSize = max(self.__rightSideBar_minSize, self.ui.tabWidget_rightSideBar.minimumSizeHint().width())
            self.ui.tabWidget_rightSideBar.setMinimumWidth(minSize)
            self.ui.tabWidget_rightSideBar.setMaximumWidth(self.__rightSideBar_maxSize)
            self.ui.splitter_h.setSizes(self.__splitter_h_sizes)
            #self.ui.splitter_h.setStretchFactor(1, 1)
            self.__rightSideBar_isShrinked = False
        else:
            self.__rightSideBar_bigSize = self.ui.tabWidget_rightSideBar.size()
            if self.__rightSideBar_lastIndex == index:
                self.__rightSideBar_minSize = self.ui.tabWidget_rightSideBar.minimumSizeHint().width()
                self.__rightSideBar_maxSize = self.ui.tabWidget_rightSideBar.maximumWidth()
                self.__splitter_h_sizes = self.ui.splitter_h.sizes()
                self.ui.tabWidget_rightSideBar.setFixedWidth(self.ui.tabWidget_rightSideBar.tabBar().width())
                self.ui.splitter_h.setStretchFactor(1, 1)
                self.__rightSideBar_isShrinked = True
        self.ui.tabWidget_rightSideBar.setCurrentIndex(index)
        self.__rightSideBar_lastIndex = index
        
    @pyqtSlot(int)
    def on_tabWidget_bottomSideBar_tabBarClicked(self, index):        
        if self.__bottomSideBar_isShrinked:
            self.ui.tabWidget_bottomSideBar.resize(self.__bottomSideBar_bigSize)
            minSize = max(self.__bottomSideBar_minSize, self.ui.tabWidget_bottomSideBar.minimumSizeHint().height())
            self.ui.tabWidget_bottomSideBar.setMinimumHeight(minSize)
            self.ui.tabWidget_bottomSideBar.setMaximumHeight(self.__bottomSideBar_maxSize)
            self.ui.splitter_v.setSizes(self.__splitter_v_sizes)
            self.ui.splitter_v.setStretchFactor(1, 1)
            self.__bottomSideBar_isShrinked = False
        else:
            self.__bottomSideBar_bigSize = self.ui.tabWidget_bottomSideBar.size()
            if self.__bottomSideBar_lastIndex == index:
                self.__bottomSideBar_minSize = self.ui.tabWidget_bottomSideBar.minimumSizeHint().height()
                self.__bottomSideBar_maxSize = self.ui.tabWidget_bottomSideBar.maximumHeight()
                self.__splitter_v_sizes = self.ui.splitter_v.sizes()
                self.ui.tabWidget_bottomSideBar.setFixedHeight(self.ui.tabWidget_bottomSideBar.tabBar().height())
                self.ui.splitter_v.setStretchFactor(1, 1)
                self.__bottomSideBar_isShrinked = True
        self.ui.tabWidget_bottomSideBar.setCurrentIndex(index)
        self.__bottomSideBar_lastIndex = index
    
    @pyqtSlot()
    def on_pushButton_bcastAddr_clicked(self):
        self.ui.lineEdit_curnode.setText('FFFFFFFFFFFF')
Esempio n. 6
0
class QMyWin(QtWidgets.QMainWindow):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.resize(QGuiApplication.primaryScreen().availableSize() * 4 / 5);
        self.setWindowTitle("项目  v0.26")

###-----------------动作设置
        self.ui.actOpen.triggered.connect(self.openfile)
        self.ui.actCloseAPP.triggered.connect(self.close)

###-----------------tab页面设置
        self.ui.tabsignalDraw = QtWidgets.QWidget()
        self.ui.tabWidget.addTab(self.ui.tabsignalDraw,'信号')

        self.ui.tabsignalFFT = QtWidgets.QWidget()
        self.ui.tabWidget.addTab(self.ui.tabsignalFFT,'FFT')

        self.ui.tabRecord = QtWidgets.QWidget()
        self.ui.tabWidget.addTab(self.ui.tabRecord,'录音')

        self.ui.tabNeo4j = QtWidgets.QWidget()
        self.ui.tabWidget.addTab(self.ui.tabNeo4j,'Neo4j')

        self.__Tab1()
        self.__Tab2()
        self.__Tab3()
        self.__Tab4()



    def openfile(self):
        self.File = QtWidgets.QFileDialog.getOpenFileName(self,'选择文件','./','ALL(*.*);;媒体(*.mp3 *.wav)','媒体(*.mp3 *.wav)')


    def __Tab1(self):
        layout = QtWidgets.QHBoxLayout()
        draw = signalDraw()
        layout.addWidget(draw)
        self.ui.tabsignalDraw.setLayout(layout)

    def __Tab2(self):
        layout = QtWidgets.QHBoxLayout()
        fft = signalDraw()
        layout.addWidget(fft)
        self.ui.tabsignalFFT.setLayout(layout)

    def __Tab3(self):
        layout = QtWidgets.QHBoxLayout()
        wid = Recorder()
        layout.addWidget(wid)
        self.ui.tabRecord.setLayout(layout)

    def __Tab4(self):
        layout = QtWidgets.QHBoxLayout()
        Neo = neo4j()
        layout.addWidget(Neo)
        self.ui.tabNeo4j.setLayout(layout)
Esempio n. 7
0
class pymainWindow(QtGui.QMainWindow):
	def __init__(self, media, parent=None):
		QtGui.QMainWindow.__init__(self, parent)
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		# self.tabifyDockWidget(self.ui.dockWidgetUser, self.ui.dockWidgetRoom)
		self.tabifyDockWidget(self.ui.dockWidgetUser, self.ui.dockWidgetVoip)
		self.tabifyDockWidget(self.ui.dockWidgetVoip, self.ui.dockWidgetRoom)
		self.voipInterface = media["voip"]
		# self.ui.dockWidgetVoip.resize(self.ui.dockWidgetVoip.height(), 200)
		# self.voipInterface.setParent(self.ui.widgetVoip)
		self.ui.layoutVoip.addWidget(self.voipInterface)
		# self.ui.dockWidgetUser.show()
		self.mdi = QtGui.QWorkspace()
		self.addToolBar(self.voipInterface.ui.toolBar)
		self.ui.menuBar.addMenu(self.voipInterface.ui.menuVoip)
		self.voipInterface.ui.menuBar.setVisible(False)
		self.webWidget = webWidget(self)
		self.addToolBar(self.webWidget.toolBar)
		self.webWidget.toolBar.setVisible(False)
		self.ui.menuBar.addMenu(self.webWidget.menuWeb)
		self.webWidget.menuBar.setVisible(False)
		self.deleteMdiWin = 1				
		self.tabWidget = QtGui.QTabWidget()
		self.setCentralWidget(self.tabWidget)
# 		self.tabWidget.addTab(self.mdi, 'VideoSlots')
# 		self.tabWidget.addTab(self.webWidget, 'Web')
		# self.remoteDesktopWinEmbed=pyprocessWinEmbed()
		self.remoteDesktopInterface = pyvncInterface()
		self.addToolBar(self.remoteDesktopInterface.toolBar)
		# self.remoteDesktopInterface.toolBar.setVisible(False)
		self.ui.menuBar.addMenu(self.remoteDesktopInterface.menuRemoteScreen)
		self.remoteDesktopInterface.menuBar.setVisible(False)
		# jid che detiente attualmente il remote desktop
		

		self.tabWidget.addTab(self.mdi, 'VideoSlots')
		self.tabWidget.addTab(self.webWidget, 'Web')
		self.tabWidget.addTab(self.remoteDesktopInterface, 'RemoteScreen')
		self.streamSession = media["streamSession"]
		self.streamSession.numWin = -1
		self.mdi.addWindow(self.streamSession)
		self.streamSession.hide()
		# Definizione del dialog container di configurazioni
		self.configContainer = pydialogsContainer(self)
		self.configContainer.addDialog(self.streamSession.streamDialog)
		self.configContainer.addDialog(self.voipInterface.voipDialog)
		QtCore.QObject.connect(self.configContainer.closeButton, QtCore.SIGNAL("clicked()"), lambda:self.ui.actionConfigure.setChecked(False))
		QtCore.QObject.connect(self.voipInterface, QtCore.SIGNAL("configureRequest()"), lambda:self.configContainer.setCurrentDialog(self.voipInterface.voipDialog))
		QtCore.QObject.connect(self.voipInterface, QtCore.SIGNAL("configureRequest()"), self.configContainer.show)
# 		self.show()
		self.numPlayer = 0
		self.boxActivatedNumber = -1
		self.boxActivatedUser = None
		# QtCore.QObject.connect(self.ui.actionNew, QtCore.SIGNAL("triggered()"), self.newWindow)
		QtCore.QObject.connect(self.ui.actionTile, QtCore.SIGNAL("triggered()"), self.tile)
		QtCore.QObject.connect(self.ui.actionCascade, QtCore.SIGNAL("triggered()"), self.mdi, QtCore.SLOT("cascade()"))
# 		QtCore.QObject.connect(self.ui.actionDelete, QtCore.SIGNAL("triggered()"), self.mdi, QtCore.SLOT("closeActiveWindow()"))
		QtCore.QObject.connect(self.ui.actionSendVideo, QtCore.SIGNAL("toggled(bool)"), self.sendVideo)
		QtCore.QObject.connect(self.ui.actionSendDesktop, QtCore.SIGNAL("toggled(bool)"), self.sendDesktop)
		QtCore.QObject.connect(self.ui.actionConfigure, QtCore.SIGNAL("toggled(bool)"), self.configureManage)
		QtCore.QObject.connect(self.ui.actionVideoStream, QtCore.SIGNAL("toggled (bool)"), self.showStream)
		QtCore.QObject.connect(self.ui.lineEditRoomMsg, QtCore.SIGNAL("returnPressed()"), self.sendMsg)
		QtCore.QObject.connect(self.tabWidget, QtCore.SIGNAL("currentChanged (int)"), self.tabActivate)
		QtCore.QObject.connect(self.ui.toolBox, QtCore.SIGNAL("currentChanged (int)"), self.boxActivated)
		QtCore.QObject.connect(self.ui.listWidgetRoomBox, QtCore.SIGNAL("itemChanged (QListWidgetItem *)"), self.setRightMsgItem)
		QtCore.QObject.connect(self.ui.dockWidgetRoom, QtCore.SIGNAL("dockLocationChanged (Qt::DockWidgetArea)"), self.location)
		QtCore.QObject.connect(self.ui.dockWidgetRoom, QtCore.SIGNAL("void topLevelChanged (bool)"), self.location)
		
		self.iconConnected = QtGui.QIcon(self.ui.actionConnection.icon())		
		self.iconConnected.addPixmap(QtGui.QPixmap(":/new/prefix2/images/actions/connect_established.png"), QtGui.QIcon.Normal, QtGui.QIcon.On)
		self.iconDisconnected = QtGui.QIcon(self.ui.actionConnection.icon())		
		self.iconDisconnected.addPixmap(QtGui.QPixmap(":/new/prefix2/images/actions/connect_creating.png"), QtGui.QIcon.Normal, QtGui.QIcon.On)
		self.timer = QtCore.QTimer()
		self.timer.start(2000)
		self.lineEditRoomMsg = self.ui.lineEditRoomMsg
		self.sysTrayIcon = None
		if QtGui.QSystemTrayIcon.isSystemTrayAvailable():
			self.sysTrayMenu = QtGui.QMenu(self)
			self.sysTrayMenu.addAction(self.ui.actionExit)
			self.sysTrayIcon = QtGui.QSystemTrayIcon(self)
			self.sysTrayIcon.setIcon(self.windowIcon())
			self.sysTrayIcon.setContextMenu(self.sysTrayMenu)
			sysTrayToolTipMsg = QtCore.QString(self.tr("Sacks - Disconnected"))
			self.sysTrayIcon.setToolTip(sysTrayToolTipMsg)
			self.sysTrayIcon.show()
			QtCore.QObject.connect(self.sysTrayIcon, QtCore.SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), self.trayIconClick)
			
	def location(self, location):
		print location
		
		
		
	def trayIconClick(self, trayActivation):
		if trayActivation == QtGui.QSystemTrayIcon.Trigger:
			if self.isHidden():
				self.show()
			else:
				self.hide()
		
	def streamSessionInit(self, streamDestination):
		self.streamDestination = streamDestination
		
	def tabActivate(self, tabNumber):
		print tabNumber
		if tabNumber == 1:
			self.webWidget.toolBar.setVisible(True)
		else:
			self.webWidget.toolBar.setVisible(False)
# 		if tabNumber==2:
# 			self.remoteDesktopInterface.toolBar.setVisible(True)
# 		else:	
# 			self.remoteDesktopInterface.toolBar.setVisible(False)

	def boxActivated(self, boxNumber):
		print "boxActivated number: ", boxNumber
		for mdiWin in self.mdi.windowList():
			if mdiWin.numWin == boxNumber:
				self.mdi.setActiveWindow(mdiWin)
				
		if self.boxActivatedUser and (self.boxActivatedNumber != -1):
			self.ui.toolBox.setItemIcon(self.boxActivatedNumber, self.boxActivatedUser.iconUser)
		
		
		
		if boxNumber >= 0:
			boxActivatedUser = self.ui.toolBox.widget(boxNumber)
			boxActivatedUser.focusRequest(False)
			if boxNumber > 0:
				self.ui.toolBox.setItemIcon(boxNumber, boxActivatedUser.iconUser)				
				self.boxActivatedNumber = boxNumber
				self.boxActivatedUser = boxActivatedUser
		
	def tile(self):
		self.mdi.tile()
		self.mdi.exactHeight = 0
		for mdiWin in self.mdi.windowList():
			print mdiWin.height(), mdiWin.width()
			if mdiWin.height() < 1.1 * mdiWin.width() :
				self.mdi.exactHeight = mdiWin.height()
		
		for mdiWin in self.mdi.windowList():
			if mdiWin.height() > 1.1 * mdiWin.width() :
				if self.mdi.exactHeight:
					mdiWin.resize(mdiWin.width(), self.mdi.exactHeight)
				else:
					mdiWin.resize(mdiWin.width(), mdiWin.height() * 0.6)
		
	
	def sendVideo(self, streamChecked):
		
		if self.streamSession and self.streamDestination:
			print "streamChecked" + str(streamChecked)
			if streamChecked:
				streamInfoDict = {}
				print 'sendVideo'
				self.streamSession.stop()
				self.ui.actionSendDesktop.setChecked(False)
				self.streamSession.numWin = -1
			
				print "streamDestination" + str(self.streamDestination)
				streamInfoDict['streamDestination'] = self.streamDestination
				streamInfoDict['streamContent'] = "acquisitionVideo"
				self.streamSession.initialize(streamInfoDict)
				self.streamSession.start()
				self.ui.actionVideoStream.setChecked(True)
				self.streamSession.setWindowTitle('My Stream Video')
			else:
				self.streamSession.stop()
	

		
	def sendDesktop(self, streamChecked):
		if self.streamSession and self.streamDestination:
			if streamChecked:
				print 'sendDesktop'
				streamInfoDict = {}
				self.streamSession.stop()
				self.ui.actionSendVideo.setChecked(False)
				self.streamSession.numWin = -1
				print "streamDestination" + str(self.streamDestination)
				streamInfoDict['streamDestination'] = self.streamDestination
			# "intellicom.eushells.net"
				streamInfoDict['streamContent'] = "acquisitionDesktop"
			
				self.streamSession.initialize(streamInfoDict)
				print "in mezzo"
				self.streamSession.start()

				self.ui.actionVideoStream.setChecked(True)
				
				self.streamSession.setWindowTitle('My Stream Desktop')
			else:
				self.streamSession.stop()	
	
	def showStream(self, showStreamStatus):
		if showStreamStatus:
			self.streamSession.show()
		else:
			self.streamSession.hide()

	def activeStream(self, streamEnable):
		if streamEnable:
			self.ui.actionSendVideo.setEnabled(True)
			self.ui.actionSendDesktop.setEnabled(True)
		else:
			self.ui.actionSendVideo.setChecked(False)
			self.ui.actionSendDesktop.setChecked(False)
			self.ui.actionSendVideo.setEnabled(False)
			self.ui.actionSendDesktop.setEnabled(False)	


	def configureManage(self, configureEnable):
		if configureEnable:
			self.configContainer.show()
		else:
			self.configContainer.hide()
			
	
	def newWindow(self, userBox):
		if userBox:
			print "presenceUserBox" + str(self.ui.toolBox.indexOf(userBox))
			# verifica per controllare se il widget percaso era gia' nel toolbox
			if self.ui.toolBox.indexOf(userBox) == -1:
				userBox.boxIndex = self.ui.toolBox.addItem(userBox, userBox.nameSlot)
				self.ui.toolBox.setItemIcon(userBox.boxIndex, userBox.iconUser)
				userBoxMdiWin = userBox.mdiWin
				userBoxMdiWin.numWin = userBox.boxIndex
				userBoxMdiWin.setWindowTitle(userBox.nameSlot)
				self.numPlayer = self.numPlayer + 1
			else: 
				print "il toolBox era stato gia' occupato dal widget"


	def delWindow(self, userBox):
		if userBox:
			userBoxIndex = self.ui.toolBox.indexOf(userBox)
			self.ui.toolBox.removeItem(userBoxIndex)

	def sendMsg(self):
		msg = self.ui.lineEditRoomMsg.text()
		self.emit(QtCore.SIGNAL('msgOut'), msg)
		self.ui.lineEditRoomMsg.clear()
		
	def showMsg(self, msg):
		itemListWidget = QtGui.QListWidgetItem(msg)
		itemListWidget.msgText = msg
		itemListWidget.setFlags(QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled)
		
		self.ui.listWidgetRoomBox.addItem(itemListWidget)
		self.ui.listWidgetRoomBox.scrollToBottom() 
		
		
	def setRightMsgItem(self, itemListWidget):
		itemListWidget.setText(itemListWidget.msgText)
	

# metodo per rendere corrente il dockwidget passato
	def setCurrentDock(self, dockWidget):
		dockWidgetTitle = dockWidget.windowTitle()
		dockWidgetKeyPosition = dockWidgetTitle.indexOf("&")
		print "dockWidgetKeyPosition ", dockWidgetKeyPosition
		if dockWidgetKeyPosition >= 0:
			dockWidgetKey = dockWidgetTitle[dockWidgetKeyPosition + 1]
			print "dockWidgetKey ", dockWidgetKey
			# genera come evento il digitare la lettera scorciatoia nel titolo del dockWidget
			keyEvent = QtGui.QKeyEvent(QtCore.QEvent.KeyPress, 0, QtCore.Qt.AltModifier, dockWidgetKey)
			QtGui.QApplication.sendEvent(self, keyEvent);
			
	def closeEvent(self, closeEvent):
# 		self.mdi.closeAllWindows()	
		print "closeEvent MainWindow"
		self.streamSession.close()
		self.voipInterface.close()
		self.webWidget.close()
		self.sysTrayIcon.hide()
		numTotalUserBox = self.ui.toolBox.count()
		for userBoxIndex in range(numTotalUserBox):
			userBox = self.ui.toolBox.widget(userBoxIndex)
			userBox.closeEvent(0)
Esempio n. 8
0
class MyApp(QtWidgets.QMainWindow):
    def __init__(self):
        super(MyApp, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.set_def_button.clicked.connect(self.set_defaults)
        self.ui.run_button.clicked.connect(self.run)

        self.defaults = {
            "a1": 0.0134,
            "b1": 1,
            "c1": 4.35e-4,
            "m1": 1,
            "a2": 2.049,
            "b2": 0.563e-3,
            "c2": 0.528e5,
            "m2": 1,
            "alpha0": 0.05,
            "alphaN": 0.01,
            "l": 10,
            "T0": 300,
            "R": 0.5,
            "F0": 50,
            "h": 0.001,
            "t": 1
        }

        self.data = {
            "a1": None,
            "b1": None,
            "c1": None,
            "m1": None,
            "a2": None,
            "b2": None,
            "c2": None,
            "m2": None,
            "alpha0": None,
            "alphaN": None,
            "l": None,
            "T0": None,
            "R": None,
            "F0": None,
            "h": None,
            "t": None
        }

        self.set_defaults()

    def set_defaults(self):
        self.ui.lineEdit_a1.setText(str(self.defaults.get("a1")))
        self.ui.lineEdit_b1.setText(str(self.defaults.get("b1")))
        self.ui.lineEdit_c1.setText(str(self.defaults.get("c1")))
        self.ui.lineEdit_m1.setText(str(self.defaults.get("m1")))

        self.ui.lineEdit_a2.setText(str(self.defaults.get("a2")))
        self.ui.lineEdit_b2.setText(str(self.defaults.get("b2")))
        self.ui.lineEdit_c2.setText(str(self.defaults.get("c2")))
        self.ui.lineEdit_m2.setText(str(self.defaults.get("m2")))

        self.ui.lineEdit_alpha0.setText(str(self.defaults.get("alpha0")))
        self.ui.lineEdit_alphaN.setText(str(self.defaults.get("alphaN")))

        self.ui.lineEdit_l.setText(str(self.defaults.get("l")))
        self.ui.lineEdit_T0.setText(str(self.defaults.get("T0")))
        self.ui.lineEdit_R.setText(str(self.defaults.get("R")))
        self.ui.lineEdit_F0.setText(str(self.defaults.get("F0")))

        self.ui.lineEdit_h.setText(str(self.defaults.get("h")))
        self.ui.lineEdit_t.setText(str(self.defaults.get("t")))

    def get_data(self):
        try:
            self.data["a1"] = float(self.ui.lineEdit_a1.text())
            self.data["b1"] = float(self.ui.lineEdit_b1.text())
            self.data["c1"] = float(self.ui.lineEdit_c1.text())
            self.data["m1"] = float(self.ui.lineEdit_m1.text())

            self.data["a2"] = float(self.ui.lineEdit_a2.text())
            self.data["b2"] = float(self.ui.lineEdit_b2.text())
            self.data["c2"] = float(self.ui.lineEdit_c2.text())
            self.data["m2"] = float(self.ui.lineEdit_m2.text())

            self.data["alpha0"] = float(self.ui.lineEdit_alpha0.text())
            self.data["alphaN"] = float(self.ui.lineEdit_alphaN.text())

            self.data["l"] = float(self.ui.lineEdit_l.text())
            self.data["T0"] = float(self.ui.lineEdit_T0.text())
            self.data["R"] = float(self.ui.lineEdit_R.text())
            self.data["F0"] = float(self.ui.lineEdit_F0.text())

            self.data["h"] = float(self.ui.lineEdit_h.text())
            self.data["t"] = float(self.ui.lineEdit_t.text())

        except ValueError:
            return False
        return True

    def run(self):
        if self.get_data():
            print("Computing...")
            mdlr = Modeller(self.data)
            mdlr.compute()
            print("Finish.")
        else:
            self.msg_box("Error!", "Error! Incorrect input!",
                         QMessageBox.Critical)

    def msg_box(self, title, message, type):
        msg = QMessageBox(self)
        msg.setIcon(type)
        msg.setWindowTitle(title)
        msg.setText(message)
        msg.addButton('Ok', QMessageBox.AcceptRole)
        msg.exec()
Esempio n. 9
0
class ModSlaveMainWindow(QtWidgets.QMainWindow):
    """ Class wrapper for main window ui """
    def __init__(self):
        super(ModSlaveMainWindow, self).__init__()
        #init
        self.svr = None  # Server hosting one or more slaves
        self._svr_args = []
        self.slv = None  # Slave
        self._coils = 10
        self._coils_start_addr = 0
        self._inputs = 10
        self._inputs_start_addr = 0
        self._input_regs = 10
        self._input_regs_start_addr = 0
        self._hold_regs = 10
        self._hold_regs_start_addr = 0
        self._time_interval = 2000  # interval for simulation in msec
        self._modbus_mode = 1  # 1:RTU, 2:TCP
        self._modbus_slave_ID = 1
        self._logging_level = 30  # warning level
        self._params_file_name = 'pyModSlave.ini'
        self._logger = logging.getLogger("modbus_tk")
        self._logger.setLevel(0)  # start with no logging
        self._setupUI()

    def _setupUI(self):
        #create window from ui
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        #setup toolbar
        self.ui.mainToolBar.addAction(self.ui.actionLoad_Session)
        self.ui.mainToolBar.addAction(self.ui.actionSave_Session)
        self.ui.mainToolBar.addAction(self.ui.actionConnect)
        self.ui.mainToolBar.addAction(self.ui.actionReset_Counters)
        self.ui.mainToolBar.addSeparator()
        self.ui.mainToolBar.addAction(self.ui.actionLog)
        self.ui.mainToolBar.addAction(self.ui.actionBus_Monitor)
        self.ui.mainToolBar.addAction(self.ui.actionHeaders)
        self.ui.mainToolBar.addSeparator()
        self.ui.mainToolBar.addAction(self.ui.actionSerial_RTU)
        self.ui.mainToolBar.addAction(self.ui.actionTCP)
        self.ui.mainToolBar.addAction(self.ui.actionSettings)
        self.ui.mainToolBar.addSeparator()
        self.ui.mainToolBar.addAction(self.ui.actionModbus_Manual)
        self.ui.mainToolBar.addAction(self.ui.actionAbout)
        self.ui.mainToolBar.addAction(self.ui.actionExit)
        #setup status bar
        pm = QtGui.QPixmap()
        self.status_ind = QtWidgets.QLabel(self.ui.centralWidget)
        self.status_ind.setFixedSize(16, 16)
        self.status_ind.setPixmap(QtGui.QPixmap(':/img/bullet-red-16.png'))
        self.status_text = QtWidgets.QLabel(self.ui.centralWidget)
        self.status_packet_text = QtWidgets.QLabel(self.ui.centralWidget)
        self.status_packet_text.setStyleSheet("QLabel {color:blue;}")
        self.status_error_text = QtWidgets.QLabel(self.ui.centralWidget)
        self.status_error_text.setStyleSheet("QLabel {color:red;}")
        self.ui.statusBar.addWidget(self.status_ind)
        self.ui.statusBar.addWidget(self.status_text, 14)
        self.ui.statusBar.addWidget(self.status_packet_text, 14)
        self.ui.statusBar.addWidget(self.status_error_text, 14)
        #setup ui dialogs
        self._about_dlg = ModSlaveAboutWindow()
        self._settingsRTU_dlg = ModSlaveSettingsRTUWindow()
        self._settingsTCP_dlg = ModSlaveSettingsTCPWindow()
        self._settings_dlg = ModSlaveSettingsWindow()
        self._bus_monitor_dlg = ModSlaveBusMonitorWindow(self)
        #setup data controller
        self._mbdata_ctrl = ModSlaveMBData(self.ui)
        #signals-slots
        self.ui.actionLoad_Session.triggered.connect(self._load_session)
        self.ui.actionSave_Session.triggered.connect(self._save_session)
        self.ui.actionAbout.triggered.connect(self._about_dlg.show)
        self.ui.actionSerial_RTU.triggered.connect(self._settings_RTU_show)
        self.ui.actionTCP.triggered.connect(self._settings_TCP_show)
        self.ui.actionSettings.triggered.connect(self._settings_show)
        self.ui.actionBus_Monitor.triggered.connect(self._bus_monitor_show)
        self.ui.actionReset_Counters.triggered.connect(self._reset_counters)
        self.ui.actionLog.triggered.connect(self._open_log_file)
        self.ui.actionHeaders.triggered.connect(self._showHeaders)
        self.ui.actionModbus_Manual.triggered.connect(self._open_modbus_manual)
        self.ui.actionConnect.triggered.connect(self._start_stop)
        self.ui.cmbModbusMode.currentIndexChanged.connect(
            self._update_status_bar)
        self.ui.spInterval.valueChanged.connect(self._spInterval_value_changed)
        self._bus_monitor_dlg.update_counters.connect(self._update_counters)
        self.ui.cmbModbusMode.currentIndexChanged.connect(
            self._update_modbus_mode)
        #show window
        self._update_status_bar()
        self.show()

    def _settings_RTU_show(self):
        """open RTU settings dialog"""
        self._settingsRTU_dlg.ui.cmbPort.setEnabled(self.svr == None)
        self._settingsRTU_dlg.ui.cmbDev.setEnabled(self.svr == None)
        self._settingsRTU_dlg.ui.cmbBaud.setEnabled(self.svr == None)
        self._settingsRTU_dlg.ui.cmbDataBits.setEnabled(self.svr == None)
        self._settingsRTU_dlg.ui.cmbParity.setEnabled(self.svr == None)
        self._settingsRTU_dlg.ui.cmbStopBits.setEnabled(self.svr == None)
        self._settingsRTU_dlg.exec_()
        self._update_status_bar()

    def _settings_TCP_show(self):
        """open TCP settings dialog"""
        self._settingsTCP_dlg.ui.leIP.setEnabled(self.svr == None)
        self._settingsTCP_dlg.ui.leTCPPort.setEnabled(self.svr == None)
        self._settingsTCP_dlg.exec_()
        self._update_status_bar()

    def _settings_show(self):
        """open general settings dialog"""
        self._settings_dlg.ui.sbMaxNoOfBusMonitorLines.setEnabled(
            self.svr == None)
        self._settings_dlg.exec_()
        self._bus_monitor_dlg.set_max_no_of_bus_monitor_lines(
            self._settings_dlg.max_no_of_bus_monitor_lines)
        self._update_status_bar()

    def _mbdata_show(self):
        """coils data dialog"""
        self._mbdata_dlg.show()

    def _bus_monitor_show(self):
        """coils data dialog"""
        self._bus_monitor_dlg.svr = self.svr
        self._bus_monitor_dlg.move(self.x() + self.width() + 20, self.y())
        self._bus_monitor_dlg.show()

    def _spInterval_value_changed(self, value):
        """sim interval value changed"""
        self._time_interval = value

    def _update_status_bar(self):
        """update status bar"""
        if (self.ui.cmbModbusMode.currentText() == "TCP"):  #TCP server
            msg = "TCP : {0}:{1}".format(self._settingsTCP_dlg.tcp_ip,
                                         self._settingsTCP_dlg.tcp_port)
        elif (self.ui.cmbModbusMode.currentText() == "RTU"):  #RTU server
            msg = "RTU : {0}, {1}, {2}, {3}, {4}".format(
                self._settingsRTU_dlg.rtu_port,
                self._settingsRTU_dlg.baud_rate,
                self._settingsRTU_dlg.byte_size,
                self._settingsRTU_dlg.stop_bits, self._settingsRTU_dlg.parity)
        self.status_text.setText(msg)
        if (self.svr != None):  #server is running
            self.status_ind.setPixmap(
                QtGui.QPixmap(':/img/bullet-green-16.png'))
        else:  #server is stopped
            self.status_ind.setPixmap(QtGui.QPixmap(':/img/bullet-red-16.png'))
        self._update_counters()

    def _update_counters(self):
        """update packets - errors counters"""
        self.status_packet_text.setText('Packets : %d' %
                                        self._bus_monitor_dlg.packets)
        self.status_error_text.setText('Erros : %d' %
                                       self._bus_monitor_dlg.errors)

    def _showHeaders(self, value):
        """show/hide headers"""
        if (value):  #show
            self.ui.tvCoilsData.horizontalHeader().show()
            self.ui.tvCoilsData.verticalHeader().show()
            self.ui.tvDiscreteInputsData.horizontalHeader().show()
            self.ui.tvDiscreteInputsData.verticalHeader().show()
            self.ui.tvInputRegistersData.horizontalHeader().show()
            self.ui.tvInputRegistersData.verticalHeader().show()
            self.ui.tvHoldingRegistersData.horizontalHeader().show()
            self.ui.tvHoldingRegistersData.verticalHeader().show()
        else:  #hide
            self.ui.tvCoilsData.horizontalHeader().hide()
            self.ui.tvCoilsData.verticalHeader().hide()
            self.ui.tvDiscreteInputsData.horizontalHeader().hide()
            self.ui.tvDiscreteInputsData.verticalHeader().hide()
            self.ui.tvInputRegistersData.horizontalHeader().hide()
            self.ui.tvInputRegistersData.verticalHeader().hide()
            self.ui.tvHoldingRegistersData.horizontalHeader().hide()
            self.ui.tvHoldingRegistersData.verticalHeader().hide()

    def _update_ui(self):
        """update enable-disable status of ui components"""
        if (self.ui.actionConnect.isChecked()):  #start
            self.ui.actionLoad_Session.setEnabled(False)
            self.ui.actionSave_Session.setEnabled(False)
            self.ui.cmbModbusMode.setEnabled(False)
            self.ui.sbSlaveID.setEnabled(False)
            self.ui.spInterval.setEnabled(False)
            self.ui.sbNoOfCoils.setEnabled(False)
            self.ui.sbCoilsStartAddr.setEnabled(False)
            self.ui.sbNoOfDigInputs.setEnabled(False)
            self.ui.sbDigInputsstartAddr.setEnabled(False)
            self.ui.sbNoOfHoldingRegs.setEnabled(False)
            self.ui.sbHoldingRegsStartAddr.setEnabled(False)
            self.ui.sbNoOfInputRegs.setEnabled(False)
            self.ui.sbInputRegsStartAddr.setEnabled(False)
        else:  #stop
            self.ui.actionLoad_Session.setEnabled(True)
            self.ui.actionSave_Session.setEnabled(True)
            self.ui.cmbModbusMode.setEnabled(True)
            self.ui.sbSlaveID.setEnabled(True)
            self.ui.spInterval.setEnabled(True)
            self.ui.sbNoOfCoils.setEnabled(True)
            self.ui.sbCoilsStartAddr.setEnabled(True)
            self.ui.sbNoOfDigInputs.setEnabled(True)
            self.ui.sbDigInputsstartAddr.setEnabled(True)
            self.ui.sbNoOfHoldingRegs.setEnabled(True)
            self.ui.sbHoldingRegsStartAddr.setEnabled(True)
            self.ui.sbNoOfInputRegs.setEnabled(True)
            self.ui.sbInputRegsStartAddr.setEnabled(True)
            _empty_model = self.coils_data_model = ModSlaveMBDataModel(0, 0, 0)
            self._mbdata_ctrl.set_data_models(_empty_model, _empty_model,
                                              _empty_model, _empty_model)

    def _start_stop(self):
        """start - stop server and slave"""
        self._reset_counters()
        del self._svr_args[:]  #clear params
        svr_hooks = []
        if (self.ui.actionConnect.isChecked()):  #start
            if (self.ui.cmbModbusMode.currentText() == "TCP"
                ):  # TCP server params
                self._logger.info("Starting TCP server")
                self._svr_args.append("-tcp")
                self._svr_args.append(self._settingsTCP_dlg.tcp_port)
                self._svr_args.append(self._settingsTCP_dlg.tcp_ip)
            elif (self.ui.cmbModbusMode.currentText() == "RTU"
                  ):  # RTU server params
                self._logger.info("Starting RTU server")
                self._svr_args.append("-rtu")
                if os.name == 'nt':  #windows
                    self._svr_args.append("COM" +
                                          str(self._settingsRTU_dlg.rtu_port))
                else:  #linux?
                    self._svr_args.append(self._settingsRTU_dlg.rtu_dev +
                                          str(self._settingsRTU_dlg.rtu_port))
                self._svr_args.append(self._settingsRTU_dlg.baud_rate)
                self._svr_args.append(self._settingsRTU_dlg.byte_size)
                self._svr_args.append(self._settingsRTU_dlg.parity[0])
                self._svr_args.append(self._settingsRTU_dlg.stop_bits)
            if (len(self._svr_args) > 0):  # check for valid no of parameters
                self.svr = modFactory.ModSvrFactory(self._svr_args)
                if (self.svr == None):  #fail to build server
                    self._logger.error("Fail to start server")
                    Utils.errorMessageBox("Fail to start server")
                    self.ui.actionConnect.setChecked(False)
                else:
                    self.svr.start()
                    self.slv = modFactory.ModSlave(
                        self.svr, self.ui.sbSlaveID.value(),
                        self.ui.spInterval.value() / 1000.0,
                        self.ui.sbCoilsStartAddr.value(),
                        self.ui.sbNoOfCoils.value(),
                        self.ui.sbDigInputsstartAddr.value(),
                        self.ui.sbNoOfDigInputs.value(),
                        self.ui.sbInputRegsStartAddr.value(),
                        self.ui.sbNoOfInputRegs.value(),
                        self.ui.sbHoldingRegsStartAddr.value(),
                        self.ui.sbNoOfHoldingRegs.value())
                    if (self.slv == None):  #fail to build slave
                        self._logger.error("Fail to start slave")
                        Utils.errorMessageBox("Fail to start slave")
                        self.svr.stop()
                        self.svr = None
                        self.ui.actionConnect.setChecked(False)
                    else:
                        self._mbdata_ctrl.set_data_models(
                            self.slv.coils_data_model,
                            self.slv.dis_inputs_data_model,
                            self.slv.input_regs_data_model,
                            self.slv.hold_regs_data_model)
                        self.slv.start_sim()
        else:  #stop
            self._logger.info("Stop server")
            self.slv.stop_sim()
            self.svr.stop()
            self.slv = None
            self.svr = None
        #update user interface
        self._update_ui()
        self._update_status_bar()

    def _load_params(self, fname):
        self._logger.info("Load params")
        config_tcp_defaut = {'TCP_Port': '502', 'TCP_IP': '127.000.000.001'}
        if os.name == 'nt':  # windows
            config_rtu_defaut = {
                'RTU_Dev': 'COM',
                'RTU_Port': '0',
                'Baud': '9600',
                'DataBits': '8',
                'StopBits': '1',
                'Parity': 'None'
            }
        else:  # linux?
            config_rtu_defaut = {
                'RTU_Dev': '/dev/ttyS',
                'RTU_Port': '0',
                'Baud': '9600',
                'DataBits': '8',
                'StopBits': '1',
                'Parity': 'None'
            }
        config_var_defaut = {
            'Coils': '10',
            'CoilsStartAddr': '0',
            'DisInputs': '10',
            'DisInputsStartAddr': '0',
            'InputRegs': '10',
            'InputRegsStartAddr': '0',
            'HoldRegs': '10',
            'HoldRegsStartAddr': '0',
            'TimeInterval': '1000',
            'MaxNoOfBusMonitorLines': '50',
            'ModbusMode': '1',
            'ModbusSlaveID': '1',
            'LoggingLevel': '30'
        }
        config_default = {}
        config_default.update(config_tcp_defaut)
        config_default.update(config_rtu_defaut)
        config_default.update(config_var_defaut)
        config = configparser.ConfigParser(config_default)
        if not (config.read(fname)):  #if file does not exist exit
            self._logger.error("Parameters file does not exist")
            return
        #TCP Settings
        self._settingsTCP_dlg.tcp_port = config.getint('TCP', 'TCP_Port')
        self._settingsTCP_dlg.tcp_ip = config.get('TCP', 'TCP_IP')
        #RTU Settings
        self._settingsRTU_dlg.rtu_dev = config.get('RTU', 'RTU_Dev')
        self._settingsRTU_dlg.rtu_port = config.getint('RTU', 'RTU_Port')
        self._settingsRTU_dlg.baud_rate = config.getint('RTU', 'Baud')
        self._settingsRTU_dlg.byte_size = config.getint('RTU', 'DataBits')
        self._settingsRTU_dlg.stop_bits = config.get('RTU', 'StopBits')
        self._settingsRTU_dlg.parity = config.get('RTU', 'Parity')
        #Var Settings
        self._coils = config.getint('Var', 'Coils')
        self._coils_start_addr = config.getint('Var', 'CoilsStartAddr')
        self._inputs = config.getint('Var', 'DisInputs')
        self._inputs_start_addr = config.getint('Var', 'DisInputsStartAddr')
        self._input_regs = config.getint('Var', 'InputRegs')
        self._input_regs_start_addr = config.getint('Var',
                                                    'InputRegsStartAddr')
        self._hold_regs = config.getint('Var', 'HoldRegs')
        self._hold_regs_start_addr = config.getint('Var', 'HoldRegsStartAddr')
        self._time_interval = config.getint('Var', 'TimeInterval')
        self._settings_dlg.max_no_of_bus_monitor_lines = config.getint(
            'Var', 'MaxNoOfBusMonitorLines')
        self._bus_monitor_dlg.set_max_no_of_bus_monitor_lines(
            self._settings_dlg.max_no_of_bus_monitor_lines)
        self._modbus_mode = config.getint('Var', 'ModbusMode')
        self._modbus_slave_ID = config.getint('Var', 'ModbusSlaveID')
        self._logging_level = config.getint('Var', 'LoggingLevel')
        self._logger.setLevel(self._logging_level)
        #update ui
        self.ui.sbNoOfCoils.setValue(self._coils)
        self.ui.sbCoilsStartAddr.setValue(self._coils_start_addr)
        self.ui.sbNoOfDigInputs.setValue(self._inputs)
        self.ui.sbDigInputsstartAddr.setValue(self._inputs_start_addr)
        self.ui.sbNoOfHoldingRegs.setValue(self._hold_regs)
        self.ui.sbHoldingRegsStartAddr.setValue(self._hold_regs_start_addr)
        self.ui.sbNoOfInputRegs.setValue(self._input_regs)
        self.ui.sbInputRegsStartAddr.setValue(self._input_regs_start_addr)
        self.ui.spInterval.setValue(self._time_interval)
        self.ui.cmbModbusMode.setCurrentIndex(self._modbus_mode)
        self.ui.sbSlaveID.setValue(self._modbus_slave_ID)

    def _save_params(self, fname):
        self._logger.info("Save params")
        #update params from ui
        self._coils = self.ui.sbNoOfCoils.value()
        self._coils_start_addr = self.ui.sbCoilsStartAddr.value()
        self._inputs = self.ui.sbNoOfDigInputs.value()
        self._inputs_start_addr = self.ui.sbDigInputsstartAddr.value()
        self._hold_regs = self.ui.sbNoOfHoldingRegs.value()
        self._hold_regs_start_addr = self.ui.sbHoldingRegsStartAddr.value()
        self._input_regs = self.ui.sbNoOfInputRegs.value()
        self._input_regs_start_addr = self.ui.sbInputRegsStartAddr.value()
        self._modbus_mode = self.ui.cmbModbusMode.currentIndex()
        self._modbus_slave_ID = self.ui.sbSlaveID.value()
        config = configparser.ConfigParser()
        #TCP Settings
        config.add_section('TCP')
        config.set('TCP', 'TCP_Port', str(self._settingsTCP_dlg.tcp_port))
        config.set('TCP', 'TCP_IP', self._settingsTCP_dlg.tcp_ip)
        #RTU Settings
        config.add_section('RTU')
        config.set('RTU', 'RTU_Dev', self._settingsRTU_dlg.rtu_dev)
        config.set('RTU', 'RTU_Port', str(self._settingsRTU_dlg.rtu_port))
        config.set('RTU', 'Baud', str(self._settingsRTU_dlg.baud_rate))
        config.set('RTU', 'DataBits', str(self._settingsRTU_dlg.byte_size))
        config.set('RTU', 'StopBits', str(self._settingsRTU_dlg.stop_bits))
        config.set('RTU', 'Parity', self._settingsRTU_dlg.parity)
        #Var Settings
        config.add_section('Var')
        config.set('Var', 'Coils', str(self._coils))
        config.set('Var', 'CoilsStartAddr', str(self._coils_start_addr))
        config.set('Var', 'DisInputs', str(self._inputs))
        config.set('Var', 'DisInputsStartAddr', str(self._inputs_start_addr))
        config.set('Var', 'InputRegs', str(self._input_regs))
        config.set('Var', 'InputRegsStartAddr',
                   str(self._input_regs_start_addr))
        config.set('Var', 'HoldRegs', str(self._hold_regs))
        config.set('Var', 'HoldRegsStartAddr', str(self._hold_regs_start_addr))
        config.set('Var', 'TimeInterval', str(self._time_interval))
        config.set('Var', 'MaxNoOfBusMonitorLines',
                   str(self._settings_dlg.max_no_of_bus_monitor_lines))
        config.set('Var', 'ModbusMode', str(self._modbus_mode))
        config.set('Var', 'ModbusSlaveID', str(self._modbus_slave_ID))
        config.set('Var', 'LoggingLevel', str(self._logging_level))
        #Save Settings
        config_file = open(fname, 'w')
        config.write(config_file)

    def _load_session(self):
        cwd = os.getcwd()
        file_path = QtWidgets.QFileDialog.getOpenFileName(
            self, "Load Session file", cwd,
            "Session Files (*.ses);;All Files (*.*)")
        if (file_path[0] != ''):
            self._logger.info("Load session : " + file_path[0])
            self._load_params(os.path.abspath(file_path[0]))

    def _save_session(self):
        cwd = os.getcwd()
        file_path = QtWidgets.QFileDialog.getSaveFileName(
            self, "Save Session file", cwd, "Session Files (*.ses)")
        if (file_path[0] != ''):
            self._logger.info("Save session : " + file_path[0])
            self._save_params(os.path.abspath(file_path[0]))

    def _reset_counters(self):
        self._bus_monitor_dlg.reset_counters()

    def _update_modbus_mode(self, index):
        if (index == 0):  # RTU
            self.ui.lblSlave.setText('Slave Addr')
            #self.ui.sbSlaveID.setVisible(True)
        elif (index == 1):  # TCP
            self.ui.lblSlave.setText('Unit ID')
            #self.ui.sbSlaveID.setVisible(False)

    def _open_log_file(self):
        """open application log"""
        if (not os.path.exists('pyModSlave.log')):
            msg = "File 'pyModSlave.log' does not exist"
            self._logger.error(msg)
            Utils.errorMessageBox(msg)
            return
        try:
            subprocess.Popen(['notepad.exe', 'pyModSlave.log'])
        except WindowsError as we:
            msg = "Windows Error No %i - %s" % we.args
            self._logger.error(msg)
            Utils.errorMessageBox(msg)

    def _open_modbus_manual(self):
        """open modbus manual"""
        if (not os.path.exists('ManModbus\index.html')):
            msg = "Modbus Manual is missing"
            self._logger.error(msg)
            Utils.errorMessageBox(msg)
            return
        try:
            webbrowser.open_new_tab('ManModbus\index.html')
        except WindowsError as we:
            msg = "Cannot open Modbus Manual %i - %s" % we.args
            self._logger.error(msg)
            Utils.errorMessageBox(msg)

    def showEvent(self, QShowEvent):
        """set values for controls"""
        self._load_params(self._params_file_name)
        self._update_status_bar()

    def closeEvent(self, QCloseEvent):
        """window is closing"""
        self._save_params(self._params_file_name)
Esempio n. 10
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.meters = []
        self.meteritems = []
        with open('meters.txt') as f:
            for line in f:
                line = line.strip()
                if line.startswith('#') or not line:
                    continue
                minfo = line.split()
                # addr.
                minfo[2] = minfo[2][:12].zfill(12)
                self.meters.append(minfo[2])
                item = QTreeWidgetItem(None, minfo)
                self.ui.treeWidget.addTopLevelItem(item)
                self.meteritems.append(item)
        self.ui.treeWidget.resizeColumnToContents(0)
        self.ui.treeWidget.resizeColumnToContents(1)
        self.ui.treeWidget.resizeColumnToContents(2)
        self.ui.progressBar.setMaximum(len(self.meters))
        
        self.ui.comboBox_port.addItems([i[0] for i in comports()])
        
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update)
        self.txtimer = QTimer(self)
        self.txtimer.timeout.connect(self.send)
        self.txtimer. setSingleShot(True)
        self.ser = None
        self.buf = bytearray()
        self.pktidx = [0]
        self.dstmeters = self.meters
#        self.rxd = 0
#        self.binfo = ['aRoute', 0, 0, 0, self.ui.lineEdit_localaddr.text(), '']
#        self.xinfo = {'data': '68 77 44 10 03 00 00 68 91 18 33 32 34 33 AC 34 33 33 58 33 33 33 95 33 33 33 99 33 33 33 58 33 33 33 9B 16'}
        
    def update(self):
#        if self.rxd:
#            self.rxd = 0
#            baseinfo = self.binfo
#            extinfo = self.xinfo
#            if baseinfo[4] == self.ui.lineEdit_localaddr.text().strip() and baseinfo[0] == 'aRoute':
#                item = self.ui.treeWidget.topLevelItem(self.meters.index(baseinfo[5]))
#                item.setText(8, extinfo['data'])
#                d = [i-0x33 for i in bytes.fromhex(extinfo['data'])[14:-2]]
#                for i in range(0, 20 if len(d)>20 else len(d), 4):
#                    item.setText(3+i//4, '%02X%02X%02X.%02X' % (d[i+3], d[i+2], d[i+1], d[i]))
#                for i in range(3, item.columnCount()):
#                    self.ui.treeWidget.resizeColumnToContents(i)
#                if self.ui.pushButton_start.text() == '停止抄表' and item is self.meteritems[self.i]:
#                    self.meteritems.remove(item)
#                    item.setBackground(2, Qt.green)
#                    oks = len(self.meters)-len(self.meteritems)
#                    self.ui.progressBar.setValue(oks)
#                    okrate = oks*100//len(self.meters)
#                    self.ui.label_currate.setText('%d' % okrate)
#                    if not self.meteritems or okrate == self.ui.spinBox_okrate.value():
#                        self.txtimer.stop()
#                        self.ui.pushButton_start.setText('开始抄表')
#                        self.ui.label_curmeter.setText('------------')
#                        self.ui.label_retry.setText('0')
#                    else:
#                        #self.retry = self.ui.spinBox_retry.value()
#                        self.retry = 0
#                        self.txtimer.start(0)
#            return
        if serial.VERSION == '2.7':
            inwaiting = self.ser.inWaiting()
        else:
            inwaiting = self.ser.in_waiting
        if inwaiting:
            self.buf.extend(self.ser.read(inwaiting))
            #print(self.buf)
            i = self.buf.find(b'\xFE\xFE\xFE\xFE')
            if i != -1:
                # from wl, no crc.
                if len(self.buf) > i+4 and len(self.buf)>= i + self.buf[i+4] + 5 +2:
                    #print(' '.join('%02X'%ii for ii in self.buf[i+8: i+self.buf[i+4]+5]))
                    try:
                        baseinfo, extinfo = PacketParser(self.buf[i+8: i+self.buf[i+4]+5])
                        #print(baseinfo)
                        #print(extinfo)
                        if baseinfo[4] == self.ui.lineEdit_localaddr.text().strip() and baseinfo[0] == 'aRoute':
                            item = self.ui.treeWidget.topLevelItem(self.meters.index(baseinfo[5]))
                            item.setText(8, extinfo['data'])
                            d = [i-0x33 for i in bytes.fromhex(extinfo['data'])[14:-2]]
                            for i in range(0, 20 if len(d)>20 else len(d), 4):
                                item.setText(3+i//4, '%02X%02X%02X.%02X' % (d[i+3], d[i+2], d[i+1], d[i]))
                            for i in range(3, item.columnCount()):
                                self.ui.treeWidget.resizeColumnToContents(i)
                            if self.ui.pushButton_start.text() == '停止抄表' and item is self.meteritems[self.i]:
                                self.meteritems.remove(item)
                                item.setBackground(2, Qt.green)
                                oks = len(self.meters)-len(self.meteritems)
                                self.ui.progressBar.setValue(oks)
                                okrate = oks*100//len(self.meters)
                                self.ui.label_currate.setText('%d' % okrate)
                                if not self.meteritems or okrate == self.ui.spinBox_okrate.value():
                                    self.txtimer.stop()
                                    self.ui.pushButton_start.setText('开始抄表')
                                    self.ui.label_curmeter.setText('------------')
                                    self.ui.label_retry.setText('0')
                                else:
                                    #self.retry = self.ui.spinBox_retry.value()
                                    self.retry = 0
                                    self.txtimer.start(0)
                    except:
                        pass
                    del self.buf[: i+self.buf[i+4]+5+2]
 
    def send(self):
        if self.retry == self.ui.spinBox_retry.value():
            self.retry = 0
            self.i += 1
            if self.i == len(self.meteritems):
                self.i = 0
                self.round += 1
                self.ui.label_curround.setText(str(self.round))
                if self.round == self.ui.spinBox_round.value():
                    self.ui.pushButton_start.setText('开始抄表')
                    self.ui.label_curmeter.setText('------------')
                    self.ui.label_retry.setText('0')
                    return
        item = self.meteritems[self.i]
        self.ui.treeWidget.setCurrentItem(item)
        #item.setBackground(2, Qt.cyan)
        meter = item.text(2)
        self.read_meter(meter)
        self.ui.label_curmeter.setText(meter)
        self.retry += 1
        self.ui.label_retry.setText(str(self.retry))
        self.txtimer.start(self.ui.spinBox_interval.value() * 1000) 
#        if 1:#self.retry == self.ui.spinBox_retry.value():
#            if meter in ['000000000002']:
#                self.rxd=1
#                self.binfo[5] = meter
 
    def read_meter(self, meter):
        dstaddr = bytearray.fromhex(meter)
        dstaddr.reverse()
        srcaddr = bytearray.fromhex(self.ui.lineEdit_localaddr.text())
        srcaddr.reverse()
        pkt = bytearray.fromhex(
            'FE FE FE FE 25 00 01 24 '
            '41 CD 5E FF FF 80 24 59 01 00 14 88 00 00 00 10 00 '
            '3C 80 24 59 01 00 14 AA AA AA AA AA AA 11 02 13 00 ')
        pkt[10] = self.pktidx[0] # mac index.
        pkt[13:19] = dstaddr
        pkt[19:25] = srcaddr
        pkt[26:32] = dstaddr
        pkt[32:38] = srcaddr
        pkt[38] = (pkt[38] & 0x0F) + ((self.pktidx[0] % 16) << 4) # nwk index.
        pkt[40] = self.i % 0x100 # aps index.
        pkt645 = bytearray.fromhex(self.ui.lineEdit_pkt645.text())
        pkt645[1:7] = dstaddr
        pkt645[-2] = sum(pkt645[:-2]) % 0x100
        pkt.extend(pkt645)
        pkt[4] = len(pkt) - 5
        pkt[5] = int(self.ui.comboBox_chnlgrp.currentText())*2 + int(self.ui.comboBox_chnl.currentText())
        pkt[7] = pkt[4] ^ pkt[5] ^ pkt[6]
        self.ser.write(pkt)
        self.pktidx[0] += 1
        if self.pktidx[0] > 255:
            self.pktidx[0] = 0

    @pyqtSlot()
    def on_pushButton_swithport_clicked(self):
        if self.ui.pushButton_swithport.text() == '打开':
            port = self.ui.comboBox_port.currentText()
            try:
                self.ser = serial.Serial(port, 115200, parity=serial.PARITY_EVEN, timeout=0)
                self.timer.start(1) 
                self.set_channel(int(self.ui.comboBox_chnlgrp.currentText()), int(self.ui.comboBox_chnl.currentText()))
                self.ui.pushButton_swithport.setText('关闭') 
            except:
                self.timer.stop()
                QMessageBox.warning(self, '警告', '无法打开 %s!' % port)
        else:
            self.ser.close()
            self.ser = None
            self.ui.pushButton_swithport.setText('打开')

    @pyqtSlot()
    def on_pushButton_start_clicked(self):
        if self.ui.pushButton_start.text() == '开始抄表':
            if int(self.ui.label_currate.text()) == self.ui.spinBox_okrate.value() or not self.meteritems:
                QMessageBox.information(self, '提示', '条件已满足,你可以重启软件来重新抄表!')
                return
            if self.ser:
                self.i = 0
                self.retry = 0
                self.round = 0
                self.ui.label_curround.setText('0')
                self.ui.label_retry.setText('0')
                self.txtimer.start(0) 
                self.ui.pushButton_start.setText('停止抄表')
            else:
                QMessageBox.warning(self, '警告', '请先打开串口!')
        else:
            self.txtimer.stop()
            self.ui.pushButton_start.setText('开始抄表')
            
    def set_channel(self, chnlgrp,  chnl):
        pkt = bytearray.fromhex('FE FE FE FE 03 00 01 24')
        pkt[5] = chnlgrp*2 + chnl
        pkt[7] = pkt[4] ^ pkt[5] ^ pkt[6]
        if self.ser:
            self.ser.write(pkt)
        else:
            QMessageBox.warning(self, '警告', '请先打开串口!')
        
    @pyqtSlot(int)
    def on_comboBox_chnlgrp_currentIndexChanged(self, index):
        self.set_channel(index, int(self.ui.comboBox_chnl.currentText()))
        
    @pyqtSlot(int)
    def on_comboBox_chnl_currentIndexChanged(self, index):
        self.set_channel(int(self.ui.comboBox_chnlgrp.currentText()), index)

    @pyqtSlot()
    def on_pushButton_save_clicked(self):
        t = datetime.now().strftime('%y-%m-%d_%H-%M-%S')
        file = QFileDialog.getSaveFileName(self, 'Save file', './result/' + t, 'data file(*.txt)')[0]
        if file:
            with open(file, 'w') as f:
                f.write('户号\t姓名\t表号\t总电能\t费率1电能\t费率2电能\t费率3电能\t费率4电能\n')
                for i in range(self.ui.treeWidget.topLevelItemCount()):
                    item = self.ui.treeWidget.topLevelItem(i)
                    colstrs = []
                    for col in range(8):
                        colstrs.append(item.text(col))
                    f.write('\t'.join(colstrs))
                    f.write('\n')

    @pyqtSlot(QTreeWidgetItem, int)
    def on_treeWidget_itemDoubleClicked(self, item, column):
            if self.ser:
                self.i = self.ui.treeWidget.indexOfTopLevelItem(item)
                self.read_meter(item.text(0))
            else:
                QMessageBox.warning(self, '警告', '请先打开串口!')
Esempio n. 11
0
class MainWindow(QMainWindow, Ui_MainWindow):
    """
    Class documentation goes here.
    """
    _receive_signal = QtCore.pyqtSignal(str)

    def __init__(self, parent = None):
        QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.about_Dialog = QtGui.QDialog()
        self.about_ui = Ui_about_dial()
        self.about_ui.setupUi(self.about_Dialog)
        self.update_dialog = UpdateQDialog(self)
        self._port = ''
        self._baud = ''
        self._currentcmd = ''
        self._last_received = ''
        self._gopath = 'D001' + self.ui.comboBox_d001_value.currentText()
        self.on_pushButton_serialrefresh_clicked()
        self._serial_context_ = serialportcontext.SerialPortContext(port=self._port, baud=self._port)
        self._receive_signal.connect(self.__display_recv_data__)

    def list_serial_ports(self):
        system_name = platform.system()
        if system_name == 'Windows':
            available = []
            for i in range(256):
                try:
                    s = serial.Serial(i)
                    available.append(s.portstr)
                    s.close()
                except serial.SerialException:
                    pass

            return available
        elif system_name == 'Darwin':
            return glob.glob('/dev/cu*')
        else:
            return glob.glob('/dev/ttyS*') + glob.glob('/dev/ttyUSB*')

    def __open_serial_port__(self):
        if self._serial_context_.isRunning():
            self._serial_context_.close()
        else:
            try:
                port = str(self.ui.comboBox_serialport.currentText())
                baud = int('%s' % self.ui.comboBox_serialbauds.currentText(), 10)
                self._serial_context_ = serialportcontext.SerialPortContext(port=port, baud=baud)
                self._serial_context_.registerReceivedCallback(self.__data_received__)
                self._serial_context_.setDTR(True)
                self._serial_context_.setRTS(True)
                self._serial_context_.open()
            except Exception as e:
                self.print_debug(str(e))
                QtGui.QMessageBox.critical(self, u'\x08\u958b\u8d77\u7aef\u53e3', u'\u958b\u8d77\u7aef\u53e3\u5931\u6557,\u8acb\u6aa2\u67e5!')

    def __data_received__(self, data):
        self._receive_signal.emit(data)

    def __display_recv_data__(self, data):
        self.print_recive(str(data))

    def __send_data__(self, msg):
        data = str(msg)
        if self._serial_context_.isRunning():
            if len(data) > 0:
                self._serial_context_.send(data, False)
                self.print_send(data)
        else:
            self.print_debug("Can't send cmd", 'ERROR')

    def __closeEvent__(self):
        if self._serial_context_.isRunning():
            self._serial_context_.close()
            self.print_debug('SERIAL PORT CLOSE', 'INFO')

    def showDial(self):
        with open('help/about_app') as f:
            content = f.read()
        self.about_ui.textBrowser_about.setText(content)
        self.about_Dialog.exec_()

    def showDial_update(self):
        with open('current_version.ini') as f:
            content = f.read().rstrip('\n')
        self.update_dialog.ui.label_current_version.setText(content)
        file_path = os.getcwd() + '/checkupdate.bat'
        output = subprocess.Popen([file_path], stdout=subprocess.PIPE, shell=True).communicate()[0]
        output = output.rstrip('\n')
        self.update_dialog.ui.label_update_state.setText(output)
        self.update_dialog.exec_()

    def currentcmd_update(self):
        self._gopath = self._gopath[:4] + self.ui.comboBox_d001_value.currentText() + self._gopath[5:]
        _cmd = 'QQQ' + self._gopath + 'XXX'
        self._currentcmd = _cmd
        self.ui.textEdit_currentcmd.setText(self._currentcmd)
        return True

    def print_debug(self, mes, stat = 'LOG'):
        st = {'NOTIFY': 'blue',
         'INFO': 'green',
         'ERROR': 'red',
         'LOG': 'gray'}
        text_format = '<span style="color:%s;" >' % st.get(stat)
        text_format = text_format + mes
        text_format = text_format + '</span>'
        self.ui.textEdit_debugmessage.append(text_format)

    def print_send(self, mes, stat = 'NOTIFY'):
        st = {'NOTIFY': 'blue',
         'INFO': 'green',
         'ERROR': 'red',
         'LOG': 'gray'}
        text_format = '<span style="color:%s;" >' % st.get(stat)
        text_format = text_format + mes
        text_format = text_format + '</span>'
        self.ui.textEdit_sendmessage.append(text_format)

    def print_recive(self, mes, stat = 'INFO'):
        st = {'NOTIFY': 'blue',
         'INFO': 'green',
         'ERROR': 'red',
         'LOG': 'gray'}
        text_format = '<span style="color:%s;" >' % st.get(stat)
        text_format = text_format + mes
        text_format = text_format + '</span>'
        self.ui.textEdit_recivemessage.insertPlainText(mes)

    @pyqtSignature('')
    def on_commandLinkButton_serailopen_clicked(self):
        self._port = self.ui.comboBox_serialport.currentText()
        self._baud = self.ui.comboBox_serialbauds.currentText()
        self.print_debug('SERIAL PORT OPEN--port : %s  baud : %s' % (self._port, self._baud), 'INFO')
        self.__open_serial_port__()
        self.ui.commandLinkButton_serailopen.setEnabled(False)
        self.ui.pushButton_stop.setEnabled(True)

    @pyqtSignature('')
    def on_pushButton_stop_clicked(self):
        self.__closeEvent__()
        self.ui.commandLinkButton_serailopen.setEnabled(True)
        self.ui.pushButton_stop.setEnabled(False)

    @pyqtSignature('')
    def on_pushButton_send_rawcmd_clicked(self):
        cmd = self.ui.textEdit_sendcmd.toPlainText()
        if cmd == '':
            self.__send_data__('empty cmd')
        else:
            self.__send_data__(cmd)

    @pyqtSignature('')
    def on_pushButton_send_currentcmd_clicked(self):
        cmd = self.ui.textEdit_currentcmd.toPlainText()
        if cmd == '':
            self.__send_data__('empty cmd')
        else:
            self.__send_data__(cmd)

    @pyqtSignature('')
    def on_pushButton_serialrefresh_clicked(self):
        self.ui.comboBox_serialport.clear()
        self.ui.comboBox_serialport.addItems(self.list_serial_ports())

    @pyqtSignature('')
    def on_pushButton_reset_funbtn_clicked(self):
        self._gopath = 'D001' + self.ui.comboBox_d001_value.currentText()
        self.print_debug('>>clear cmd')
        self.ui.textEdit_currentcmd.setText('')

    @pyqtSignature('')
    def on_pushButton_addpath_clicked(self):
        choosepath = self.ui.comboBox_choosepath.currentText()
        path2stop = self.ui.comboBox_path2stop.currentIndex()
        self._gopath = self._gopath + str(choosepath) + str(path2stop)
        self.print_debug('>>add new station : %s%s' % (choosepath, path2stop))
        self.currentcmd_update()

    @pyqtSignature('')
    def on_pushButton_batterystate_clicked(self):
        cmd = 'QQQJ0040XXX'
        self.__send_data__(cmd)

    @pyqtSignature('')
    def on_pushButton_lastcardstate_clicked(self):
        cmd = 'QQQJ0120XXX'
        self.__send_data__(cmd)

    @pyqtSignature('')
    def on_pushButton_runstate_clicked(self):
        cmd = 'QQQJ0020XXX'
        self.__send_data__(cmd)

    @pyqtSignature('')
    def on_pushButton_addrotation_clicked(self):
        cmd = 'Z00'
        if self.ui.comboBox_rotation.currentIndex() == 0:
            cmd = cmd + '21'
        else:
            cmd = cmd + '31'
        self._gopath = self._gopath + str(cmd)
        self.print_debug('>>add rotation : %s' % cmd)
        self.currentcmd_update()

    @pyqtSignature('')
    def on_actionAbout_AutoCar_triggered(self):
        self.showDial()

    @pyqtSignature('')
    def on_action_checkupdate_triggered(self):
        self.showDial_update()

    @pyqtSignature('QString')
    def on_comboBox_d001_value_currentIndexChanged(self):
        self.print_debug('>>change speed : %s' % self.ui.comboBox_d001_value.currentText())
        self.currentcmd_update()
Esempio n. 12
0
class MainWindow(QMainWindow, Ui_MainWindow):
    """
    Class documentation goes here.
    """
    _receive_signal = QtCore.pyqtSignal(str)

    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.about_Dialog = QtGui.QDialog()
        self.about_ui = Ui_about_dial()
        self.about_ui.setupUi(self.about_Dialog)
        self.update_dialog = UpdateQDialog(self)
        self._port = ''
        self._baud = ''
        self._currentcmd = ''
        self._last_received = ''
        self._gopath = 'D001' + self.ui.comboBox_d001_value.currentText()
        self.on_pushButton_serialrefresh_clicked()
        self._serial_context_ = serialportcontext.SerialPortContext(
            port=self._port, baud=self._port)
        self._receive_signal.connect(self.__display_recv_data__)

    def list_serial_ports(self):
        system_name = platform.system()
        if system_name == 'Windows':
            available = []
            for i in range(256):
                try:
                    s = serial.Serial(i)
                    available.append(s.portstr)
                    s.close()
                except serial.SerialException:
                    pass

            return available
        elif system_name == 'Darwin':
            return glob.glob('/dev/cu*')
        else:
            return glob.glob('/dev/ttyS*') + glob.glob('/dev/ttyUSB*')

    def __open_serial_port__(self):
        if self._serial_context_.isRunning():
            self._serial_context_.close()
        else:
            try:
                port = str(self.ui.comboBox_serialport.currentText())
                baud = int('%s' % self.ui.comboBox_serialbauds.currentText(),
                           10)
                self._serial_context_ = serialportcontext.SerialPortContext(
                    port=port, baud=baud)
                self._serial_context_.registerReceivedCallback(
                    self.__data_received__)
                self._serial_context_.setDTR(True)
                self._serial_context_.setRTS(True)
                self._serial_context_.open()
            except Exception as e:
                self.print_debug(str(e))
                QtGui.QMessageBox.critical(
                    self, u'\x08\u958b\u8d77\u7aef\u53e3',
                    u'\u958b\u8d77\u7aef\u53e3\u5931\u6557,\u8acb\u6aa2\u67e5!'
                )

    def __data_received__(self, data):
        self._receive_signal.emit(data)

    def __display_recv_data__(self, data):
        self.print_recive(str(data))

    def __send_data__(self, msg):
        data = str(msg)
        if self._serial_context_.isRunning():
            if len(data) > 0:
                self._serial_context_.send(data, False)
                self.print_send(data)
        else:
            self.print_debug("Can't send cmd", 'ERROR')

    def __closeEvent__(self):
        if self._serial_context_.isRunning():
            self._serial_context_.close()
            self.print_debug('SERIAL PORT CLOSE', 'INFO')

    def showDial(self):
        with open('help/about_app') as f:
            content = f.read()
        self.about_ui.textBrowser_about.setText(content)
        self.about_Dialog.exec_()

    def showDial_update(self):
        with open('current_version.ini') as f:
            content = f.read().rstrip('\n')
        self.update_dialog.ui.label_current_version.setText(content)
        file_path = os.getcwd() + '/checkupdate.bat'
        output = subprocess.Popen([file_path],
                                  stdout=subprocess.PIPE,
                                  shell=True).communicate()[0]
        output = output.rstrip('\n')
        self.update_dialog.ui.label_update_state.setText(output)
        self.update_dialog.exec_()

    def currentcmd_update(self):
        self._gopath = self._gopath[:
                                    4] + self.ui.comboBox_d001_value.currentText(
                                    ) + self._gopath[5:]
        _cmd = 'QQQ' + self._gopath + 'XXX'
        self._currentcmd = _cmd
        self.ui.textEdit_currentcmd.setText(self._currentcmd)
        return True

    def print_debug(self, mes, stat='LOG'):
        st = {'NOTIFY': 'blue', 'INFO': 'green', 'ERROR': 'red', 'LOG': 'gray'}
        text_format = '<span style="color:%s;" >' % st.get(stat)
        text_format = text_format + mes
        text_format = text_format + '</span>'
        self.ui.textEdit_debugmessage.append(text_format)

    def print_send(self, mes, stat='NOTIFY'):
        st = {'NOTIFY': 'blue', 'INFO': 'green', 'ERROR': 'red', 'LOG': 'gray'}
        text_format = '<span style="color:%s;" >' % st.get(stat)
        text_format = text_format + mes
        text_format = text_format + '</span>'
        self.ui.textEdit_sendmessage.append(text_format)

    def print_recive(self, mes, stat='INFO'):
        st = {'NOTIFY': 'blue', 'INFO': 'green', 'ERROR': 'red', 'LOG': 'gray'}
        text_format = '<span style="color:%s;" >' % st.get(stat)
        text_format = text_format + mes
        text_format = text_format + '</span>'
        self.ui.textEdit_recivemessage.insertPlainText(mes)

    @pyqtSignature('')
    def on_commandLinkButton_serailopen_clicked(self):
        self._port = self.ui.comboBox_serialport.currentText()
        self._baud = self.ui.comboBox_serialbauds.currentText()
        self.print_debug(
            'SERIAL PORT OPEN--port : %s  baud : %s' %
            (self._port, self._baud), 'INFO')
        self.__open_serial_port__()
        self.ui.commandLinkButton_serailopen.setEnabled(False)
        self.ui.pushButton_stop.setEnabled(True)

    @pyqtSignature('')
    def on_pushButton_stop_clicked(self):
        self.__closeEvent__()
        self.ui.commandLinkButton_serailopen.setEnabled(True)
        self.ui.pushButton_stop.setEnabled(False)

    @pyqtSignature('')
    def on_pushButton_send_rawcmd_clicked(self):
        cmd = self.ui.textEdit_sendcmd.toPlainText()
        if cmd == '':
            self.__send_data__('empty cmd')
        else:
            self.__send_data__(cmd)

    @pyqtSignature('')
    def on_pushButton_send_currentcmd_clicked(self):
        cmd = self.ui.textEdit_currentcmd.toPlainText()
        if cmd == '':
            self.__send_data__('empty cmd')
        else:
            self.__send_data__(cmd)

    @pyqtSignature('')
    def on_pushButton_serialrefresh_clicked(self):
        self.ui.comboBox_serialport.clear()
        self.ui.comboBox_serialport.addItems(self.list_serial_ports())

    @pyqtSignature('')
    def on_pushButton_reset_funbtn_clicked(self):
        self._gopath = 'D001' + self.ui.comboBox_d001_value.currentText()
        self.print_debug('>>clear cmd')
        self.ui.textEdit_currentcmd.setText('')

    @pyqtSignature('')
    def on_pushButton_addpath_clicked(self):
        choosepath = self.ui.comboBox_choosepath.currentText()
        path2stop = self.ui.comboBox_path2stop.currentIndex()
        self._gopath = self._gopath + str(choosepath) + str(path2stop)
        self.print_debug('>>add new station : %s%s' % (choosepath, path2stop))
        self.currentcmd_update()

    @pyqtSignature('')
    def on_pushButton_batterystate_clicked(self):
        cmd = 'QQQJ0040XXX'
        self.__send_data__(cmd)

    @pyqtSignature('')
    def on_pushButton_lastcardstate_clicked(self):
        cmd = 'QQQJ0120XXX'
        self.__send_data__(cmd)

    @pyqtSignature('')
    def on_pushButton_runstate_clicked(self):
        cmd = 'QQQJ0020XXX'
        self.__send_data__(cmd)

    @pyqtSignature('')
    def on_pushButton_addrotation_clicked(self):
        cmd = 'Z00'
        if self.ui.comboBox_rotation.currentIndex() == 0:
            cmd = cmd + '21'
        else:
            cmd = cmd + '31'
        self._gopath = self._gopath + str(cmd)
        self.print_debug('>>add rotation : %s' % cmd)
        self.currentcmd_update()

    @pyqtSignature('')
    def on_actionAbout_AutoCar_triggered(self):
        self.showDial()

    @pyqtSignature('')
    def on_action_checkupdate_triggered(self):
        self.showDial_update()

    @pyqtSignature('QString')
    def on_comboBox_d001_value_currentIndexChanged(self):
        self.print_debug('>>change speed : %s' %
                         self.ui.comboBox_d001_value.currentText())
        self.currentcmd_update()
Esempio n. 13
0
class MyApp(QtWidgets.QMainWindow):
    def __init__(self):
        super(MyApp, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.run_button.clicked.connect(self.run)
        self.ui.set_default_btn.clicked.connect(self.set_defaults)

        self.defaults = {
            "R": 0.35,
            "Le": 12,
            "Lk": 187e-6,
            "Ck": 268e-6,
            "Rk": 0.25,
            "Uc0": 1400,
            "I0": 0.5,
            "Tw": 2000,
            "Tstart": 0,
            "Tend": 0.0006,
            "Tstep": 1e-6
        }
        self.set_defaults()
        self.data = {}

    def set_defaults(self):
        self.ui.lineEdit_r.setText(str(self.defaults.get("R")))
        self.ui.lineEdit_le.setText(str(self.defaults.get("Le")))
        self.ui.lineEdit_lk.setText(str(self.defaults.get("Lk")))
        self.ui.lineEdit_ck.setText(str(self.defaults.get("Ck")))
        self.ui.lineEdit_rk.setText(str(self.defaults.get("Rk")))
        self.ui.lineEdit_uc0.setText(str(self.defaults.get("Uc0")))
        self.ui.lineEdit_i0.setText(str(self.defaults.get("I0")))
        self.ui.lineEdit_tw.setText(str(self.defaults.get("Tw")))
        self.ui.lineEdit_tstart.setText(str(self.defaults.get("Tstart")))
        self.ui.lineEdit_tend.setText(str(self.defaults.get("Tend")))
        self.ui.lineEdit_tstep.setText(str(self.defaults.get("Tstep")))

    def run(self):
        if self.check():
            mdlr = Modeller(self.data)
            isequal = self.ui.checkBox.isChecked()
            mdlr.compute(isequal)
        else:
            self.msg_box("Error!", "Error! Incorrect input!",
                         QMessageBox.Critical)

    def msg_box(self, title, message, type):
        msg = QMessageBox(self)
        msg.setIcon(type)
        msg.setWindowTitle(title)
        msg.setText(message)
        msg.addButton('Ok', QMessageBox.AcceptRole)
        msg.exec()

    def check(self):
        try:
            self.data["R"] = float(self.ui.lineEdit_r.text())
            self.data["Le"] = float(self.ui.lineEdit_le.text())
            self.data["Lk"] = float(self.ui.lineEdit_lk.text())
            self.data["Ck"] = float(self.ui.lineEdit_ck.text())
            self.data["Rk"] = float(self.ui.lineEdit_rk.text())
            self.data["Uc0"] = float(self.ui.lineEdit_uc0.text())
            self.data["I0"] = float(self.ui.lineEdit_i0.text())
            self.data["Tw"] = float(self.ui.lineEdit_tw.text())
            self.data["Tstart"] = float(self.ui.lineEdit_tstart.text())
            self.data["Tend"] = float(self.ui.lineEdit_tend.text())
            self.data["Tstep"] = float(self.ui.lineEdit_tstep.text())
        except ValueError:
            return False
        return True