- import sys,threading,time;
- import serial;
- import binascii,encodings;
- import re;
- import socket;
- from struct import *;
- class ComThread:
- def __init__(self, Port=1):
- self.l_serial = None;
- self.alive = False;
- self.waitEnd = None;
- self.port = Port;
- def waiting(self):
- if not self.waitEnd is None:
- self.waitEnd.wait();
- def SetStopEvent(self):
- if not self.waitEnd is None:
- self.waitEnd.set();
- self.alive = False;
- self.stop();
- def start(self):
- self.l_serial = serial.Serial();
- self.l_serial.port = self.port;
- self.l_serial.baudrate = 9600;
- self.l_serial.timeout = 2;
- self.l_serial.open();
- if self.l_serial.isOpen():
- self.waitEnd = threading.Event();
- self.alive = True;
- self.thread_read = None;
- self.thread_read = threading.Thread(target=self.FirstReader);
- self.thread_read.setDaemon(1);
- self.thread_read.start();
- return True;
- else:
- return False;
- def FirstReader(self):
- print "waiting data"
- while self.alive:
- time.sleep(0.01);
- try:
- data = '';
- n = self.l_serial.inWaiting();
- if n:
- data = data + self.l_serial.read(n);
- #for l in xrange(len(data)):
- # print '%02X' % ord(data[l]),
- #snddata = '';
- #snddata += chr(97)
- #tt = 0x12345678;
- #snddata += pack('i', tt)
- #snddata += chr(0x64)
- #print snddata;
- #self.l_serial.write(snddata);
- snddata= pack('i', 0x12345600)
- snddata+= pack('B', 0x11)
- self.l_serial.write(snddata);
- if len(data) > 0 and ord(data[len(data)-1])==0x0a:
- #pass;
- break;
- except Exception, ex:
- print str(ex);
- self.waitEnd.set();
- self.alive = False;
- def stop(self):
- self.alive = False;
- self.thread_read.join();
- if self.l_serial.isOpen():
- self.l_serial.close();
- #
- if __name__ == '__main__':
- rt = ComThread();
- try:
- if rt.start():
- rt.waiting();
- rt.stop();
- else:
- pass;
- except Exception,se:
- print str(se);
- if rt.alive:
- rt.stop();
- print '';
- print 'End OK .';
- del rt;
python实现串口通信 要导入serial的包 而且刚开始在等待接受收到0x45退出
最新推荐文章于 2024-05-25 22:34:53 发布