Summary
将udpserver和Serial的对象进行包装,分别使用独立线程来维护。 实现的功能:
- UDP端接收的数据从串口发出,串口接收的数据从UDP端发出
SerialThreadBase.py
import serial
import serial.tools.list_ports
import threading
from queue import Queue
import time
class serialThreadBase(threading.Thread):
def __init__(self,name,serial:serial.Serial,inQueue:Queue,outQueue:Queue,interval:float) -> None:
super(serialThreadBase,self).__init__(daemon=True)
self.serial=serial
self.inQueue=inQueue
self.outQueue=outQueue
self.isRuning=False
self.name=name
self.interval=interval
def run(self) -> None:
print(self.name+' start.')
while(True):
time.sleep(self.interval)
try:
if self.serial.isOpen():
if self.inQueue is not None:
if not self.inQueue.empty():
buffer=self.inQueue.get()
if buffer is not None:
self.serial.write(buffer)
if self.serial.in_waiting:
readbuffer=self.serial.read_all()
if self.outQueue is not None:
if not self.outQueue.full():
self.outQueue.put(readbuffer)
else:
try:
self.serial.open()
except Exception as ex:
print(ex)
time.sleep(1)
except Exception as ex:
print(ex)
time.sleep(1)
self.serial.close()
udpServerThreadBase.py
import socket
import threading
from queue import Queue
import time
class udpServerThreadBase(threading.Thread):
def __init__(self,name,udpServer:socket.socket,listenPort:int,inQueue:Queue,outQueue:Queue,interval:float) -> None:
super().__init__(daemon=True)
self.name=name
self.udpServer=udpServer
self.inQueue=inQueue
self.outQueue=outQueue
self.interval=interval
self.client=None
self.port=listenPort
def run(self) -> None:
print(self.name+'start.')
try:
self.udpServer.bind((('0.0.0.0'),self.port))
self.udpServer.setblocking(0)
while(True):
time.sleep(self.interval)
try:
if self.client is not None:
if self.inQueue is not None:
if not self.inQueue.empty():
buffer=self.inQueue.get()
if buffer is not None:
self.udpServer.sendto(buffer,self.client)
message,self.client=self.udpServer.recvfrom(1024)
if message is not None:
if self.outQueue is not None:
if not self.outQueue.full():
self.outQueue.put(message)
except BlockingIOError:
pass
except BaseException as ex:
print(ex)
time.sleep(1)
main.py
from queue import Queue
import threading
import serial
import time
import socket
from serialThreadBase import serialThreadBase
from udpServerThreadBase import udpServerThreadBase
sendQueue=Queue()
recvQueue=Queue()
netSendQueue=Queue()
netRecvQueue=Queue()
def main():
global sendQueue,recvQueue
comSerial=serial.Serial()
comSerial.baudrate=115200
comSerial.setPort("COM21")
comThread=serialThreadBase('ComThread',comSerial,sendQueue,recvQueue,0.02)
comThread.start()
udpServer=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
udpThread=udpServerThreadBase('UdpThread',udpServer,10080,netSendQueue,netRecvQueue,0.02)
udpThread.start()
while(1):
if not netRecvQueue.empty():
sendQueue.put(netRecvQueue.get())
if not recvQueue.empty():
netSendQueue.put(recvQueue.get())
time.sleep(0.1)
if __name__=='__main__':
try:
main()
except KeyboardInterrupt:
pass
|