Switched mopidy backend from websockets to websocket-client

This commit is contained in:
Fabio Manganiello 2019-02-12 22:52:29 +01:00
parent b555777cc8
commit ee3df8fe8c
3 changed files with 120 additions and 100 deletions

View file

@ -1,4 +1,3 @@
import asyncio
import json
import queue
import re
@ -46,21 +45,7 @@ class MusicMopidyBackend(Backend):
self.url = 'ws://{}:{}/mopidy/ws'.format(host, port)
self._msg_id = 0
self._latest_status = self._get_tracklist_status()
async def _poll_events(self):
import websockets
try:
while not self.should_stop():
async with websockets.connect(self.url) as ws:
msg = await ws.recv()
if isinstance(msg, bytes):
msg = msg.decode()
self._handle_msg(msg)
except Exception as e:
self.logger.warning('The Mopidy backend raised an exception')
self.logger.exception(e)
time.sleep(2) # Wait a bit before retrying
self._ws = None
def _parse_track(self, track, pos=None):
if not track:
@ -90,7 +75,7 @@ class MusicMopidyBackend(Backend):
def _communicate(self, msg):
import websockets
import websocket
if isinstance(msg, str):
msg = json.loads(msg)
@ -99,21 +84,11 @@ class MusicMopidyBackend(Backend):
msg['jsonrpc'] = '2.0'
msg['id'] = self._msg_id
msg = json.dumps(msg)
resp_queue = queue.Queue()
async def get_response():
async with websockets.connect(self.url) as ws:
await ws.send(msg)
response = await ws.recv()
if isinstance(response, bytes):
response = response.decode()
resp_queue.put(json.loads(response))
ws = websocket.create_connection(self.url)
ws.send(msg)
return json.loads(ws.recv()).get('result')
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(get_response())
loop.stop()
return resp_queue.get().get('result')
def _get_tracklist_status(self):
return {
@ -127,7 +102,23 @@ class MusicMopidyBackend(Backend):
'method': 'core.tracklist.get_consume'}),
}
def _handle_msg(self, msg):
async def _poll_events(self):
import websocket
try:
while not self.should_stop():
async with websockets.connect(self.url) as ws:
msg = await ws.recv()
if isinstance(msg, bytes):
msg = msg.decode()
self._handle_msg(msg)
except Exception as e:
self.logger.warning('The Mopidy backend raised an exception')
self.logger.exception(e)
time.sleep(2) # Wait a bit before retrying
def _on_msg(self):
def hndl(msg):
msg = json.loads(msg)
event = msg.get('event')
if not event:
@ -198,16 +189,41 @@ class MusicMopidyBackend(Backend):
self._latest_status = new_status
return hndl
def _on_error(self):
def hndl(error):
self.logger.warning('Mopidy websocket error: {}'.format(error))
return hndl
def _on_close(self):
def hndl():
self._ws = None
self.logger.warning('Mopidy websocket connection closed')
time.sleep(5)
self._connect()
return hndl
def _on_open(self):
def hndl():
self.logger.info('Mopidy websocket connected')
return hndl
def _connect(self):
if not self._ws:
self._ws = websocket.WebSocketApp(self.url,
on_message=self._on_msg(),
on_error=self._on_error(),
on_close=self._on_close())
def run(self):
super().run()
self.logger.info('Started Mopidy events backend on {}:{}'.format(
self.host, self.port))
self.logger.info('Started tracking Mopidy events backend on {}:{}'.
format(self.host, self.port))
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
while not self.should_stop():
loop.run_until_complete(self._poll_events())
self._connect()
self._ws.on_open = self._on_open()
self._ws.run_forever()
# vim:sw=4:ts=4:et:

View file

@ -128,3 +128,6 @@ inputs
# git+https://github.com/agonzalezro/python-opensubtitles#egg=python-opensubtitles
# webvtt-py
# Mopidy backend
websocket-client

View file

@ -96,6 +96,7 @@ setup(
'Support for Chromecast plugin': ['pychromecast'],
'Support for sound devices': ['sounddevice', 'soundfile', 'numpy'],
'Support for web media subtitles': ['webvtt-py']
'Support for mopidy backend': ['websocket-client'],
# 'Support for Leap Motion backend': ['git+ssh://git@github.com:BlackLight/leap-sdk-python3.git'],
# 'Support for Flic buttons': ['git+https://@github.com/50ButtonsEach/fliclib-linux-hci.git']
# 'Support for media subtitles': ['git+https://github.com/agonzalezro/python-opensubtitles#egg=python-opensubtitles']