Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python3
- # -*- coding: utf-8 -*-
- import sys
- from PyQt5.QtWidgets import *
- from PyQt5.QtGui import *
- from PyQt5.QtCore import *
- from PyQt5 import *
- import serial
- import time
- import glob
- import codecs
- import binascii
- from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
- from matplotlib.figure import Figure
- import matplotlib.pyplot as plt
- import random
- ser = serial.Serial()
- recieved = []
- class ComboBox(QComboBox):
- popupAboutToBeShown = pyqtSignal()
- def showPopup(self):
- self.popupAboutToBeShown.emit()
- super(ComboBox, self).showPopup()
- class Example(QMainWindow):
- def __init__(self):
- super().__init__()
- self.initUI()
- def initUI(self):
- QToolTip.setFont(QFont('SansSerif', 10))
- self.setToolTip('Это главное окно программы')
- global recieveBox
- recieveBox = QTextEdit(self) #текстовое поле отправки данных
- recieveBox.setGeometry(50, 100, 350, 240)
- recieveBox.setPlainText("Поле для приема данных")
- recieveBox.setToolTip("Поле для приема данных")
- ## while ser.isOpen:
- ## line = ser.readline()
- ## recieveBox.setText(line)
- ## while True:
- ## line = ser.read()
- ## if line:
- ## received.append(line.decode().strip())
- clearRecieveBox = QPushButton('Очистить поле принятых данных', self)
- clearRecieveBox.resize(clearRecieveBox.sizeHint())
- clearRecieveBox.setGeometry(50, 345, 350, 35)
- clearRecieveBox.setToolTip("Нажмите чтобы очистить поле принятых данных")
- clearRecieveBox.clicked.connect(self.clear_Recieve_Box)
- global transmitBox
- transmitBox = QTextEdit(self) # текстовое поле приема данных
- transmitBox.setGeometry(50, 385, 350, 60)
- transmitBox.setPlainText("Поле для отправки данных")
- transmitBox.setToolTip("Поле для отправки данных")
- sendData= QPushButton('Отправить', self)
- sendData.resize(sendData.sizeHint())
- sendData.setGeometry(50, 450, 350, 35)
- sendData.setToolTip('Нажмите чтобы отправить данные')
- sendData.clicked.connect(self.send_Data)
- global setPort
- setPort = ComboBox(self) # комбобокс для выбора порта
- setPort.setStatusTip('Hi!')
- setPort.setGeometry(50, 50, 50, 25)
- setPort.setToolTip('Выберите порт')
- setPort.resize(setPort.sizeHint())
- setPort.popupAboutToBeShown.connect(self.setPortClicked)
- setPort.activated[str].connect(self.setPort_Activated)
- labelPort = QLabel(self) # лейбл "выберите порт"
- labelPort.move(50, 25)
- labelPort.setText('Выберите порт')
- setSpeed = QComboBox(self) # комбобокс для выбора скорости
- setSpeed.setGeometry(150, 50, 50, 25)
- setSpeed.setToolTip('Выберите скорость')
- setSpeed.addItems(['1200', '2400', '4800', '9600', '14400', '19200', '56000', '115200'])
- setSpeed.resize(setSpeed.sizeHint())
- setSpeed.activated[str].connect(self.setSpeed_Activated)
- labelSpeed = QLabel(self)# лейбл "выберите скорость"
- labelSpeed.move(150, 25)
- labelSpeed.setText('Выберите скорость')
- closePortButton = QPushButton("Закрыть порт", self)
- closePortButton.setToolTip('Нажмите на кнопку чтобы закрыть порт')
- closePortButton.resize(closePortButton.sizeHint())
- closePortButton.move(250, 50)
- closePortButton.clicked.connect(self.closePort)
- global portStatus
- portStatus = QLabel(self)
- portStatus.move(50, 75)
- portStatus.setText('Порт закрыт')
- portStatus.setStyleSheet("color: rgb(255, 0, 0);")
- portStatus.resize(portStatus.sizeHint())
- exitAction = QAction(QIcon('web.ico'), '&Exit', self)
- exitAction.setShortcut('Ctrl+Q')
- exitAction.setStatusTip('Exit')
- exitAction.triggered.connect(qApp.quit)
- printAction = QAction(QIcon('web.ico'), 'Printhello', self)
- printAction.setShortcut('Ctrl+H')
- printAction.setStatusTip('print Hello')
- printAction.triggered.connect(self.printhello)
- self.statusBar()
- menubar = self.menuBar()
- fileMenu = menubar.addMenu('&File')
- fileMenu.addAction(exitAction)
- optionsMenu = menubar.addMenu('&Options')
- optionsMenu.addAction(printAction)
- m = PlotCanvas(self, width=5, height=4) #график
- m.move(450,100)
- self.setGeometry(300, 300, 1000, 550)
- self.setWindowTitle('Бесполезная программа')
- self.show()
- def setPortClicked(self):
- if ser.isOpen():
- ser.close()
- setPort.clear()
- setPort.addItems(self.serial_ports())
- def serial_ports(self): # список компортов
- if sys.platform.startswith('win'):
- ports = ['COM%s' % (i + 1) for i in range(256)]
- elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
- # this excludes your current terminal "/dev/tty"
- ports = glob.glob('/dev/tty[A-Za-z]*')
- else:
- raise EnvironmentError('Unsupported platform')
- result = []
- for port in ports:
- try:
- ## ser.port = port
- ## ser.close()
- s = serial.Serial(port)
- s.close()
- result.append(port)
- except (OSError, serial.SerialException):
- pass
- return result
- def closeEvent(self, event):
- reply = QMessageBox.question(self, 'Выход', "Закрыть программу?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
- if reply == QMessageBox.Yes:
- event.accept()
- else:
- event.ignore()
- def printhello(self):
- print('Hello!')
- def setSpeed_Activated(self, text): # функция выбора скорости
- self.br = text
- ser.baudrate = text
- print(ser.baudrate)
- ## setSpeed.setStatusTip("установлена скорость")
- def setPort_Activated(self, text): # функция выбора компорта и его открытия
- self.sp = text
- ser.port = text
- if (ser.isOpen == True):
- print("open")
- else:
- ser.open()
- print('%s' % ser.port + " opened")
- portStatus.setText('Порт ' + '%s' % ser.port + ' открыт')
- portStatus.setStyleSheet("color: rgb(0, 255, 0);")
- portStatus.resize(portStatus.sizeHint())
- ser.timeout = 1
- ser.writeTimeout = 10
- time.sleep(0.5)
- self.reciver()
- ## while (ser.inWaiting() > 0):
- ## line = ser.readline()
- ## recieveBox.setPlainText(line)
- ## print(line)
- ## if line:
- ## received.append(line.decode().strip())
- def closePort(self):
- ser.close()
- if (ser.isOpen != True):
- print('%s' % ser.port + " closed")
- portStatus.setText('Порт ' + '%s' % ser.port + ' закрыт')
- portStatus.setStyleSheet("color: rgb(255, 0, 0);")
- def send_Data(self):
- ## data = transmitBox.toPlainText()
- ## data.encode("ascii")
- ## print(data)
- ## print(help(data.encode))
- ## print(ascii(transmitBox.toPlainText()))
- ## print(ser)
- if ser.isOpen():
- ## ser.flushInput()
- ## ser.flushOutput()
- ## ser.write(ascii(transmitBox.toPlainText()))
- ser.write(transmitBox.toPlainText().encode())
- print(transmitBox.toPlainText().encode())
- ## s = str(transmitBox.toPlainText())
- ## print(s.hex())
- ## s.hex()
- ## ser.write(b'\x55')
- def clear_Recieve_Box(self):
- print('RecieveBox cleared')
- recieveBox.clear()
- def reciver(self):
- while (ser.inWaiting() > 0):
- line = ser.readline()
- recieveBox.setPlainText(line)
- print(line + "you recived")
- class PlotCanvas(FigureCanvas): # класс графика
- def __init__(self, parent=None, width=5, height=4, dpi=100):
- fig = Figure(figsize=(width, height), dpi=dpi)
- self.axes = fig.add_subplot(111)
- FigureCanvas.__init__(self, fig)
- self.setParent(parent)
- FigureCanvas.setSizePolicy(self,
- QSizePolicy.Expanding,
- QSizePolicy.Expanding)
- FigureCanvas.updateGeometry(self)
- self.plot()
- def plot(self):
- data = [random.random() for i in range(60)]
- ax = self.figure.add_subplot(111)
- ax.plot(data, 'y-')
- ax.set_title('Тестовый график')
- ax.set_xlabel("Время, с")
- ax.set_xlim(xmin = 0, xmax = 60)
- ax.set_ylabel("Напряжение, В")
- ax.set_ylim(ymin = 0, ymax = 3)
- self.draw()
- try:
- while (ser.inWaiting() > 0):
- line = ser.readline()
- recieveBox.setPlainText(line)
- print(line + "you recived")
- except (OSError, serial.SerialException):
- pass
- if __name__ == '__main__':
- app = QApplication(sys.argv)
- ex = Example()
- sys.exit(app.exec_())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement