我打算使用Twisted實現一個Python程序來與藍牙設備進行通信。下面是什麼我實現了一個示例代碼:扭曲的串行端口dataReceived()提供零碎的數據
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()
當我運行程序時,有時我得到的迴應,其他時間我沒有收到任何東西。而且大多數時候,很長一段時間的回覆都是碎片化的,作爲下一條消息的一部分。我已經通過超級終端來確保我通過藍牙設備獲得適當的響應。所以,這個問題必須與我的代碼。
有沒有什麼我在我的代碼中做錯了?
附加修改/校正
當我替換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功能分段的數據。
我用stringReceived替換了thye的dataReceived函數,並運行了代碼。但是當我這樣做時,程序甚至不會輸入stringReceived函數。 我也嘗試了LineReceived protcol的上述程序的修改版本,在這裏我也遇到了dataReceived函數中碎片數據的相同問題。 – siva82kb
你爲什麼要在Int16StringReceiver和LineReceiver之間切換?你想在這裏說什麼協議? –
我試過LineReceiver協議,只是想看看它是否工作。來自藍牙設備的協議被實現爲基於線路的協議。我是Twisted的新手,所以嘗試了不同的東西。 – siva82kb