Goal is to send serial "payload" to a non-local server (static IP) using a websocket and fired each time there's new serial data from a serial device connected to a local machine (where this code runs). The following code does receive serial data...and it creates a websocket with the remote server. I can't trigger a sendmessage from the SerialDevice Class, as it breaks when I uncomment the line in class SerialDevice "BroadcastClientProtocol().sendPayload(payload)"
Here is the unhandled error: [...] if self.state != WebSocketProtocol.STATE_OPEN: exceptions.AttributeError:BroadcastClientProtocol instance has no attribute 'state'
From within SerialDevice Class, I can call a test inherited method BroadcastClientProtocol().testInheritanceMethod().
Here's the code adapted from 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()