3

pyserial を使用してシリアル モデムと通信する方法の適切な例が見つかりませんでした。インスタンス化された pyserial オブジェクトを指定して、次のことを行うコード スニペットを作成しましたser

  • AT コマンドをモデムに送信する
  • できるだけ早くモデムの応答を返します
  • タイムアウトの場合は None などを返します
  • スクリプトとモデムの間の通信を最も合理的で堅牢かつ簡単に処理します。

スニペットは次のとおりです。

def send(cmd, timeout=2):

  # flush all output data
  ser.flushOutput()

  # initialize the timer for timeout
  t0 = time.time()
  dt = 0

  # send the command to the serial port
  ser.write(cmd+'\r')

  # wait until answer within the alotted time
  while ser.inWaiting()==0 and time.time()-t0<timeout:
    pass

  n = ser.inWaiting()
  if n>0:
    return ser.read(n)
  else:
    return None

私の質問: これは優れた堅牢なコードですか、それとも一部を変更/簡素化できますか? 私は特にこのメソッドが好きではありませんread(n).pyserialがバッファの内容全体を返すだけのコードを提供することを期待しています. また、前に出力バッファにがらくたが入るのを避けるために、最初に出力をフラッシュする必要がありますか?

ありがとうアレックス

4

1 に答える 1

1

timeout=2読み取りタイムアウトのパラメーターを使用して Serial オブジェクトを作成します。

ミのレシピは次のとおりです。

def send(data):
    try:
        ser.write(data)
    except Exception as e:
        print "Couldn't send data to serial port: %s" % str(e)
    else:
        try:
            data = ser.read(1)
        except Exception as e:
            print "Couldn't read data from serial port: %s" % str(e)
        else:
            if data:  # If data = None, timeout occurr
                n = ser.inWaiting()
                if n > 0: data += ser.read(n)
                return data

これはシリアルポートとの通信を管理する良い形だと思います。

于 2013-03-24T17:31:39.773 に答える