-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprogram.py
299 lines (263 loc) · 13.5 KB
/
program.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
#-*-coding: utf8-*-
import sys
from PyQt4 import QtGui, QtCore
from collections import OrderedDict
from serial.tools import list_ports
import serial
import time
import re
from config import Config
from ui.iwsk import Ui_Dialog
# TODO: add automatic terminator option
class MyDialog(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, parent)
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.myConfig = Config()
# bufor na tekst do wysłania
self.sendTextBuffor = u''
# bufor na wartości odczytane
self.bufferRecived = u''
# Opcje wyboru sterowania magistrali
self.protocolOptionDict = {'Brak': ' ', 'CTRL-S/CTRL-Q': 'xonxoff', 'DSR/DTR': 'dsrdtr', 'RTS/CTS': 'rtscts'}
# Terminatory standardowe + terminator w?asny
# ASCII 10 -LF 13 -CR
self.treminatorTypes = OrderedDict([('CR', chr(13)), ('LF', chr(10)), \
('CR, LF', chr(13) + chr(10)), \
('brak', ''), \
(u'własny', '')])
# Tworzymy lista dostępnych w systemie portów COM
self.comPortsList = [portList[0] for portList in list_ports.comports()]
#Timmer do odbioru danych/powoduje zap?tlenie programu
self.recivedTimer = QtCore.QTimer(self)
#
#
#
# Połączenie sygnałów/slotów - wewnętrzne sprawy Qt
self.ui.btn_open.clicked.connect(self.openPort)
self.ui.btn_close.clicked.connect(self.closePort)
self.ui.btn_save.clicked.connect(self.save)
self.ui.btn_clear_recived.clicked.connect(self.ui.o_recived_plainTextEdit.clear)
self.ui.btn_clear_send.clicked.connect(self.ui.o_send_plainTextEdit.clear)
self.ui.btn_send.clicked.connect(self.send)
self.ui.btn_pingFunction.clicked.connect(self.ping)
# self.ui.i_howMuchChars_spinBox.valueChanged(int).connect(self.changedSizeTerminator)
QtCore.QObject.connect(self.ui.i_howMuchChars_spinBox, QtCore.SIGNAL("valueChanged(int)"), self.changedSizeTerminator)
QtCore.QObject.connect(self.ui.tabWidget, QtCore.SIGNAL("currentChanged(int)"), self.reDrawKonfigurationTab)
self.recivedTimer.timeout.connect(self.recived)
self.ui.i_terminator_comboBox.currentIndexChanged[str].connect(self.terminatorChanged)
# Tworzenie listy obsługiwanych wartości szybkości transmisji
for baudRate in Config.serial.BAUDRATES:
self.ui.i_baudRate_comboBox.addItem(repr(baudRate))
# Tworzenie listy dostępnych portów COM - dla intefejsu użytkownika
for port in self.comPortsList:
self.ui.i_portName_comboBox.addItem(port)
# Dodajemy możliwe typy terminatora
for terminator in self.treminatorTypes.keys():
self.ui.i_terminator_comboBox.addItem(terminator)
# Dodajemy listę typów sterowania transmisją
for protocol in self.protocolOptionDict.keys():
self.ui.i_protocol_comboBox.addItem(protocol)
# Tworzymy listy obiektów intefejsu użytkownika
# reprezentująch parametry transmisji.
# W celu ułatwienia zarz?dzania transmisją.
# Długś słowa
self.byteSizeList = [self.ui.i_word_7bits_radio, \
self.ui.i_word_8bits_radio]
# Parzystość
self.paritiesList = [self.ui.i_parityNone_radio, \
self.ui.i_parityEven_radio, \
self.ui.i_parityOdd_radio]
# Liczba bitiów stopu
self.stopBitsList = [self.ui.i_stopBit1_radio, \
self.ui.i_stopBit2_radio]
self.readAndSetGui()
def readAndSetGui(self):
# Wczytujemy dane z poprzedniej konfiguracji jeśli taka była
timeoutConfigValue = self.myConfig.serialDict['timeout']
# Aktualizujemy interfejs użytkownika wczytanymi wartośćiami
if timeoutConfigValue:
self.ui.i_timeout_spinBox.setValue(timeoutConfigValue)
self.ui.i_baudRate_comboBox.setCurrentIndex(self.ui.i_baudRate_comboBox.\
findText(repr(self.myConfig.serialDict['baudrate'])))
self.ui.i_terminator_comboBox.setCurrentIndex(self.ui.i_terminator_comboBox.\
findText(self.myConfig.serialDict.get('terminator', 'CR')))
# protocolSet = lambda lista:
# self.ui.i_protocol_comboBox.setCurrentIndex(self.ui.i_protocol_comboBox.\
# findText(self.myConfig.serialDict.get('p
try:
self.ui.i_portName_comboBox.setCurrentIndex(self.comPortsList.index(self.myConfig.serialDict.get('port')))
except ValueError:
self.ui.i_portName_comboBox.setCurrentIndex(0)
self.ui.i_automaticTerminator_checkBox.setChecked(self.myConfig.serialDict.get('automaticTerminator', True))
if unicode(self.ui.i_terminator_comboBox.currentText()) == u"własny":
self.ui.i_itsTerminator_lineEdit.setText(self.myConfig.serialDict.get('itsTerminator', ''))
self.ui.i_howMuchChars_spinBox.setValue(len(unicode(self.ui.i_itsTerminator_lineEdit.text())))
# except KeyError:
# self.ui.i_portName_comboBox.setCurrentIndex(0)
# Odczytanie i ustwienie wybranej wartości długości słowa, parzystości, liczby bitów stopu
byteSizeIndex = Config.serial.BYTESIZES[2:].index(self.myConfig.serialDict['bytesize'])
paritiesIndex = Config.serial.PARITIES.index(self.myConfig.serialDict['parity'])
stopBitsIndex = Config.serial.STOPBITS[::2].index(self.myConfig.serialDict['stopbits'])
self.byteSizeList[byteSizeIndex].setChecked(True)
self.paritiesList[paritiesIndex].setChecked(True)
self.stopBitsList[stopBitsIndex].setChecked(True)
# Odczytanie i ustawienie wartości o sposobie zarządzania transmisją
if self.myConfig.serialDict['dsrdtr']:
protocolIndex = 2
elif self.myConfig.serialDict['rtscts']:
protocolIndex = 3
elif self.myConfig.serialDict['xonxoff']:
protocolIndex = 1
else:
protocolIndex = 0
self.ui.i_protocol_comboBox.setCurrentIndex(protocolIndex)
def reDrawKonfigurationTab(self, tab):
if tab == 1:
self.readAndSetGui()
def dtrRts(self):
Config.serial.setRTS(False)
Config.serial.setDTR(False)
if Config.serial.dsrdtr:
print "jeden"
self.dtrRtsWrite = Config.serial.setDTR
elif Config.serial.rtscts:
print "dwa"
self.dtrRtsWrite = Config.serial.setRTS
elif Config.serial.xonxoff:
print "trzy"
self.dtrRtsWrite = Config.serial.setXON
else:
self.dtrRtsWrite = lambda tekst: tekst
@QtCore.pyqtSlot()
def changedSizeTerminator(self, howMuch):
self.ui.i_itsTerminator_lineEdit.setMaxLength(howMuch)
@QtCore.pyqtSlot()
def openPort(self):
try:
Config.serial.open()
self.dtrRts()
self.dtrRtsWrite(True)
# self.dtrRtsWrite(True)
self.recivedTimer.start(1000)
print u"Port Opened / Port otwarty"
except serial.serialutil.SerialException:
print u"Port %s jest juz otwarty!" \
% (self.myConfig.serialDict['port'])
@QtCore.pyqtSlot()
def closePort(self):
self.recivedTimer.stop()
Config.serial.close()
print u"Port Closed / Prot zamknięty"
@QtCore.pyqtSlot()
def recived(self):
# TODO: ogarnac xonxoff
# xonxoff = False
recivedText = u''
if Config.serial.inWaiting():
print "\tgetCTS:%s getDSR:%s\n\tgetRtsCts:%s getRtsToggle:%s" \
% (Config.serial.getCTS(), Config.serial.getDSR(), Config.serial.getRtsCts(), Config.serial.getRtsToggle())
if(self.bufferRecived == u''):
print u"Odbieranie danych"
recivedText = Config.serial.read(Config.serial.inWaiting())
print recivedText
# if recivedText.find(
self.bufferRecived += recivedText
self.bufferRecived, isTerminator = self.searchTerminator(self.bufferRecived)
print repr(self.bufferRecived)
if isTerminator:
print u"Odebrano dane (znaleziono terminator)"
self.ui.o_recived_plainTextEdit.appendPlainText(self.bufferRecived)
if re.search(r'^ ?p<[0-2][0-9](:[0-5][0-9]){2}>!$', self.bufferRecived):
print u"Odebrano ping"
sendRecivePing = u"rp<%s>!" % (time.strftime('%X'))
print repr(sendRecivePing + self.treminatorTypes[self.myConfig.serialDict.get('terminator', 'CR')])
Config.serial.write(sendRecivePing + self.treminatorTypes[self.myConfig.serialDict.get('terminator', 'CR')])
print u"Wysłano ping zwrotny"
self.bufferRecived = u''
print u"Oczyszczono bufor odbioru danych"
@QtCore.pyqtSlot(str)
def terminatorChanged(self, itemName):
shouldShow = False
if itemName == u"własny":
shouldShow = True
self.ui.i_howMuchChars_spinBox.setVisible(shouldShow)
self.ui.i_itsTerminator_lineEdit.setVisible(shouldShow)
self.ui.customTermator.setVisible(shouldShow)
@QtCore.pyqtSlot()
def ping(self):
sendPing = u"p<%s>!" % (time.strftime('%X'))
Config.serial.write(sendPing + self.treminatorTypes[self.myConfig.serialDict.get('terminator', u'CR')])
print u"Wysłano ping"
@QtCore.pyqtSlot()
def send(self):
# if Config.serial.getDSR() or Config.serial.getCTS() or Config.serial.xonxoff:
# self.dtrRtsWrite(False)
terminator = self.treminatorTypes[self.myConfig.serialDict.get('terminator', 'CR')]
sendText = unicode(self.ui.lineEdit.text())
if self.myConfig.serialDict.get('automaticTerminator', True):
sendText += terminator
Config.serial.write(sendText)
sendText, isTerminator = self.searchTerminator(sendText)
self.ui.o_send_plainTextEdit.appendPlainText(sendText)
print u"Wysłano dane"
else:
sendText, isTerminator = self.searchTerminator(sendText)
self.sendTextBuffor += sendText
print u"Wysłano dane do bufora BRAK TERMINATORA"
if isTerminator:
self.ui.o_send_plainTextEdit.appendPlainText(self.sendTextBuffor)
Config.serial.write(self.sendTextBuffor + terminator)
self.sendTextBuffor = u''
print u"Terminator znaleziony, dane wysłane, bufor wysyłania oprózniony"
self.ui.lineEdit.clear()
# self.dtrRtsWrite(True)
def searchTerminator(self, text):
terminator = self.treminatorTypes[self.myConfig.serialDict.get('terminator', 'CR')]
if terminator in text:
indexFind = True
elif ("%s" % repr(terminator)[1:-1]) in text:
terminator = "%s" % repr(terminator)[1:-1]
terminator = repr(terminator)[1:-1]
indexFind = True
else:
indexFind = False
text = re.split(terminator, text)[0]
return (text, indexFind)
@QtCore.pyqtSlot()
def save(self):
if Config.serial.isOpen():
QtGui.QMessageBox.warning(None, u"RS-232", u"Należy zamknąć i otworzyć port, aby zmiany zostały wporawdzone.", \
buttons=QtGui.QMessageBox.Ok, defaultButton=QtGui.QMessageBox.NoButton)
for clear in self.protocolOptionDict.values():
self.myConfig.serialDict[clear] = False
if self.ui.i_protocol_comboBox.currentIndex() != 0:
self.myConfig.serialDict[self.protocolOptionDict[\
unicode(self.ui.i_protocol_comboBox.currentText())]] = True
self.myConfig.serialDict['port'] = str(self.ui.i_portName_comboBox.currentText())
self.myConfig.serialDict['baudrate'] = int(self.ui.i_baudRate_comboBox.currentText())
for byteSize in self.byteSizeList:
if(byteSize.isChecked()):
self.myConfig.serialDict['bytesize'] = int(byteSize.text())
for parity in self.paritiesList:
if(parity.isChecked()):
self.myConfig.serialDict['parity'] = Config.serial.PARITIES[self.paritiesList.index(parity)]
for stopBit in self.stopBitsList:
if(stopBit.isChecked()):
self.myConfig.serialDict['stopbits'] = int(stopBit.text())
if self.ui.i_timeout_spinBox.value():
self.myConfig.serialDict['timeout'] = self.ui.i_timeout_spinBox.value()
else:
self.myConfig.serialDict['timeout'] = None
self.myConfig.serialDict['automaticTerminator'] = self.ui.i_automaticTerminator_checkBox.isChecked()
self.myConfig.serialDict['terminator'] = unicode(self.ui.i_terminator_comboBox.currentText())
if unicode(self.ui.i_terminator_comboBox.currentText()) == u"własny":
self.myConfig.serialDict[u'itsTerminator'] = unicode(self.ui.i_itsTerminator_lineEdit.text())
self.treminatorTypes[u'własny'] = self.myConfig.serialDict['itsTerminator']
self.myConfig.save()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myApp = MyDialog()
myApp.show()
sys.exit(app.exec_())