Bluetoothデバイスと通信するために、Twistedを使用してpythonプログラムを実装しようとしています。以下は、私が実装したサンプルコードです。
from twisted.internet import protocol, reactor
from twisted.internet.serialport import SerialPort
from twisted.protocols import basic
class DeviceBluetooth(basic.Int16StringReceiver):
def connectionMade(self):
print 'Connection made!'
self.sendString('[01] help\n')
def dataReceived(self, data):
print"Response: {0}".format(data)
print "-----"
print "choose message to send: "
print "1. Stim on"
print "2. Stim off"
print "3. Stim status"
print "4. Help"
# user input
ch = input("Choose command :: ")
if int(ch) == 1:
self.sendString('[02] stim on\n')
elif int(ch) == 2:
self.sendString('[03] stim off\n')
elif int(ch) == 3:
self.sendString('[04] stim ?\n')
elif int(ch) == 4:
self.sendString('[05] help\n')
else:
reactor.stop()
SerialPort(DeviceBluetooth(), 'COM20', reactor, baudrate=115200)
reactor.run()
プログラムを実行すると、応答が返されることもあれば、何も受信されないこともあります。ほとんどの場合、長い応答は断片化されており、次のメッセージの一部として表示されます。ハイパーターミナルを介して、Bluetooth デバイスから適切な応答が得られることを確認します。したがって、問題は私のコードにあるはずです。
私のコードで間違っていることがありますか?
追加修正・訂正
上記のコードの dataReceived() 関数を stringReceived() に置き換えると、プログラムはこの関数に入りません。
また、次のように、LineReceiver プロトコルを使用して上記のプログラムを作成しようとしました。
from twisted.internet import protocol, reactor
from twisted.internet.serialport import SerialPort
from twisted.protocols import basic
class DeviceBluetooth(basic.LineReceiver):
def connectionMade(self):
print 'Connection made!'
self.sendLine('[01] help')
def dataReceived(self, data):
print"Response: {0}".format(data)
print "-----"
print "choose message to send: "
print "1. Stim on"
print "2. Stim off"
print "3. Stim status"
print "4. Help"
# user input
ch = input("Choose command :: ")
if int(ch) == 1:
self.sendLine('[02] stim on')
elif int(ch) == 2:
self.sendLine('[03] stim off')
elif int(ch) == 3:
self.sendLine('[04] stim ?')
elif int(ch) == 4:
self.sendLine('[05] help')
else:
reactor.stop()
SerialPort(DeviceBluetooth(), 'COM20', reactor, baudrate=115200)
reactor.run()
dataReceived 関数からの断片化されたデータで、以前と同じ問題があります。