Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2020
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.93 KB | None | 0 0
  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. import sys
  4. from PyQt5.QtWidgets import *
  5. from PyQt5.QtGui import *
  6. from PyQt5.QtCore import *
  7. from PyQt5 import *
  8. import serial
  9. import time
  10. import glob
  11. import codecs
  12. import binascii
  13.  
  14. from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
  15. from matplotlib.figure import Figure
  16. import matplotlib.pyplot as plt
  17.  
  18. import random
  19.  
  20. ser = serial.Serial()
  21. recieved = []
  22.  
  23.  
  24. class ComboBox(QComboBox):
  25. popupAboutToBeShown = pyqtSignal()
  26.  
  27. def showPopup(self):
  28. self.popupAboutToBeShown.emit()
  29. super(ComboBox, self).showPopup()
  30.  
  31. class Example(QMainWindow):
  32.  
  33.  
  34. def __init__(self):
  35. super().__init__()
  36. self.initUI()
  37.  
  38.  
  39. def initUI(self):
  40.  
  41. QToolTip.setFont(QFont('SansSerif', 10))
  42.  
  43. self.setToolTip('Это главное окно программы')
  44.  
  45. global recieveBox
  46. recieveBox = QTextEdit(self) #текстовое поле отправки данных
  47. recieveBox.setGeometry(50, 100, 350, 240)
  48. recieveBox.setPlainText("Поле для приема данных")
  49. recieveBox.setToolTip("Поле для приема данных")
  50. ## while ser.isOpen:
  51. ## line = ser.readline()
  52. ## recieveBox.setText(line)
  53. ## while True:
  54. ## line = ser.read()
  55. ## if line:
  56. ## received.append(line.decode().strip())
  57.  
  58. clearRecieveBox = QPushButton('Очистить поле принятых данных', self)
  59. clearRecieveBox.resize(clearRecieveBox.sizeHint())
  60. clearRecieveBox.setGeometry(50, 345, 350, 35)
  61. clearRecieveBox.setToolTip("Нажмите чтобы очистить поле принятых данных")
  62. clearRecieveBox.clicked.connect(self.clear_Recieve_Box)
  63.  
  64.  
  65. global transmitBox
  66. transmitBox = QTextEdit(self) # текстовое поле приема данных
  67. transmitBox.setGeometry(50, 385, 350, 60)
  68. transmitBox.setPlainText("Поле для отправки данных")
  69. transmitBox.setToolTip("Поле для отправки данных")
  70.  
  71. sendData= QPushButton('Отправить', self)
  72. sendData.resize(sendData.sizeHint())
  73. sendData.setGeometry(50, 450, 350, 35)
  74. sendData.setToolTip('Нажмите чтобы отправить данные')
  75. sendData.clicked.connect(self.send_Data)
  76.  
  77. global setPort
  78. setPort = ComboBox(self) # комбобокс для выбора порта
  79. setPort.setStatusTip('Hi!')
  80. setPort.setGeometry(50, 50, 50, 25)
  81. setPort.setToolTip('Выберите порт')
  82. setPort.resize(setPort.sizeHint())
  83. setPort.popupAboutToBeShown.connect(self.setPortClicked)
  84. setPort.activated[str].connect(self.setPort_Activated)
  85.  
  86. labelPort = QLabel(self) # лейбл "выберите порт"
  87. labelPort.move(50, 25)
  88. labelPort.setText('Выберите порт')
  89.  
  90. setSpeed = QComboBox(self) # комбобокс для выбора скорости
  91. setSpeed.setGeometry(150, 50, 50, 25)
  92. setSpeed.setToolTip('Выберите скорость')
  93. setSpeed.addItems(['1200', '2400', '4800', '9600', '14400', '19200', '56000', '115200'])
  94. setSpeed.resize(setSpeed.sizeHint())
  95. setSpeed.activated[str].connect(self.setSpeed_Activated)
  96.  
  97. labelSpeed = QLabel(self)# лейбл "выберите скорость"
  98. labelSpeed.move(150, 25)
  99. labelSpeed.setText('Выберите скорость')
  100.  
  101. closePortButton = QPushButton("Закрыть порт", self)
  102. closePortButton.setToolTip('Нажмите на кнопку чтобы закрыть порт')
  103. closePortButton.resize(closePortButton.sizeHint())
  104. closePortButton.move(250, 50)
  105. closePortButton.clicked.connect(self.closePort)
  106.  
  107. global portStatus
  108. portStatus = QLabel(self)
  109. portStatus.move(50, 75)
  110. portStatus.setText('Порт закрыт')
  111. portStatus.setStyleSheet("color: rgb(255, 0, 0);")
  112. portStatus.resize(portStatus.sizeHint())
  113.  
  114. exitAction = QAction(QIcon('web.ico'), '&Exit', self)
  115. exitAction.setShortcut('Ctrl+Q')
  116. exitAction.setStatusTip('Exit')
  117. exitAction.triggered.connect(qApp.quit)
  118.  
  119. printAction = QAction(QIcon('web.ico'), 'Printhello', self)
  120. printAction.setShortcut('Ctrl+H')
  121. printAction.setStatusTip('print Hello')
  122. printAction.triggered.connect(self.printhello)
  123.  
  124. self.statusBar()
  125. menubar = self.menuBar()
  126.  
  127. fileMenu = menubar.addMenu('&File')
  128. fileMenu.addAction(exitAction)
  129. optionsMenu = menubar.addMenu('&Options')
  130. optionsMenu.addAction(printAction)
  131.  
  132. m = PlotCanvas(self, width=5, height=4) #график
  133. m.move(450,100)
  134.  
  135. self.setGeometry(300, 300, 1000, 550)
  136. self.setWindowTitle('Бесполезная программа')
  137.  
  138. self.show()
  139.  
  140. def setPortClicked(self):
  141. if ser.isOpen():
  142. ser.close()
  143. setPort.clear()
  144. setPort.addItems(self.serial_ports())
  145.  
  146.  
  147.  
  148. def serial_ports(self): # список компортов
  149.  
  150. if sys.platform.startswith('win'):
  151. ports = ['COM%s' % (i + 1) for i in range(256)]
  152. elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
  153. # this excludes your current terminal "/dev/tty"
  154. ports = glob.glob('/dev/tty[A-Za-z]*')
  155. else:
  156. raise EnvironmentError('Unsupported platform')
  157.  
  158. result = []
  159. for port in ports:
  160. try:
  161. ## ser.port = port
  162. ## ser.close()
  163. s = serial.Serial(port)
  164. s.close()
  165. result.append(port)
  166. except (OSError, serial.SerialException):
  167. pass
  168. return result
  169.  
  170. def closeEvent(self, event):
  171. reply = QMessageBox.question(self, 'Выход', "Закрыть программу?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
  172. if reply == QMessageBox.Yes:
  173. event.accept()
  174. else:
  175. event.ignore()
  176.  
  177. def printhello(self):
  178. print('Hello!')
  179.  
  180. def setSpeed_Activated(self, text): # функция выбора скорости
  181. self.br = text
  182. ser.baudrate = text
  183. print(ser.baudrate)
  184. ## setSpeed.setStatusTip("установлена скорость")
  185.  
  186. def setPort_Activated(self, text): # функция выбора компорта и его открытия
  187. self.sp = text
  188. ser.port = text
  189. if (ser.isOpen == True):
  190. print("open")
  191. else:
  192. ser.open()
  193. print('%s' % ser.port + " opened")
  194. portStatus.setText('Порт ' + '%s' % ser.port + ' открыт')
  195. portStatus.setStyleSheet("color: rgb(0, 255, 0);")
  196. portStatus.resize(portStatus.sizeHint())
  197. ser.timeout = 1
  198. ser.writeTimeout = 10
  199. time.sleep(0.5)
  200. self.reciver()
  201. ## while (ser.inWaiting() > 0):
  202. ## line = ser.readline()
  203. ## recieveBox.setPlainText(line)
  204. ## print(line)
  205. ## if line:
  206. ## received.append(line.decode().strip())
  207.  
  208. def closePort(self):
  209. ser.close()
  210. if (ser.isOpen != True):
  211. print('%s' % ser.port + " closed")
  212. portStatus.setText('Порт ' + '%s' % ser.port + ' закрыт')
  213. portStatus.setStyleSheet("color: rgb(255, 0, 0);")
  214.  
  215. def send_Data(self):
  216. ## data = transmitBox.toPlainText()
  217. ## data.encode("ascii")
  218. ## print(data)
  219. ## print(help(data.encode))
  220. ## print(ascii(transmitBox.toPlainText()))
  221. ## print(ser)
  222. if ser.isOpen():
  223. ## ser.flushInput()
  224. ## ser.flushOutput()
  225. ## ser.write(ascii(transmitBox.toPlainText()))
  226. ser.write(transmitBox.toPlainText().encode())
  227. print(transmitBox.toPlainText().encode())
  228. ## s = str(transmitBox.toPlainText())
  229. ## print(s.hex())
  230. ## s.hex()
  231. ## ser.write(b'\x55')
  232.  
  233. def clear_Recieve_Box(self):
  234. print('RecieveBox cleared')
  235. recieveBox.clear()
  236.  
  237. def reciver(self):
  238. while (ser.inWaiting() > 0):
  239. line = ser.readline()
  240. recieveBox.setPlainText(line)
  241. print(line + "you recived")
  242.  
  243.  
  244. class PlotCanvas(FigureCanvas): # класс графика
  245.  
  246. def __init__(self, parent=None, width=5, height=4, dpi=100):
  247. fig = Figure(figsize=(width, height), dpi=dpi)
  248. self.axes = fig.add_subplot(111)
  249.  
  250. FigureCanvas.__init__(self, fig)
  251. self.setParent(parent)
  252.  
  253. FigureCanvas.setSizePolicy(self,
  254. QSizePolicy.Expanding,
  255. QSizePolicy.Expanding)
  256. FigureCanvas.updateGeometry(self)
  257. self.plot()
  258.  
  259.  
  260. def plot(self):
  261. data = [random.random() for i in range(60)]
  262. ax = self.figure.add_subplot(111)
  263. ax.plot(data, 'y-')
  264. ax.set_title('Тестовый график')
  265. ax.set_xlabel("Время, с")
  266. ax.set_xlim(xmin = 0, xmax = 60)
  267. ax.set_ylabel("Напряжение, В")
  268. ax.set_ylim(ymin = 0, ymax = 3)
  269. self.draw()
  270.  
  271. try:
  272. while (ser.inWaiting() > 0):
  273. line = ser.readline()
  274. recieveBox.setPlainText(line)
  275. print(line + "you recived")
  276. except (OSError, serial.SerialException):
  277. pass
  278.  
  279.  
  280. if __name__ == '__main__':
  281. app = QApplication(sys.argv)
  282. ex = Example()
  283. sys.exit(app.exec_())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement