Python中文资料收编Python 串口通信开发 ::-- ZoomQuiet [2006-09-05 06:47:10]

CPUG联盟::

CPUG::门户plone

BPUG

SPUG

ZPUG

SpreadPython Python宣传

1. Python 串口设备应用

简述

1.1. 线程轮寻

风尘无限 <tianyu263@163.com>

-- 分享

就是打开串口后,启动一个线程来监听串口数据的进入,有数据时,就做数据的处理(也可以发送一个事件,并携带接收到的数据)。

   1 
   2 #coding=gb18030
   3 
   4 import sys,threading,time;
   5 import serial;
   6 import binascii,encodings;
   7 import re;
   8 import socket;
   9 
  10 class ReadThread:
  11    def __init__(self, Output=None, Port=0, Log=None, i_FirstMethod=True):
  12        self.l_serial = None;
  13        self.alive = False;
  14        self.waitEnd = None;
  15        self.bFirstMethod = i_FirstMethod;
  16        self.sendport = '';
  17        self.log = Log;
  18        self.output = Output;
  19        self.port = Port;
  20        self.re_num = None;
  21 
  22    def waiting(self):
  23        if not self.waitEnd is None:
  24            self.waitEnd.wait();
  25 
  26    def SetStopEvent(self):
  27        if not self.waitEnd is None:
  28            self.waitEnd.set();
  29        self.alive = False;
  30        self.stop();
  31 
  32    def start(self):
  33        self.l_serial = serial.Serial();
  34        self.l_serial.port = self.port;
  35        self.l_serial.baudrate = 9600;
  36        self.l_serial.timeout = 2;
  37 
  38        self.re_num = re.compile('\d');
  39 
  40        try:
  41            if not self.output is None:
  42                self.output.WriteText(u'打开通讯端口\r\n');
  43            if not self.log is None:
  44                self.log.info(u'打开通讯端口');
  45            self.l_serial.open();
  46        except Exception, ex:
  47            if self.l_serial.isOpen():
  48                self.l_serial.close();
  49 
  50            self.l_serial = None;
  51 
  52            if not self.output is None:
  53                self.output.WriteText(u'出错:\r\n    %s\r\n' % ex);
  54            if not self.log is None:
  55                self.log.error(u'%s' % ex);
  56            return False;
  57 
  58        if self.l_serial.isOpen():
  59            if not self.output is None:
  60                self.output.WriteText(u'创建接收任务\r\n');
  61            if not self.log is None:
  62                self.log.info(u'创建接收任务');
  63            self.waitEnd = threading.Event();
  64            self.alive = True;
  65            self.thread_read = None;
  66            self.thread_read = threading.Thread(target=self.FirstReader);
  67            self.thread_read.setDaemon(1);
  68            self.thread_read.start();
  69            return True;
  70        else:
  71            if not self.output is None:
  72                self.output.WriteText(u'通讯端口未打开\r\n');
  73            if not self.log is None:
  74                self.log.info(u'通讯端口未打开');
  75            return False;
  76 
  77    def InitHead(self):
  78                #串口的其它的一些处理
  79        try:
  80            time.sleep(3);
  81            if not self.output is None:
  82                self.output.WriteText(u'数据接收任务开始连接网络\r\n');
  83            if not self.log is None:
  84                self.log.info(u'数据接收任务开始连接网络');
  85            self.l_serial.flushInput();
  86            self.l_serial.write('\x11');
  87            data1 = self.l_serial.read(1024);
  88        except ValueError,ex:
  89            if not self.output is None:
  90                self.output.WriteText(u'出错:\r\n    %s\r\n' % ex);
  91            if not self.log is None:
  92                self.log.error(u'%s' % ex);
  93            self.SetStopEvent();
  94            return;
  95 
  96        if not self.output is None:
  97            self.output.WriteText(u'开始接收数据\r\n');
  98        if not self.log is None:
  99            self.log.info(u'开始接收数据');
 100            self.output.WriteText(u'===================================\r\n');
 101 
 102    def SendData(self, i_msg):
 103        lmsg = '';
 104        isOK = False;
 105        if isinstance(i_msg, unicode):
 106            lmsg = i_msg.encode('gb18030');
 107        else:
 108            lmsg = i_msg;
 109        try:
 110           #发送数据到相应的处理组件
 111            pass
 112        except Exception, ex:
 113            pass;
 114        return isOK;
 115 
 116    def FirstReader(self):
 117        data1 = '';
 118        isQuanJiao = True;
 119        isFirstMethod = True;
 120        isEnd = True;
 121        readCount = 0;
 122        saveCount = 0;
 123        RepPos = 0;
 124        #read Head Infor content
 125        self.InitHead();
 126 
 127        while self.alive:
 128            try:
 129                data = '';
 130                n = self.l_serial.inWaiting();
 131                if n:
 132                    data = data + self.l_serial.read(n);
 133                    #print binascii.b2a_hex(data),
 134 
 135                for l in xrange(len(data)):
 136                    if ord(data[l])==0x8E:
 137                        isQuanJiao = True;
 138                        continue;
 139                    if ord(data[l])==0x8F:
 140                        isQuanJiao = False;
 141                        continue;
 142                    if ord(data[l]) == 0x80 or ord(data[l]) == 0x00:
 143                        if len(data1)>10:
 144                            if not self.re_num.search(data1,1) is None:
 145                                saveCount = saveCount + 1;
 146                                if RepPos==0:
 147                                    RepPos = self.output.GetInsertionPoint();
 148                                self.output.Remove(RepPos,self.output.GetLastPosition());
 149 
 150                                self.SendData(data1);
 151                        data1 = '';
 152                        continue;
 153            except Exception, ex:
 154                if not self.log is None:
 155                    self.log.error(u'%s' % ex);
 156 
 157        self.waitEnd.set();
 158        self.alive = False;
 159 
 160    def stop(self):
 161        self.alive = False;
 162        self.thread_read.join();
 163        if self.l_serial.isOpen():
 164            self.l_serial.close();
 165            if not self.output is None:
 166                self.output.WriteText(u'关闭通迅端口:[%d] \r\n' % self.port);
 167            if not self.log is None:
 168                self.log.info(u'关闭通迅端口:[%d]' % self.port);
 169 
 170    def printHex(self, s):
 171        s1 = binascii.b2a_hex(s);
 172        print s1;
 173 
 174 #测试用部分
 175 if __name__ == '__main__':
 176    rt = ReadThread();
 177    f = open("sendport.cfg", "r")
 178    rt.sendport = f.read()
 179    f.close()
 180    try:
 181        if rt.start():
 182            rt.waiting();
 183            rt.stop();
 184        else:
 185            pass;
 186    except Exception,se:
 187        print str(se);
 188 
 189    if rt.alive:
 190        rt.stop();
 191 
 192    print 'End OK .';
 193    del rt;

2. 反馈

ghostwwl -- 补充一点点 那个串口的pyserial模块到http://sourceforge.net/project/showfiles.php?group_id=46487去下 不然会no model named .....

Border -- 从 http://pyserial.cvs.sourceforge.net/pyserial/pyserial/ 得到些例子。