通过两个进程分别读写串口,并把发送与接收到的内容记录在blog中,收到q时程序结束并退出
import threading,time
import serial
import string


class SerThread:
    def __init__(self, Port=0):
        #初始化串口、blog文件名称
        self.my_serial = serial.Serial()
        self.my_serial.port=Port
        self.my_serial.baudrate = 9600
        self.my_serial.timeout = 1        
        self.alive = False
        self.waitEnd = None
        fname=time.strftime("%Y%m%d")#blog名称为当前时间
        self.rfname='r'+fname #接收blog名称
        self.sfname='s'+fname #发送blog名称
        self.thread_read= None
        self.thread_send=None      
             

    def waiting(self):
        # 等待event停止标志
        if not self.waitEnd is None:
            self.waitEnd.wait()

    def start(self):
        #开串口以及blog文件 
        self.rfile=open(self.rfname,'w')
        self.sfile=open(self.sfname,'w')
        self.my_serial.open()
             
        if self.my_serial.isOpen():
            self.waitEnd = threading.Event()
            self.alive = True
            
            self.thread_read = threading.Thread(target=self.Reader)
            self.thread_read.setDaemon(True)
            
            self.thread_send=threading.Thread(target=self.Sender)
            self.thread_send.setDaemon(True)
            
            self.thread_read.start()
            self.thread_send.start()
            return True
        else:
            return False

   
    def Reader(self):
        while self.alive:
            try:
                n=self.my_serial.inWaiting()
                data=''
                if n:
                    data= self.my_serial.read(n).decode('utf-8')             
                    print ('recv'+' '+time.strftime("%Y-%m-%d %X")+' '+data.strip())
                    print (time.strftime("%Y-%m-%d %X:")+data.strip(),file=self.rfile)
                    if len(data)==1 and ord(data[len(data)-1])==113: #收到字母q,程序退出
                        break
            except Exception as ex:
                print (ex)
               

        self.waitEnd.set()
        self.alive = False
    
    def Sender(self):
        while self.alive:
            try:
                snddata=input("input data:\n")
                self.my_serial.write(snddata.encode('utf-8'))
                print ('sent'+' '+ time.strftime("%Y-%m-%d %X"))
     print (snddata,file=self.sfile)  
                
            except Exception as ex:
                print (ex)
        
        self.waitEnd.set()
        self.alive = False                   
                
        

    def stop(self):
        self.alive = False
        #self.thread_read.join()
        #self.thread_send.join()
        if self.my_serial.isOpen():
            self.my_serial.close()
        self.rfile.close()
        self.sfile.close()
            

if __name__ == '__main__':    
    
    ser = SerThread('com4')
    try:
        if ser.start():
            ser.waiting()
            ser.stop()
        else:
            pass;            
    except Exception as ex:
        print (ex)

    if ser.alive:
        ser.stop()

    print ('End OK .');
    del ser; 

更多相关文章

  1. Python(名称空间、函数嵌套、函数对象)
  2. Python 3.4中的Pytesser:名称“image_to_string”没有定义?
  3. 获取网卡名称 linux c
  4. Linux 下串口编程之三 termios结构体介绍
  5. tty、串口、console等的区别
  6. Linux串口应用编程
  7. 如何利用SQL语句查询数据库中所有表的名称?
  8. 如果在两个模式中存在具有相似名称的删除表
  9. MS ACCESS jdbc.odbc连接。未找到数据源名称/未指定默认驱动程序

随机推荐

  1. 使用id替换存储在xml数据中的值
  2. 求助:请大侠帮我把下面的查询语句改写为可
  3. sql语句延时执行或者是指定时间执行
  4. 畅谈学习SQL Server后未来的路在哪
  5. 记录关于搭建mysql主从复制中遇见的问题
  6. Java数据持久层框架 MyBatis之API学习七(
  7. T-SQL中的随机数
  8. 我用的mysqlcc,我想看别人执行过哪些语句
  9. 今天看了一整天的汇编语言,真发现语言这东
  10. navicat+for+mysql破解版