__new__实现的串口单例,查了很多单例格式,都只有框架怎么用的案例没有,学习了一下做记录,如果有问题欢迎来拍砖。
import sys
import serial
import serial.tools.list_ports
import threading
import time
class SerialComm(object):
_instance_lock = threading.Lock()
def __new__(cls,commport,
baudrate,
bytesize=8,
parity=serial.PARITY_NONE,
stopbit=1,
timeout=5):
if not hasattr(SerialComm,"_instance"):
with SerialComm._instance_lock:
if not hasattr(SerialComm,"_instance"):
SerialComm._instance = CommFunc(commport, baudrate, bytesize, parity, stopbit, timeout)
return SerialComm._instance
class CommFunc(object):
def __init__(self,commport,baudrate,bytesize=8,
parity=serial.PARITY_NONE,stopbit=1,timeout=5):
self.bAsynRecv = False
self.bStartRecv = False
self.recvThd = None
self.comm = \
serial.Serial(commport, baudrate, bytesize, parity, stopbit, timeout)
@staticmethod
def getPortList():
nameList = []
infoList = list(serial.tools.list_ports.comports())
if len(infoList) > 0:
for i in range(len(infoList)):
tmpList = list(infoList[i])
nameList.append(tmpList[0])
return nameList
def setAsynRecv(self, callBackFunc):
self.bAsynRecv = True
self.bStartRecv = True
self.callFunc = callBackFunc
self.recvThd = threading.Thread(target=self.recvThread,daemon=True)
self.recvThd.start()
def openComm(self):
if self.comm.isOpen():
return True
else:
self.comm.open()
if self.comm.isOpen():
return True
else:
return False
def modifyComm(self, baudrate=115200,bytesize=8,parity=serial.PARITY_NONE,
stopbit=1, timeout=5, bAsnyRecv=True):
commName = self.comm.port()
bAsynRecv = self.bAsynRecv
self.closeComm()
self.comm = serial.Serial(commName,baudrate,bytesize,
parity,stopbit,timeout)
self.openComm()
if bAsnyRecv:
self.setAsynRecv()
def closeComm(self):
if self.bStartRecv:
self.bStartRecv = False
time.sleep(5)
if self.comm.isOpen():
self.comm.close()
return
def sendData(self, data):
len = self.comm.write(data)
return len
def recvData(self):
return self.comm.readall()
def recvThread(self):
while self.bStartRecv:
content = self.recvData()
if self.callFunc is not None:
self.callFunc(content)
print(content)
if __name__ == "__main__":
portList = CommFunc.getPortList()
print(portList[0],len(portList))
comm = SerialComm("COM3",baudrate=115200)
comm.openComm()
comm.setAsynRecv(None)
time.sleep(6)
comm.closeComm()