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

PySerial (last edited 2009-12-25 07:15:42 by localhost)