Skip to content

Commit

Permalink
mavutil: WebSockets: fix wsproto import for newer python versions
Browse files Browse the repository at this point in the history
  • Loading branch information
IamPete1 committed Sep 7, 2024
1 parent 50a291a commit f8d038e
Showing 1 changed file with 21 additions and 14 deletions.
35 changes: 21 additions & 14 deletions mavutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -1738,13 +1738,8 @@ def write(self, buf):
class mavwebsocket(mavfile):
'''Mavlink WebSocket server, single client only'''
def __init__(self, device, source_system=255, source_component=0, use_native=default_native):
from wsproto import ConnectionType, WSConnection, utilities
from wsproto.events import (
AcceptConnection,
CloseConnection,
Request,
BytesMessage,
)
# Try importing wsproto, we don't need it here but it means we fail early if its missing
import wsproto

self.ws = None

Expand Down Expand Up @@ -1775,6 +1770,14 @@ def close(self):
self.listen.close()

def recv(self,n=None):
from wsproto import ConnectionType, WSConnection, utilities
from wsproto.events import (
AcceptConnection,
CloseConnection,
Request,
BytesMessage,
)

# Based on: https://github.com/python-hyper/wsproto/blob/main/example/synchronous_server.py
if not self.port:
try:
Expand All @@ -1787,7 +1790,7 @@ def recv(self,n=None):
self.fd = self.port.fileno()

# Start server
self.ws = self.WSConnection(self.ConnectionType.SERVER)
self.ws = WSConnection(ConnectionType.SERVER)

if not self.ws:
# Should probbily raise a exception of some sort
Expand All @@ -1803,7 +1806,7 @@ def recv(self,n=None):
return ''
self.close_port()
return ''
except self.utilities.RemoteProtocolError:
except utilities.RemoteProtocolError:
self.close_port()
return ''

Expand All @@ -1812,16 +1815,16 @@ def recv(self,n=None):
reply = b""
keep_running = True
for event in self.ws.events():
if isinstance(event, self.Request):
if isinstance(event, Request):
# Negotiate new WebSocket connection
reply += self.ws.send(self.AcceptConnection())
reply += self.ws.send(AcceptConnection())

elif isinstance(event, self.CloseConnection):
elif isinstance(event, CloseConnection):
# Request to close
reply += self.ws.send(event.response())
keep_running = False

elif isinstance(event, self.BytesMessage):
elif isinstance(event, BytesMessage):
# Some actual MAVLink data
data += event.data

Expand All @@ -1839,8 +1842,12 @@ def write(self, buf):
if self.port is None or self.ws is None:
return

from wsproto.events import (
BytesMessage,
)

# Pack buf into WebSocket binary message
packed = self.ws.send(self.BytesMessage(data = buf))
packed = self.ws.send(BytesMessage(data = buf))

try:
self.port.send(packed)
Expand Down

0 comments on commit f8d038e

Please sign in to comment.