目标是使用websocket将串行“有效负载”发送到非本地服务器(静态IP),并在每次从连接到本地计算机的串行设备(运行此代码)的新串行数据时触发。以下代码确实接收串行数据......并且它使用远程服务器创建websocket。我无法从SerialDevice类触发sendmessage,因为当我取消注释SerialDevice类中的行“BroadcastClientProtocol()。sendPayload(payload)”
这是未处理的错误: [...] if self.state!= WebSocketProtocol.STATE_OPEN: exceptions.AttributeError:BroadcastClientProtocol实例没有属性'state'
在SerialDevice Class中,我可以调用一个测试继承的方法BroadcastClientProtocol()。testInheritanceMethod()。
以下是改编自autobahn websocket / broadcast client.py
的代码from twisted.internet import reactor
from autobahn.twisted.websocket import WebSocketClientFactory, \
WebSocketClientProtocol, \
connectWS
from twisted.internet.serialport import SerialPort
from twisted.protocols.basic import LineReceiver
COM_PORT='/dev/ttyUSB0'
BAUD_RATE=115200
import sys
from twisted.internet import reactor
from autobahn.twisted.websocket import WebSocketClientFactory, \
WebSocketClientProtocol, \
connectWS
from twisted.internet.serialport import SerialPort
from twisted.protocols.basic import LineReceiver
COM_PORT='/dev/ttyUSB0'
BAUD_RATE=115200
class SerialDevice(LineReceiver):
def __init__(self, network):
pass
def lineReceived(self, payload):
print "receive:", payload
#the call to the inherited method testInheritanceMethod() works
BroadcastClientProtocol().testInheritanceMethod()
#the call to the inherited method sendPayload() fails
#BroadcastClientProtocol().sendPayload(payload)
class BroadcastClientProtocol(WebSocketClientProtocol):
"""
Simple client that connects to a WebSocket server, send a HELLO
message every 2 seconds and print everything it receives.
"""
def testInheritanceMethod(self):
print("inherited method called OK")
def sendHello(self):
self.sendMessage("Hello from Python!".encode('utf8'))
reactor.callLater(2, self.sendHello)
def sendPayload(self, data):
self.sendMessage(data.encode('utf8'))
def onOpen(self):
self.sendHello()
def onMessage(self, payload, isBinary):
if not isBinary:
print("Text message received: {}".format(payload.decode('utf8')))
if __name__ == '__main__':
if len(sys.argv) < 2:
print("Need the WebSocket server address, i.e. ws://localhost:9000")
sys.exit(1)
factory = WebSocketClientFactory(sys.argv[1])
factory.protocol = BroadcastClientProtocol
connectWS(factory)
SerialPort(SerialDevice(BroadcastClientProtocol), COM_PORT, reactor, baudrate=BAUD_RATE)
reactor.run()