2016-11-18 83 views
1

所以我想與連接到通過使用AT串行端口的ZigBee模塊進行通信讀取(有時refered海耶斯)命令。問題,同時與pyserial

我的問題是我無法弄清楚如何正確使用Python的pyserial模塊(我使用Python 2.7的嵌入式設備)讀取它的答案。

有時腳本管理完美讀取模塊的響應,有時它只是返回了一套「A」字符。

下面是一個示例輸出:

打開串口的/ dev/ttyS2 ... 的/ dev/ttyS2是開放...

輸入命令或 '退出':AT

------------- -------------響應

AT OK

輸入命令或 '退出':ATI

------------- -------------響應 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaAaAaaaAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

輸入命令或「退出':

我真的不明白這裏發生了什麼,但我想可能是因爲我用的是pyserial模塊不正確。我已經嘗試使用inWaiting()命令來只讀取輸入緩衝區中包含的字節,但該函數始終返回零,並且readline()命令似乎不工作,所以我只讀取1024字節的數據包。

這裏是我到目前爲止已經編寫的代碼:

import serial, time, os 

def sendAtCommand(command): 

    # responseArray = [] 
    # i = 0 

    try: 
     # print('Number of bytes waiting in input buffer before write : '+str(ser.inWaiting())) -> always zero... 

     if ser.inWaiting(): 
      # flush input buffer, discarding all its contents 
      print('flushing input buffer ...') 
      ser.flushInput() 
      # flush output buffer, aborting current output 
      # ser.flushOutput() 

     try: 
      ser.write(command.encode('ascii')+'\r') 
      #ser.write(command+'\r') 
      #time.sleep(5) 
     except SerialTimeoutException as e: 
      print(repr(e)) 

     response = ser.read(size=1024) 
     # print('Number of bytes waiting in input buffer after write : '+str(ser.inWaiting())) -> always zero 
     # while ser.inWaiting(): 
      # print('Reading response ... '+str(i)) 
      # responseArray.append(ser.readline(eol='\r\n')) 
      # i += 1 
      # time.sleep(0.2) 

     print('------------------------------------') 
     print('------------- Response -------------') 
     print('------------------------------------') 
     print(response) 
     # for line in responseArray: 
      # print(line)   
     print('------------------------------------') 

     time.sleep(1) 

    except KeyboardInterrupt as e: 
     print('Closing serial '+port+' before interrupting ...') 
     ser.close() 
     exit() 

VERSION = '0.02' 
firstStart = True 

port = '/dev/ttyS2' 
baudrate = 19200 
bytesize = 8 
parity = 'N' 
stopbits = 1 
timeout = 1 
xonxoff = False 
rtscts = False 
dsrdtr = False 
write_timeout = None 
inter_byte_timeout = None 

try: 
    os.system('cls' if os.name == 'nt' else 'clear') 
    print('') 
    print('PySerial version : '+serial.VERSION) 
    firstStart = False 

    print('') 
    print('Opening serial '+port+' ...') 
    ser = serial.Serial(port, baudrate, bytesize, parity, stopbits, timeout, 
    xonxoff, rtscts, write_timeout, dsrdtr, inter_byte_timeout) 
except ValueError as e: 
    print(repr(e)) 
except SerialException as e: 
    print(repr(e)) 

if ser.isOpen(): 
    print(ser.name + ' is open...') 
    print('') 

while True: 

    try: 
     cmd = raw_input('Enter command or \'exit\' : ') 

     if cmd == 'exit': 
      ser.close() 
      exit() 
     else: 
      sendAtCommand(cmd) 
    except KeyboardInterrupt as e: 
     print('Closing serial '+port+' before interrupting ...') 
     ser.close() 
     exit() 
+0

您是否嘗試過控制用串口終端設備程序像minicom(或屏幕)通過直接輸入命令發送命令,並直接顯示zignee設備響應?這將有助於確定問題是您的程序,串行端口設置還是設備(或組合)。 – barny

+0

欲瞭解更多詳情,請參閱http://unix.stackexchange.com/questions/22545/how-to-connect-to-a-serial-port-as-simple-as-using-ssh – barny

+1

看起來像一個比特率和/或stopbit-mismatch。 – Olaf

回答

0

好了,所以先謝謝大家的答案。最後我想出瞭如何解決這個問題。

我不知道爲什麼,但問題是我使用它的UART vcc引腳(連接到Linkit 7688 3v3引腳)爲telegesis zigbee板供電。現在

,我只是連接這兩個板的GND,Tx和Rx和使用電力的外部源,它完美的作品。如果您對同一材料有同樣的問題,請參考下面的圖片。

請勿使用裝入紅色的VCC引腳,必須通過x2插座使用外部電源爲主板供電。

(對不起所有,我的英語質量差)

Telegesis ETRX357-DVK development kit

編輯:

啊,現在我再也不會讀的1024個字節的數據包隨機,我用的是單獨的線程如下所示:

class readSerial(Thread): 
    """This thread waits for data in the serial input buffer""" 
    """This is a new subclass of the Thread class (cf. Python 2.4+ threading module"""  

    def __init__(self, serialObject): 
     """Overrides the __init__(self [,args]) method to add additional arguments""" 
     Thread.__init__(self) 
     self.serialObject = serialObject 
     self.daemon = True 
     self.start() 

    def run(self): 

     ser = self.serialObject 

     data = '' 

     ser.reset_input_buffer() 
     ser.reset_output_buffer() 

     while True: 
      try: 
       if ser.in_waiting > 0: 
        data = ser.read(ser.in_waiting) 

        print('msg received : ') 
        print('') 
        print(data.decode('ascii')) 

       if 'UCAST' in data.decode('ascii'): 
        zigbeeRequest(data.decode('ascii')[26:], ser) 

        ser.reset_input_buffer() 

        data = '' 
       if 'BCAST' in data.decode('ascii'): 
        zigbeeRequest(data.decode('ascii')[26:], ser) 

        ser.reset_input_buffer() 

        data = '' 

       time.sleep(1)      
      except Exception as e: 
       print(repr(e)) 

然後只要把

readThread = readSerial(ser) 

在您的主程序中打開串口連接後。

我希望即使我清楚地知道它並不完美編程這可能是有用的人(不捕捉異常像我這樣做...)