-
Notifications
You must be signed in to change notification settings - Fork 0
/
MySerial.py
67 lines (56 loc) · 1.81 KB
/
MySerial.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
#-*- coding: utf-8 -*-
import threading
from time import sleep
from PyQt4.QtCore import QObject, SIGNAL
from serial import Serial
class MySerial(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.qtobj = QObject()
self.__terminate = False
def open(self, settings):
try:
self.serial = Serial(settings["port"], settings["baund"], settings["bytesize"],
settings["parity"], settings["stopbits"], settings["timeout"])
self.serial.flushInput()
self.serial.flushOutput()
except Exception, msg:
return False, msg.message.decode("gbk")
return True, "success"
def resetArduino(self):
self.serial.setDTR(0)
sleep(0.1)
self.serial.setDTR(1)
def terminate(self):
self.__terminate = True
def send(self, data, _type):
self.serial.write(data)
def __recv(self):
data, quit = None, False
while 1:
if self.__terminate:
break
data = self.serial.read(1)
if data == '':
continue
while 1:
n = self.serial.inWaiting()
if n > 0:
data = "%s%s" % (data, self.serial.read(n))
sleep(0.02) # data is this interval will be merged
else:
quit = True
break
if quit:
break
return data
def close(self):
if self.serial.isOpen():
self.serial.close()
def run(self):
while 1:
data = self.__recv()
if not data:
break
self.qtobj.emit(SIGNAL("NewData"), data)
self.serial.close()