예제 #1
0
 def draw_left_part(self):
     from Visual.RadioPlot import PlotElem
     plotsbox = QtGui.QVBoxLayout()
     self.plotX = PlotElem('X')
     self.plotY = PlotElem('Y')
     self.plotZ = PlotElem('Z')
     plotsbox.addLayout(self.plotX)
     plotsbox.addLayout(self.plotY)
     plotsbox.addLayout(self.plotZ)
     self.parts[0].setLayout(plotsbox)
예제 #2
0
class MInterfaceWindow(QtGui.QMainWindow):
    def __init__(self, geometry):
        super(MInterfaceWindow, self).__init__()
        f = open("gyro.txt", "w")
        f.close()
        #{"time": [], "accX": [], "accY": [], "accZ": [], "angvX": [], "angvY": [], "angvZ": []}
        self.const_hard_data = 2000
        self.const_reduced_data = 400
        self.const_process_rate = 10

        self.num_hard_data = 0
        self.num_reduced_data = 0
        self.num_record = 0

        self.data_from_hard = np.zeros((2*self.const_hard_data, 7))
        self.data_reduced = np.zeros((2*self.const_reduced_data, 7))
        self.data_traj = np.zeros((2*self.const_hard_data, 7))
        self.data_for_record = np.zeros((2*self.const_hard_data, 7))

        self.flag = {"play run": 0, "hardware run": 0, "trajectory load": 0, "record run": 0, "new data": 0, "record_reset":0}
        self.COMnum = '1'
        self.started = 0


        self.counter = 0
        self.timer_period = 5
        self.border_time = 10

        self.popup = None
        self.initUI()
        self.setWindowTitle(u'EpiSim')
        self.maxtime = 10
        self.reduced_time0 = 0

        locg = geometry
        self.setGeometry(100, 100, 400, 400)

        self.showMaximized()

    def initUI(self):
        self.timer = QtCore.QTimer(self)
        self.connect(self.timer, QtCore.SIGNAL("timeout()"), self.updater)
        self.timer.start(self.timer_period)
        self.message = ""


        centralWindow = QtGui.QWidget()
        self.setCentralWidget(centralWindow)

        main_layer = QtGui.QHBoxLayout() #right/left division
        centralWindow.setLayout(main_layer)
        number_parts = 2 #divide main window for "2" par
        self.parts = []
        splitter = QtGui.QSplitter(QtCore.Qt.Horizontal)
        for x in range(number_parts):
            self.parts.append(QtGui.QFrame(self))
        for x in self.parts:
            splitter.addWidget(x)
            x.setFrameShape(QtGui.QFrame.StyledPanel)
        main_layer.addWidget(splitter)

        self.draw_bars()
        self.draw_left_part()
        self.draw_right_part()
        return

    def service_popup_range_wrap(self):
        self.popup = ServiceRange()
        t = self.popup
        t.setMax(20)
        t.setMin(0)
        t.setTitle(u"Проверка диапазона")
        self.popup.show()

    def service_popup_angles_wrap(self):
        self.popup = ServiceRange()
        t = self.popup
        t.setMax(15)
        t.setMin(-10)
        t.setTitle(u"Проверка углов")

        self.popup.current = QtGui.QLabel()
        self.popup.main_layout.addWidget(self.popup.current)
        self.popup.show()

    def service_popup_acceleration_wrap(self):
        self.popup = ServiceRange(flag_line=1)
        t = self.popup
        t.line = QtGui.QDoubleSpinBox()
        t.setTitle(u"Проверка ускорения")

        self.popup.current = QtGui.QLabel()
        self.popup.main_layout.addWidget(self.popup.current)
        self.popup.show()

    def service_popup_coord_rotation_wrap(self):
        self.popup = ServiceRange(flag_line=2)
        t = self.popup
        t.line = QtGui.QDoubleSpinBox()
        t.setTitle(u"Поворот базиса вокруг оси")

        self.popup.current = QtGui.QLabel()
        self.popup.main_layout.addWidget(self.popup.current)
        self.popup.show()

    def draw_bars(self):
        self.statusBar().showMessage(u'Готов')#Запуск платформы по порту №'+str(self.COMnum))
        mymenu = self.menuBar()

        filemenu = mymenu.addMenu(u'Файл')
        openAction = QtGui.QAction(QtGui.QIcon('exit.png'), u'Открыть файл', self)
        openAction.triggered.connect(self.dialog_open_file)
        filemenu.addAction(openAction)

        saveAction = QtGui.QAction(QtGui.QIcon('exit.png'), u'Сохранить файл', self)
        saveAction.triggered.connect(self.dialog_save_file)
        filemenu.addAction(saveAction)

        exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), u'Выход', self)
        exitAction.triggered.connect(self.close)
        filemenu.addAction(exitAction)

        servicemenu = mymenu.addMenu(u'Сервис')

        serviceRange = QtGui.QAction(QtGui.QIcon('exit.png'), u'Проверка диапазона', self)
        serviceRange.triggered.connect(self.service_popup_range_wrap)
        servicemenu.addAction(serviceRange)

        serviceAngles = QtGui.QAction(QtGui.QIcon('exit.png'), u'Проверка углов', self)
        serviceAngles.triggered.connect(self.service_popup_angles_wrap)
        servicemenu.addAction(serviceAngles)

        serviceAcceleration = QtGui.QAction(QtGui.QIcon('exit.png'), u'Проверка ускорения', self)
        serviceAcceleration.triggered.connect(self.service_popup_acceleration_wrap)
        servicemenu.addAction(serviceAcceleration)

        serviceRotation = QtGui.QAction(QtGui.QIcon('exit.png'), u'Повернуть систему координат', self)
        serviceRotation.triggered.connect(self.service_popup_coord_rotation_wrap)
        servicemenu.addAction(serviceRotation)

        serviceInit = QtGui.QAction(QtGui.QIcon('exit.png'), u'Инициализация', self)
        servicemenu.addAction(serviceInit)

        return

    def draw_left_part(self):
        from Visual.RadioPlot import PlotElem
        plotsbox = QtGui.QVBoxLayout()
        self.plotX = PlotElem('X')
        self.plotY = PlotElem('Y')
        self.plotZ = PlotElem('Z')
        plotsbox.addLayout(self.plotX)
        plotsbox.addLayout(self.plotY)
        plotsbox.addLayout(self.plotZ)
        self.parts[0].setLayout(plotsbox)

    def draw_right_part(self):
        rightPart = QtGui.QVBoxLayout()

        from pyqtgraph import PlotWidget
        pl = PlotWidget()
        self.plotU = pl.plot(pen=(255, 0, 0))

        rightPart.addWidget(pl)

        self.menuLayout = QtGui.QGridLayout()

        temp = QtGui.QHBoxLayout()
        templabel = QtGui.QLabel(u'  COM порт №    ')
        self.text_COM_number = QtGui.QLineEdit()
        temp.addWidget(templabel)
        temp.addWidget(self.text_COM_number)

        self.button_setCOM = QtGui.QPushButton(u'Выбрать')
        self.button_setCOM.clicked.connect(self.button_setCOM_pressed)
        temp.addWidget(self.button_setCOM)
        temp.addStretch(1)

        #self.menuLayout.addWidget(self.button_setCOM, 0, 1)#, alignment=1)
        self.menuLayout.addLayout(temp,0,0)

        temp = QtGui.QHBoxLayout()
        self.button_hardware = QtGui.QPushButton(u'Старт платформы')
        self.button_hardware.clicked.connect(self.button_hardware_pressed)
        temp.addWidget(self.button_hardware)
        #self.menuLayout.addWidget(self.button_hardware, 1, 0)#, alignment=1)

        self.button_watch = QtGui.QPushButton(u'Начать просмотр')
        self.button_watch.clicked.connect(self.button_watch_pressed)
        temp.addWidget(self.button_watch)

        self.button_record = QtGui.QPushButton(u' Начать запись ')
        self.button_record.clicked.connect(self.button_record_pressed)
        temp.addWidget(self.button_record)
        temp.addStretch(1)

        self.menuLayout.addLayout(temp, 1,0)#Widget(self.button_watch, 1, 1)#, alignment=1)

        self.menuLayout.addLayout(self.build_parameters_menu(), 2, 0)

        temp = QtGui.QHBoxLayout()
        temp.insertSpacing(-1, 10)
        self.string_message = QtGui.QLineEdit()
        temp.addWidget(self.string_message)

        self.button_send_string = QtGui.QPushButton(u'Отправить строку')
        self.button_send_string.clicked.connect(self.button_send_string_pressed)
        temp.addWidget(self.button_send_string)
        temp.insertStretch(-1, 1)
        self.menuLayout.addLayout(temp, 3, 0)#, alignment=1)

        rightPart.addLayout(self.menuLayout)

        self.parts[1].setLayout(rightPart)

    def build_parameters_menu(self):
        temp = QtGui.QGridLayout()

        temp1 = QtGui.QLabel(u'A, mm, 0-20')
        temp1.setAlignment(QtCore.Qt.AlignCenter)
        temp.addWidget(temp1, 0, 0)
        self.parameter_A = QtGui.QLineEdit()
        temp.addWidget(self.parameter_A, 1,0)

        temp1 = QtGui.QLabel(u't1')
        temp1.setAlignment(QtCore.Qt.AlignCenter)
        temp.addWidget(temp1, 0, 1)
        self.parameter_t1 = QtGui.QLineEdit()
        temp.addWidget(self.parameter_t1, 1, 1)

        temp1 = QtGui.QLabel(u't2')
        temp1.setAlignment(QtCore.Qt.AlignCenter)
        temp.addWidget(temp1, 0, 2)
        self.parameter_t2 = QtGui.QLineEdit()
        temp.addWidget(self.parameter_t2, 1, 2)

        temp1 = QtGui.QLabel(u't3')
        temp1.setAlignment(QtCore.Qt.AlignCenter)
        temp.addWidget(temp1, 0, 3)

        self.parameter_t3 = QtGui.QLineEdit()
        temp.addWidget(self.parameter_t3, 1, 3)

        temp1 = QtGui.QLabel(u'T')
        temp1.setAlignment(QtCore.Qt.AlignCenter)
        temp.addWidget(temp1, 0, 4)
        self.parameter_T = QtGui.QLineEdit()
        temp.addWidget(self.parameter_T, 1, 4)

        self.button_setMessage = QtGui.QPushButton(u'Установить сообшение')
        self.button_setMessage.clicked.connect(self.button_setMessage_pressed)
        temp.addWidget(self.button_setMessage, 0, 5)

        self.button_sendMessage = QtGui.QPushButton(u'Отправить сообшение')
        self.button_sendMessage.clicked.connect(self.button_sendMessage_pressed)

        temp.addWidget(self.button_sendMessage, 1, 5)

        temp.setContentsMargins(10,10,100,10)

        return temp

    def button_setMessage_pressed(self):
        try:
            A = float(self.parameter_A.text())
        except:
            self.statusBar().showMessage(u'Ошибка в параметре А')
            return

        try:
            t1 = float(self.parameter_t1.text())
        except:
            self.statusBar().showMessage(u'Ошибка в параметре t1')
            return

        try:
            t2 = float(self.parameter_t2.text())
        except:
            self.statusBar().showMessage(u'Ошибка в параметре t2')
            return

        try:
            t3 = float(self.parameter_t3.text())
        except:
            self.statusBar().showMessage(u'Ошибка в параметре t3')
            return

        try:
            T = float(self.parameter_T.text())
        except:
            self.statusBar().showMessage(u'Ошибка в параметре T')
            return

        p1 = int(A)
        if p1<1: p1 = 1

        p2 = int(t1/(p1*3.1875*10**(-5)))
        if p2<1: p2 = 1

        p3 = int(t2/(3.1875*10**(-5)))
        if p3<1: p3 = 1

        p4 = int(t3/(p1*3.1875*10**(-5)))
        if p4<1: p4 = 1

        p5 = int((T-t1-t2-t3)/(3.1875*10**(-4)))
        if p5<1: p5 = 1

        self.message = '! '+str(p1)+', '+str(p2)+', '+str(p3)+', '+str(p4)+', '+str(p5)+'='
        self.statusBar().showMessage(self.message)

        self.parameter_A.setText(str(p1))
        self.parameter_t1.setText(str(round(p1*p2*3.1875/10**5, 3)))
        self.parameter_t2.setText(str(round(p3*3.1875/10**5, 3)))
        self.parameter_t3.setText(str(round(p1*p4*3.1875/10**5, 3)))
        self.parameter_T.setText(str(round(t1 + t2 + t3 + p5*3.1875/10**4, 3)))

    def button_setCOM_pressed(self):
        s = self.text_COM_number.text()
        if str(s)!= '':
            self.COMnum = str(s)
            self.statusBar().showMessage(u"Выбран порт № "+self.COMnum)
        else:
            self.statusBar().showMessage(u"Выбран порт по умолчанию - порт № "+self.COMnum)
        return

    def button_sendMessage_pressed(self):
        if not self.flag["hardware run"]:
            self.statusBar().showMessage(u'Перед отправкой сообщения необходимо подключиться к аппаратуре')
            return

        mess = self.message
        if mess == "":
            self.statusBar().showMessage(u'Нельзя отправить пустое сообщение')
            return
        self.statusBar().showMessage(u'Сообщение отправлено')
        self.message = ""
        hw.ComSend(self.com, mess)

    def button_send_string_pressed(self):
        if not self.flag["hardware run"]:
            self.statusBar().showMessage(u'Перед отправкой строки необходимо подключиться к аппаратуре')
            return

        mess = str(self.string_message.text())
        if mess == "":
            self.statusBar().showMessage(u'Нельзя отправить пустую строку')
            return
        self.statusBar().showMessage(u'Строка отправлена')
        print mess
        hw.ComSend(self.com, mess)


    def button_hardware_pressed(self):
        if self.flag["hardware run"]:
            self.button_hardware.setText(u'Старт платформы')
            hw.FinishComPort(self.com)
            self.flag["hardware run"] = 0
            self.data_reduced = np.zeros(self.data_reduced.shape)
            self.num_reduced_data = 0
        else:
            self.button_hardware.setText(u'Остановка платформы')
            self.com = hw.StartComPort(num=self.COMnum)
            self.flag["hardware run"] = 1

        return

    def button_watch_pressed(self):
        if self.flag["hardware run"] == 0:
            self.statusBar().showMessage(u'Сначала подключитесь к аппаратуре')
            return

        if self.flag["play run"]:
            self.flag["play run"] = 0
            self.button_watch.setText(u'Начать просмотр')
        else:
            self.flag["play run"] = 1
            self.button_watch.setText(u'Остановить просмотр')

        return

    def button_record_pressed(self):
        if self.flag["record run"]:
            self.button_record.setText(u"Включить запись")
            self.flag["record run"] = 0
            self.flag["record_reset"] = 1
            self.statusBar().showMessage(u"Запись остановлена. Сохраните файл")
            return
        if self.flag["hardware run"]==0:
            self.statusBar().showMessage(u"Запись невозможна без подключения к аппаратуре")
            return

        if self.flag["play run"] == 0:
            self.statusBar().showMessage(u"Запись невозможна без включения просмотра")
            return

        self.data_for_record = np.zeros(self.data_for_record.shape)
        self.num_record = 0

        self.flag["record run"] = 1
        self.button_record.setText(u"Остановить запись")
        return

    def dialog_open_file(self):
        curr_path = os.path.dirname('C:\\')
        fname, _ = QtGui.QFileDialog.getOpenFileName(self, u'Открыть файл',
                    curr_path)
        try:
            f = open(fname, 'r')
        except:
            return

        return
        with f:
            locflag = self.read_trajectory(file=f)
            if locflag:
                self.statusBar().showMessage(u'Данные получены')
                self.flag["trajectory load"] = 1
            else:
                self.msgBox = QtGui.QMessageBox.information(self,"Open file error","Errors in trajectory, wasnt loaded")

        return

    def dialog_save_file(self):
        fname, _ = QtGui.QFileDialog.getSaveFileName(self,u'Сохранить файл', os.path.dirname('C:\\'))#os.path.abspath(__file__)),"Text files (*.txt)")
        data = self.data_for_record[0:self.num_record].copy()
        data = np.around(data, decimals=3)
        try:
            f = open(fname, 'w')
        except:
            return
        for line in data:
            s = str(line)
            s = s.strip("]")
            s = s.strip("[")
            s += '\n'
            f.write(s)
        f.close()

    def updater(self):
        if self.flag["hardware run"]:
            self.hard_data_recieve()

        self.counter += 1
        if self.counter == self.const_process_rate:
            self.processData()

            if self.flag["play run"]:
                self.data_draw()

            if self.flag["trajectory load"]:
                self.show_trajectory()
            self.counter = 0

    def read_trajectory(self, file):
        return
        traj = np.zeros((1000,7))#{"time": [], "accX": [], "accY": [], "accZ": [], "angvX": [], "angvY": [], "angvZ": []}
        for line in file:
            line = line.split('\n')[0]
            if self.check_trajectory_data(line):
                line = line.split(' ')
                traj["time"].append(float(line[0]))
                traj["accX"].append(float(line[1]))
                traj["accY"].append(float(line[2]))
                traj["accZ"].append(float(line[3]))
                traj["angvX"].append(float(line[4]))
                traj["angvY"].append(float(line[5]))
                traj["angvZ"].append(float(line[6]))
            else:
                return 0
        self.data_traj = traj
        return 1

    def check_trajectory_data(self, datum):
        return 1
        locd = datum.split(' ')
        locd = locd.strip('[')
        if len(locd) != 7: #7 parametrov razdelennih probelami
            return 0
        locd_int = []
        for x in locd:
            try:
                locd_int.append(float(x)) #vse 7 - cifri
            except:
                return 0
        if locd_int[0]<0: #vremya otrizatelnoye
            return 0
        return 1

    def show_trajectory(self):
        self.plotX.setData(data=self.data_traj, fl='t')
        self.plotY.setData(data=self.data_traj, fl='t')
        self.plotZ.setData(data=self.data_traj, fl='t')
        return

    def hard_data_recieve(self):
        res = hw.ComListen(self.com)
        if res[0] != 1:
            return

        res = res[1]
        leng = len(res)

        n = self.num_hard_data
        if leng == 0:
            return
        try:
            self.data_from_hard[n:(n+leng),:] = res

        except:
            print(leng, res.shape)
            print(self.data_from_hard[n:(n+leng),:].shape,n, n+leng)
        self.num_hard_data += leng

        if self.flag["play run"]:
            if self.num_reduced_data < self.const_reduced_data*1.5:
                self.data_reduced[self.num_reduced_data] = res[0]
                self.num_reduced_data += 1
            self.flag["new data"] = 1

            if self.flag["record run"]:
                if self.num_reduced_data < len(self.data_for_record):
                    self.data_for_record[self.num_record] = res[0]
                    self.num_record += 1
                else:
                    self.statusBar().showMessage(u'Слишком длинная траектория. Перезапустите или сохраните')#Запуск платформы по порту №'+str(self.COMnum))

    def processData(self):
        if not(self.flag["hardware run"]):
            return

        if self.num_hard_data > self.const_hard_data:
            self.data_from_hard = processHardData(self.data_from_hard, self.const_hard_data, flagwrite=self.flag["record run"])
            self.num_hard_data = 0

        if self.num_hard_data > self.const_hard_data*2:
            self.num_hard_data = 0

        if (self.data_reduced[self.num_reduced_data-1][0] - self.data_reduced[0][0]) > self.border_time:
            self.const_reduced_data = int(self.num_reduced_data - 1)
            #self.data_reduced = self.data_reduced[0:self.const_reduced_data*2]

        if self.num_reduced_data > self.const_reduced_data*1.5:
            self.data_reduced = processHardData(self.data_reduced, self.const_reduced_data)
            self.num_reduced_data = 0

        if self.num_reduced_data > self.const_reduced_data:
            t = int(self.const_reduced_data*0.9)
            self.num_reduced_data = t
            temp = self.data_reduced[self.const_reduced_data-t:]
            self.data_reduced[:t-self.const_reduced_data] = temp
            print(self.data_reduced[self.num_reduced_data,0] - self.data_reduced[0,0])
            if self.data_reduced[self.num_reduced_data][0]- self.data_reduced[0,0] < 0.9*self.border_time:
                self.const_reduced_data = int(1.1*self.const_reduced_data)

    def data_draw(self):
        if not self.flag["new data"]:
            return
        if not self.flag["play run"]:
            return
        n = self.num_reduced_data
        if n<=2:
            return
        temp = np.copy(self.data_reduced[0:n-1])
        temp[:,0] -= temp[0,0]

        self.plotX.setData(data=temp)
        self.plotY.setData(data=temp)
        self.plotZ.setData(data=temp)
        self.flag["new data"] = 0

        if self.flag["record run"] or self.flag["record_reset"]:
            n = self.num_record
            temp = np.copy(self.data_for_record[0:n-1])
            temp[:, 0] -= self.data_reduced[0,0]

            self.plotX.setData(data=temp, fl='r')
            self.plotY.setData(data=temp, fl='r')
            self.plotZ.setData(data=temp, fl='r')
        else:

            if (self.data_for_record[0][0]<self.data_reduced[0][0]):
                if (self.data_for_record[self.num_record-1][0]>self.data_reduced[0][0]):
                    self.flag["record_reset"] = 0
                    self.plotX.resetRecord()
                    self.plotY.resetRecord()
                    self.plotZ.resetRecord()
        return