pax_global_header00006660000000000000000000000064145753077560014535gustar00rootroot0000000000000052 comment=aa14561f57abdc740aab9d868eae3be80b834b04 happyleavesaoc-python-snapcast-aa14561/000077500000000000000000000000001457530775600202165ustar00rootroot00000000000000happyleavesaoc-python-snapcast-aa14561/.gitignore000066400000000000000000000000701457530775600222030ustar00rootroot00000000000000snapcast.egg-info* *.pyc .cache .coverage .tox MANIFEST happyleavesaoc-python-snapcast-aa14561/.travis.yml000066400000000000000000000001631457530775600223270ustar00rootroot00000000000000cache: directories: - $HOME/.cache/pip language: python python: "3.5" install: "pip install tox" script: tox happyleavesaoc-python-snapcast-aa14561/LICENSE000066400000000000000000000020711457530775600212230ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2015 happyleavesaoc Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. happyleavesaoc-python-snapcast-aa14561/Makefile000066400000000000000000000001751457530775600216610ustar00rootroot00000000000000all: .PHONY: dist update dist: rm -f dist/*.whl dist/*.tar.gz python setup.py sdist release: twine upload dist/*.tar.gz happyleavesaoc-python-snapcast-aa14561/README.md000066400000000000000000000032451457530775600215010ustar00rootroot00000000000000[![Build Status](https://travis-ci.org/happyleavesaoc/python-snapcast.svg?branch=master)](https://travis-ci.org/happyleavesaoc/python-snapcast) [![PyPI version](https://badge.fury.io/py/snapcast.svg)](https://badge.fury.io/py/snapcast) # python-snapcast Control [Snapcast](https://github.com/badaix/snapcast) in Python 3. Reads client configurations, updates clients, and receives updates from other controllers. Supports Snapcast `0.15.0`. ## Install `pip install snapcast` ## Usage ### Control ```python import asyncio import snapcast.control loop = asyncio.get_event_loop() server = loop.run_until_complete(snapcast.control.create_server(loop, 'localhost')) # print all client names for client in server.clients: print(client.friendly_name) # set volume for client #0 to 50% client = server.clients[0] loop.run_until_complete(server.client_volume(client.identifier, {'percent': 50, 'muted': False})) # create background task (polling) async def testloop(): while(1): print("still running") #print(json.dumps(server.streams[0].properties, indent=4)) print(server.groups) await asyncio.sleep(10) test = loop.create_task(testloop()) # add callback for client #0 volume change def my_update_func(client): print(client.volume) server.clients[0].set_callback(my_update_func) # keep loop running to receive callbacks and to keep background task alive loop.run_forever() ``` ### Client Note: This is experimental. Synchronization is not yet supported. Requires GStreamer 1.0. ```python import snapcast.client client = snapcast.client.Client('localhost', snapcast.client.SERVER_PORT) client.register() client.request_start() # this blocks ``` happyleavesaoc-python-snapcast-aa14561/pylintrc000066400000000000000000000001111457530775600217760ustar00rootroot00000000000000[MASTER] reports=no disable=I [MESSAGES CONTROL] disable=duplicate-code happyleavesaoc-python-snapcast-aa14561/setup.cfg000066400000000000000000000000501457530775600220320ustar00rootroot00000000000000[metadata] description-file = README.md happyleavesaoc-python-snapcast-aa14561/setup.py000066400000000000000000000011071457530775600217270ustar00rootroot00000000000000from setuptools import setup setup( name='snapcast', version='2.3.6', description='Control Snapcast.', url='https://github.com/happyleavesaoc/python-snapcast/', license='MIT', author='happyleaves', author_email='happyleaves.tfr@gmail.com', packages=['snapcast', 'snapcast.control', 'snapcast.client'], install_requires=[ 'construct>=2.5.2', 'packaging', ], classifiers=[ 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', ] ) happyleavesaoc-python-snapcast-aa14561/snapcast/000077500000000000000000000000001457530775600220325ustar00rootroot00000000000000happyleavesaoc-python-snapcast-aa14561/snapcast/__init__.py000066400000000000000000000000001457530775600241310ustar00rootroot00000000000000happyleavesaoc-python-snapcast-aa14561/snapcast/client/000077500000000000000000000000001457530775600233105ustar00rootroot00000000000000happyleavesaoc-python-snapcast-aa14561/snapcast/client/__init__.py000066400000000000000000000074601457530775600254300ustar00rootroot00000000000000""" Snapcast Client. """ import logging import queue import socket import threading import time from snapcast.client.messages import (hello_packet, request_packet, command_packet, packet, basemessage, BASE_SIZE) from snapcast.client.gstreamer import GstreamerAppSrc __version__ = '0.0.1-py' SERVER_PORT = 1704 SYNC_AFTER = 1 BUFFER_SIZE = 30 CMD_START_STREAM = 'startStream' MSG_SERVER_SETTINGS = 'ServerSettings' MSG_SAMPLE_FORMAT = 'SampleFormat' MSG_WIRE_CHUNK = 'WireChunk' MSG_HEADER = 'Header' MSG_TIME = 'Time' _LOGGER = logging.getLogger(__name__) def mac(): """ Get MAC. """ from uuid import getnode as get_mac return ':'.join(("%012x" % get_mac())[i:i+2] for i in range(0, 12, 2)) class Client: """ Snapcast Client. """ def __init__(self, host, port): """ Setup. """ self._queue = queue.Queue() self._buffer = queue.Queue() self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._socket.connect((host, port)) self._source = GstreamerAppSrc() self._last_sync = time.time() self._connected = False self._buffered = False threading.Thread(target=self._read_socket, daemon=True).start() threading.Thread(target=self._write_socket, daemon=True).start() threading.Thread(target=self._play, daemon=True).start() _LOGGER.info('Connected to %s:%s', host, port) def register(self): """ Transact with server. """ self._queue.put(hello_packet(socket.gethostname(), mac(), __version__)) self._queue.put(request_packet(MSG_SERVER_SETTINGS)) self._queue.put(request_packet(MSG_SAMPLE_FORMAT)) self._queue.put(request_packet(MSG_HEADER)) def request_start(self): """ Indicate readiness to receive stream. This is a blocking call. """ self._queue.put(command_packet(CMD_START_STREAM)) _LOGGER.info('Requesting stream') self._source.run() def _read_socket(self): """ Process incoming messages from socket. """ while True: base_bytes = self._socket.recv(BASE_SIZE) base = basemessage.parse(base_bytes) payload_bytes = self._socket.recv(base.payload_length) self._handle_message(packet.parse(base_bytes + payload_bytes)) def _handle_message(self, data): """ Handle messages. """ if data.type == MSG_SERVER_SETTINGS: _LOGGER.info(data.payload) elif data.type == MSG_SAMPLE_FORMAT: _LOGGER.info(data.payload) self._connected = True elif data.type == MSG_TIME: if not self._buffered: _LOGGER.info('Buffering') elif data.type == MSG_HEADER: # Push to app source and start playing. _LOGGER.info(data.payload.codec.decode('ascii')) self._source.push(data.payload.header) self._source.play() elif data.type == MSG_WIRE_CHUNK: # Add chunks to play queue. self._buffer.put(data.payload.chunk) if self._buffer.qsize() > BUFFER_SIZE: self._buffered = True if self._buffer.empty(): self._buffered = False def _write_socket(self): """ Pass messages from queue to socket. """ while True: now = time.time() if self._connected and (self._last_sync + SYNC_AFTER) < now: self._queue.put(request_packet(MSG_TIME)) self._last_sync = now if not self._queue.empty(): self._socket.send(self._queue.get()) def _play(self): """ Relay buffer to app source. """ while True: if self._buffered: self._source.push(self._buffer.get()) happyleavesaoc-python-snapcast-aa14561/snapcast/client/gstreamer.py000066400000000000000000000037621457530775600256630ustar00rootroot00000000000000""" GStreamer-related items. """ import gi from gi.repository import GObject, Gst gi.require_version('Gst', '1.0') GObject.threads_init() Gst.init(None) class GstreamerAppSrc: """ GStreamer 1.0 App Source. Pipeline is like this: App Source -> Decode -> Queue -> Convert -> Sink App Source: The snapcast client pushes buffers into the source. Decode: Will decode for codecs supported by GStreamer (ogg, flac, etc) Queue: Queue for converting. Convert: Convert to suitable representation for Alsa. Sink: Alsa. """ def __init__(self): """ Initialize app src. """ self._mainloop = GObject.MainLoop() self._pipeline = Gst.Pipeline() # Make elements. self._src = Gst.ElementFactory.make('appsrc', 'appsrc') decode = Gst.ElementFactory.make("decodebin", "decode") self._queueaudio = Gst.ElementFactory.make('queue', 'queueaudio') audioconvert = Gst.ElementFactory.make('audioconvert', 'audioconvert') sink = Gst.ElementFactory.make('alsasink', 'sink') self._src.set_property('stream-type', 'stream') # Add to pipeline. self._pipeline.add(self._src) self._pipeline.add(decode) self._pipeline.add(self._queueaudio) self._pipeline.add(audioconvert) self._pipeline.add(sink) # Link elements. self._src.link(decode) self._queueaudio.link(audioconvert) audioconvert.link(sink) decode.connect('pad-added', self._decode_src_created) def play(self): """ Play. """ self._pipeline.set_state(Gst.State.PLAYING) def run(self): """ Run - blocking. """ self._mainloop.run() def push(self, buf): """ Push a buffer into the source. """ self._src.emit('push-buffer', Gst.Buffer.new_wrapped(buf)) # pylint: disable=unused-argument def _decode_src_created(self, element, pad): """ Link pad to queue. """ pad.link(self._queueaudio.get_static_pad('sink')) happyleavesaoc-python-snapcast-aa14561/snapcast/client/messages.py000066400000000000000000000072561457530775600255030ustar00rootroot00000000000000""" Snapcast messages. """ from construct import (ULInt8, ULInt16, ULInt32, ULInt64, Embed, Struct, Enum, Array, PascalString, Switch, Container) ENCODING = 'utf-8' BASE_SIZE = 26 # pylint: disable=bad-continuation,invalid-name timestamp = Embed(Struct('time', ULInt32('secs'), ULInt32('usecs') )) snaptype = Enum(ULInt16('type'), Base=0, Header=1, WireChunk=2, SampleFormat=3, ServerSettings=4, Time=5, Request=6, Ack=7, Command=8, Hello=9, Map=10, String=11 ) basemessage = Struct('base', snaptype, ULInt16('id'), ULInt16('refer'), Struct('sent', timestamp), Struct('recv', timestamp), ULInt32('payload_length'), ) mapmessage = Struct('map', ULInt16('num'), Array(lambda ctx: ctx.num, Struct('map', PascalString('field', length_field=ULInt16('length')), PascalString('value', length_field=ULInt16('length')) )) ) stringmessage = Struct('string', PascalString('string', length_field=ULInt16('string_length')) ) request = Struct('request', Struct('request_type', Embed(snaptype)) ) server_settings = Struct('settings', ULInt32('buffer_ms'), ULInt32('latency'), ULInt16('volume'), ULInt8('mute') ) sample_format = Struct('sample', ULInt32('rate'), ULInt16('bits'), ULInt16('channels'), ULInt16('sample_size'), ULInt16('frame_size') ) header = Struct('header', PascalString('codec', length_field=ULInt16('codec_length')), PascalString('header', length_field=ULInt32('header_length')) ) time = Struct('header', ULInt64('latency') ) chunk = Struct('chunk', Struct('timestamp', timestamp), PascalString('chunk', length_field=ULInt32('chunk_length')) ) hello = mapmessage command = stringmessage ack = stringmessage packet = Struct('packet', Embed(basemessage), Switch('payload', lambda ctx: ctx.type, { 'Header': header, 'Time': time, 'WireChunk': chunk, 'SampleFormat': sample_format, 'ServerSettings': server_settings, 'Request': request, 'Hello': hello, 'Command': command, 'Ack': ack } ) ) # pylint: enable=bad-continuation,invalid-name def message(message_type, payload, payload_length): """ Build a message. """ return packet.build( Container( type=message_type, id=1, refer=0, sent=Container( secs=0, usecs=0 ), recv=Container( secs=0, usecs=0 ), payload_length=payload_length, payload=payload ) ) def map_helper(data): """ Build a map message. """ as_list = [] length = 2 for field, value in data.items(): as_list.append(Container(field=bytes(field, ENCODING), value=bytes(value, ENCODING))) length += len(field) + len(value) + 4 return (Container( num=len(as_list), map=as_list ), length) def hello_packet(hostname, mac, version): """ Build a hello message. """ return message('Hello', *map_helper({ 'HostName': hostname, 'MAC': mac, 'Version': version })) def request_packet(request_type): """ Build a request message. """ return message('Request', Container(request_type=request_type), 2) def command_packet(cmd): """ Build a command message. """ return message('Command', Container(string_length=len(cmd), string=bytes(cmd, ENCODING)), len(cmd) + 2) happyleavesaoc-python-snapcast-aa14561/snapcast/control/000077500000000000000000000000001457530775600235125ustar00rootroot00000000000000happyleavesaoc-python-snapcast-aa14561/snapcast/control/__init__.py000066400000000000000000000004571457530775600256310ustar00rootroot00000000000000"""Snapcast control for Snapcast 0.11.1.""" from snapcast.control.server import Snapserver, CONTROL_PORT async def create_server(loop, host, port=CONTROL_PORT, reconnect=False): """Server factory.""" server = Snapserver(loop, host, port, reconnect) await server.start() return server happyleavesaoc-python-snapcast-aa14561/snapcast/control/client.py000066400000000000000000000124021457530775600253410ustar00rootroot00000000000000"""Snapcast client.""" import logging _LOGGER = logging.getLogger(__name__) # pylint: disable=too-many-public-methods class Snapclient(): """Represents a snapclient.""" def __init__(self, server, data): """Initialize.""" self._server = server self._snapshot = None self._last_seen = None self._callback_func = None self.update(data) def update(self, data): """Update client.""" self._client = data @property def identifier(self): """Get identifier.""" return self._client.get('id') @property def group(self): """Get group.""" for group in self._server.groups: if self.identifier in group.clients: return group return None @property def friendly_name(self): """Get friendly name.""" if len(self._client.get('config').get('name')): return self._client.get('config').get('name') return self._client.get('host').get('name') @property def version(self): """Version.""" return self._client.get('snapclient').get('version') @property def connected(self): """Connected or not.""" return self._client.get('connected') @property def name(self): """Name.""" return self._client.get('config').get('name') async def set_name(self, name): """Set a client name.""" if not name: name = '' self._client['config']['name'] = name await self._server.client_name(self.identifier, name) @property def latency(self): """Latency.""" return self._client.get('config').get('latency') async def set_latency(self, latency): """Set client latency.""" self._client['config']['latency'] = latency await self._server.client_latency(self.identifier, latency) @property def muted(self): """Muted or not.""" return self._client.get('config').get('volume').get('muted') async def set_muted(self, status): """Set client mute status.""" new_volume = self._client['config']['volume'] new_volume['muted'] = status self._client['config']['volume']['muted'] = status await self._server.client_volume(self.identifier, new_volume) _LOGGER.debug('set muted to %s on %s', status, self.friendly_name) @property def volume(self): """Volume percent.""" return self._client.get('config').get('volume').get('percent') async def set_volume(self, percent, update_group=True): """Set client volume percent.""" if percent not in range(0, 101): raise ValueError('Volume percent out of range') new_volume = self._client['config']['volume'] new_volume['percent'] = percent self._client['config']['volume']['percent'] = percent await self._server.client_volume(self.identifier, new_volume) if update_group: self._server.group(self.group.identifier).callback() _LOGGER.debug('set volume to %s on %s', percent, self.friendly_name) def groups_available(self): """Get available group objects.""" return list(self._server.groups) def update_volume(self, data): """Update volume.""" self._client['config']['volume'] = data['volume'] _LOGGER.debug('updated volume on %s', self.friendly_name) self._server.group(self.group.identifier).callback() self.callback() def update_name(self, data): """Update name.""" self._client['config']['name'] = data['name'] _LOGGER.debug('updated name on %s', self.friendly_name) self.callback() def update_latency(self, data): """Update latency.""" self._client['config']['latency'] = data['latency'] _LOGGER.debug('updated latency on %s', self.friendly_name) self.callback() def update_connected(self, status): """Update connected.""" self._client['connected'] = status _LOGGER.debug('updated connected status to %s on %s', status, self.friendly_name) self.callback() def snapshot(self): """Snapshot current state.""" self._snapshot = { 'name': self.name, 'volume': self.volume, 'muted': self.muted, 'latency': self.latency } _LOGGER.debug('took snapshot of current state of %s', self.friendly_name) async def restore(self): """Restore snapshotted state.""" if not self._snapshot: return await self.set_name(self._snapshot['name']) await self.set_volume(self._snapshot['volume']) await self.set_muted(self._snapshot['muted']) await self.set_latency(self._snapshot['latency']) self.callback() _LOGGER.debug('restored snapshot of state of %s', self.friendly_name) def callback(self): """Run callback.""" if self._callback_func and callable(self._callback_func): self._callback_func(self) def set_callback(self, func): """Set callback function.""" self._callback_func = func def __repr__(self): """Return string representation.""" return f'Snapclient {self.version} ({self.friendly_name}, {self.identifier})' happyleavesaoc-python-snapcast-aa14561/snapcast/control/group.py000066400000000000000000000151231457530775600252220ustar00rootroot00000000000000"""Snapcast group.""" import logging _LOGGER = logging.getLogger(__name__) # pylint: disable=too-many-public-methods class Snapgroup(): """Represents a snapcast group.""" def __init__(self, server, data): """Initialize.""" self._server = server self._snapshot = None self._callback_func = None self.update(data) def update(self, data): """Update group.""" self._group = data @property def identifier(self): """Get group identifier.""" return self._group.get('id') @property def name(self): """Get group name.""" return self._group.get('name') async def set_name(self, name): """Set a group name.""" if not name: name = '' self._group['name'] = name await self._server.group_name(self.identifier, name) @property def stream(self): """Get stream identifier.""" return self._group.get('stream_id') async def set_stream(self, stream_id): """Set group stream.""" self._group['stream_id'] = stream_id await self._server.group_stream(self.identifier, stream_id) _LOGGER.debug('set stream to %s on %s', stream_id, self.friendly_name) @property def stream_status(self): """Get stream status.""" return self._server.stream(self.stream).status @property def muted(self): """Get mute status.""" return self._group.get('muted') async def set_muted(self, status): """Set group mute status.""" self._group['muted'] = status await self._server.group_mute(self.identifier, status) _LOGGER.debug('set muted to %s on %s', status, self.friendly_name) @property def volume(self): """Get volume.""" volume_sum = 0 for client in self._group.get('clients'): volume_sum += self._server.client(client.get('id')).volume return int(volume_sum / len(self._group.get('clients'))) async def set_volume(self, volume): """Set volume.""" if volume not in range(0, 101): raise ValueError('Volume out of range') current_volume = self.volume if volume == current_volume: _LOGGER.debug('left volume at %s on group %s', volume, self.friendly_name) return delta = volume - current_volume if delta < 0: ratio = (current_volume - volume) / current_volume else: ratio = (volume - current_volume) / (100 - current_volume) for data in self._group.get('clients'): client = self._server.client(data.get('id')) client_volume = client.volume if delta < 0: client_volume -= ratio * client_volume else: client_volume += ratio * (100 - client_volume) client_volume = round(client_volume) await client.set_volume(client_volume, update_group=False) client.update_volume({ 'volume': { 'percent': client_volume, 'muted': client.muted } }) _LOGGER.debug('set volume to %s on group %s', volume, self.friendly_name) @property def friendly_name(self): """Get friendly name.""" fname = self.name if self.name != '' else "+".join( sorted([self._server.client(c).friendly_name for c in self.clients if c in [client.identifier for client in self._server.clients]])) return fname if fname != '' else self.identifier @property def clients(self): """Get client identifiers.""" return [client.get('id') for client in self._group.get('clients')] async def add_client(self, client_identifier): """Add a client.""" if client_identifier in self.clients: _LOGGER.error('%s already in group %s', client_identifier, self.identifier) return new_clients = self.clients new_clients.append(client_identifier) await self._server.group_clients(self.identifier, new_clients) _LOGGER.debug('added %s to %s', client_identifier, self.identifier) status = (await self._server.status())[0] self._server.synchronize(status) self._server.client(client_identifier).callback() self.callback() async def remove_client(self, client_identifier): """Remove a client.""" new_clients = self.clients new_clients.remove(client_identifier) await self._server.group_clients(self.identifier, new_clients) _LOGGER.debug('removed %s from %s', client_identifier, self.identifier) status = (await self._server.status())[0] self._server.synchronize(status) self._server.client(client_identifier).callback() self.callback() def streams_by_name(self): """Get available stream objects by name.""" return {stream.friendly_name: stream for stream in self._server.streams} def update_mute(self, data): """Update mute.""" self._group['muted'] = data['mute'] self.callback() _LOGGER.debug('updated mute on %s', self.friendly_name) def update_name(self, data): """Update name.""" self._group['name'] = data['name'] _LOGGER.debug('updated name on %s', self.name) self.callback() def update_stream(self, data): """Update stream.""" self._group['stream_id'] = data['stream_id'] self.callback() _LOGGER.debug('updated stream to %s on %s', self.stream, self.friendly_name) def snapshot(self): """Snapshot current state.""" self._snapshot = { 'muted': self.muted, 'volume': self.volume, 'stream': self.stream } _LOGGER.debug('took snapshot of current state of %s', self.friendly_name) async def restore(self): """Restore snapshotted state.""" if not self._snapshot: return await self.set_muted(self._snapshot['muted']) await self.set_volume(self._snapshot['volume']) await self.set_stream(self._snapshot['stream']) self.callback() _LOGGER.debug('restored snapshot of state of %s', self.friendly_name) def callback(self): """Run callback.""" if self._callback_func and callable(self._callback_func): self._callback_func(self) def set_callback(self, func): """Set callback.""" self._callback_func = func def __repr__(self): """Return string representation.""" return f'Snapgroup ({self.friendly_name}, {self.identifier})' happyleavesaoc-python-snapcast-aa14561/snapcast/control/protocol.py000066400000000000000000000053241457530775600257310ustar00rootroot00000000000000"""Snapcast protocol.""" import asyncio import json import random SERVER_ONDISCONNECT = 'Server.OnDisconnect' # pylint: disable=consider-using-f-string def jsonrpc_request(method, identifier, params=None): """Produce a JSONRPC request.""" return '{}\r\n'.format(json.dumps({ 'id': identifier, 'method': method, 'params': params or {}, 'jsonrpc': '2.0' })).encode() class SnapcastProtocol(asyncio.Protocol): """Async Snapcast protocol.""" def __init__(self, callbacks): """Initialize.""" self._transport = None self._buffer = {} self._callbacks = callbacks self._data_buffer = '' def connection_made(self, transport): """When a connection is made.""" self._transport = transport def connection_lost(self, exc): """When a connection is lost.""" for b in self._buffer.values(): b['error'] = {"code": -1, "message": "connection lost"} b['flag'].set() self._callbacks.get(SERVER_ONDISCONNECT)(exc) def data_received(self, data): """Handle received data.""" self._data_buffer += data.decode() if not self._data_buffer.endswith('\r\n'): return data = self._data_buffer self._data_buffer = '' # clear buffer for cmd in data.strip().split('\r\n'): data = json.loads(cmd) if not isinstance(data, list): data = [data] for item in data: self.handle_data(item) def handle_data(self, data): """Handle JSONRPC data.""" if 'id' in data: self.handle_response(data) else: self.handle_notification(data) def handle_response(self, data): """Handle JSONRPC response.""" identifier = data.get('id') self._buffer[identifier]['data'] = data.get('result') self._buffer[identifier]['error'] = data.get('error') self._buffer[identifier]['flag'].set() def handle_notification(self, data): """Handle JSONRPC notification.""" if data.get('method') in self._callbacks: self._callbacks.get(data.get('method'))(data.get('params')) async def request(self, method, params): """Send a JSONRPC request.""" identifier = random.randint(1, 1000) self._transport.write(jsonrpc_request(method, identifier, params)) self._buffer[identifier] = {'flag': asyncio.Event()} await self._buffer[identifier]['flag'].wait() result = self._buffer[identifier].get('data') error = self._buffer[identifier].get('error') self._buffer[identifier].clear() del self._buffer[identifier] return (result, error) happyleavesaoc-python-snapcast-aa14561/snapcast/control/server.py000066400000000000000000000443311457530775600253770ustar00rootroot00000000000000"""Snapcast server.""" import asyncio import logging from packaging import version from snapcast.control.client import Snapclient from snapcast.control.group import Snapgroup from snapcast.control.protocol import SERVER_ONDISCONNECT, SnapcastProtocol from snapcast.control.stream import Snapstream _LOGGER = logging.getLogger(__name__) CONTROL_PORT = 1705 SERVER_GETSTATUS = 'Server.GetStatus' SERVER_GETRPCVERSION = 'Server.GetRPCVersion' SERVER_DELETECLIENT = 'Server.DeleteClient' SERVER_ONUPDATE = 'Server.OnUpdate' CLIENT_GETSTATUS = 'Client.GetStatus' CLIENT_SETNAME = 'Client.SetName' CLIENT_SETLATENCY = 'Client.SetLatency' CLIENT_SETVOLUME = 'Client.SetVolume' CLIENT_ONCONNECT = 'Client.OnConnect' CLIENT_ONDISCONNECT = 'Client.OnDisconnect' CLIENT_ONVOLUMECHANGED = 'Client.OnVolumeChanged' CLIENT_ONLATENCYCHANGED = 'Client.OnLatencyChanged' CLIENT_ONNAMECHANGED = 'Client.OnNameChanged' GROUP_GETSTATUS = 'Group.GetStatus' GROUP_SETMUTE = 'Group.SetMute' GROUP_SETSTREAM = 'Group.SetStream' GROUP_SETCLIENTS = 'Group.SetClients' GROUP_SETNAME = 'Group.SetName' GROUP_ONMUTE = 'Group.OnMute' GROUP_ONSTREAMCHANGED = 'Group.OnStreamChanged' GROUP_ONNAMECHANGED = 'Group.OnNameChanged' STREAM_ONPROPERTIES = 'Stream.OnProperties' STREAM_SETPROPERTY = 'Stream.SetProperty' STREAM_CONTROL = 'Stream.Control' # not yet implemented STREAM_SETMETA = 'Stream.SetMeta' # deprecated STREAM_ONUPDATE = 'Stream.OnUpdate' STREAM_ONMETA = 'Stream.OnMetadata' # deprecated STREAM_ADDSTREAM = 'Stream.AddStream' STREAM_REMOVESTREAM = 'Stream.RemoveStream' SERVER_RECONNECT_DELAY = 5 _EVENTS = [SERVER_ONUPDATE, CLIENT_ONVOLUMECHANGED, CLIENT_ONLATENCYCHANGED, CLIENT_ONNAMECHANGED, CLIENT_ONCONNECT, CLIENT_ONDISCONNECT, GROUP_ONMUTE, GROUP_ONSTREAMCHANGED, GROUP_ONNAMECHANGED, STREAM_ONUPDATE, STREAM_ONMETA, STREAM_ONPROPERTIES] _METHODS = [SERVER_GETSTATUS, SERVER_GETRPCVERSION, SERVER_DELETECLIENT, SERVER_DELETECLIENT, CLIENT_GETSTATUS, CLIENT_SETNAME, CLIENT_SETLATENCY, CLIENT_SETVOLUME, GROUP_GETSTATUS, GROUP_SETMUTE, GROUP_SETSTREAM, GROUP_SETCLIENTS, GROUP_SETNAME, STREAM_SETMETA, STREAM_SETPROPERTY, STREAM_CONTROL, STREAM_ADDSTREAM, STREAM_REMOVESTREAM] # server versions in which new methods were added _VERSIONS = { GROUP_SETNAME: '0.16.0', STREAM_SETPROPERTY: '0.26.0', STREAM_ADDSTREAM: '0.16.0', STREAM_REMOVESTREAM: '0.16.0', } class ServerVersionError(NotImplementedError): """Server Version Error, not implemented.""" # pylint: disable=too-many-public-methods class Snapserver(): """Represents a snapserver.""" # pylint: disable=too-many-instance-attributes def __init__(self, loop, host, port=CONTROL_PORT, reconnect=False): """Initialize.""" self._loop = loop self._port = port self._reconnect = reconnect self._is_stopped = True self._clients = {} self._streams = {} self._groups = {} self._host = host self._version = None self._protocol = None self._transport = None self._callbacks = { CLIENT_ONCONNECT: self._on_client_connect, CLIENT_ONDISCONNECT: self._on_client_disconnect, CLIENT_ONVOLUMECHANGED: self._on_client_volume_changed, CLIENT_ONNAMECHANGED: self._on_client_name_changed, CLIENT_ONLATENCYCHANGED: self._on_client_latency_changed, GROUP_ONMUTE: self._on_group_mute, GROUP_ONSTREAMCHANGED: self._on_group_stream_changed, GROUP_ONNAMECHANGED: self._on_group_name_changed, STREAM_ONMETA: self._on_stream_meta, STREAM_ONPROPERTIES: self._on_stream_properties, STREAM_ONUPDATE: self._on_stream_update, SERVER_ONDISCONNECT: self._on_server_disconnect, SERVER_ONUPDATE: self._on_server_update } self._on_update_callback_func = None self._on_connect_callback_func = None self._on_disconnect_callback_func = None self._new_client_callback_func = None async def start(self): """Initiate server connection.""" self._is_stopped = False await self._do_connect() status, error = await self.status() if (not isinstance(status, dict)) or ('server' not in status): _LOGGER.warning('connected, but no valid response:\n%s', str(error)) self.stop() raise OSError _LOGGER.debug('connected to snapserver on %s:%s', self._host, self._port) self.synchronize(status) self._on_server_connect() def stop(self): """Stop server.""" self._is_stopped = True self._do_disconnect() _LOGGER.debug('Stopping') self._clients = {} self._streams = {} self._groups = {} self._version = None def _do_disconnect(self): """Perform the connection to the server.""" if self._transport: self._transport.close() async def _do_connect(self): """Perform the connection to the server.""" self._transport, self._protocol = await self._loop.create_connection( lambda: SnapcastProtocol(self._callbacks), self._host, self._port) def _reconnect_cb(self): """Try to reconnect to the server.""" _LOGGER.debug('try reconnect') async def try_reconnect(): """Actual coroutine ro try to reconnect or reschedule.""" try: await self._do_connect() status, error = await self.status() if (not isinstance(status, dict)) or ('server' not in status): _LOGGER.warning('connected, but no valid response:\n%s', str(error)) self.stop() raise OSError except OSError: self._loop.call_later(SERVER_RECONNECT_DELAY, self._reconnect_cb) else: self.synchronize(status) self._on_server_connect() asyncio.ensure_future(try_reconnect()) async def _transact(self, method, params=None): """Wrap requests.""" result = error = None if self._protocol is None or self._transport is None or self._transport.is_closing(): error = {"code": None, "message": "Server not connected"} else: result, error = await self._protocol.request(method, params) return (result, error) @property def version(self): """Version.""" return self._version async def status(self): """System status.""" return await self._transact(SERVER_GETSTATUS) async def rpc_version(self): """RPC version.""" return await self._transact(SERVER_GETRPCVERSION) async def delete_client(self, identifier): """Delete client.""" params = {'id': identifier} response, _ = await self._transact(SERVER_DELETECLIENT, params) self.synchronize(response) async def client_name(self, identifier, name): """Set client name.""" return await self._request(CLIENT_SETNAME, identifier, 'name', name) async def client_latency(self, identifier, latency): """Set client latency.""" return await self._request(CLIENT_SETLATENCY, identifier, 'latency', latency) async def client_volume(self, identifier, volume): """Set client volume.""" return await self._request(CLIENT_SETVOLUME, identifier, 'volume', volume) async def client_status(self, identifier): """Get client status.""" return await self._request(CLIENT_GETSTATUS, identifier, 'client') async def group_status(self, identifier): """Get group status.""" return await self._request(GROUP_GETSTATUS, identifier, 'group') async def group_mute(self, identifier, status): """Set group mute.""" return await self._request(GROUP_SETMUTE, identifier, 'mute', status) async def group_stream(self, identifier, stream_id): """Set group stream.""" return await self._request(GROUP_SETSTREAM, identifier, 'stream_id', stream_id) async def group_clients(self, identifier, clients): """Set group clients.""" return await self._request(GROUP_SETCLIENTS, identifier, 'clients', clients) async def group_name(self, identifier, name): """Set group name.""" self._version_check(GROUP_SETNAME) return await self._request(GROUP_SETNAME, identifier, 'name', name) async def stream_control(self, identifier, control_command, control_params): """Set stream control.""" self._version_check(STREAM_SETPROPERTY) return await self._request( STREAM_CONTROL, identifier, 'command', control_command, control_params) async def stream_setmeta(self, identifier, meta): # deprecated """Set stream metadata.""" return await self._request(STREAM_SETMETA, identifier, 'meta', meta) async def stream_setproperty(self, identifier, stream_property, value): """Set stream metadata.""" self._version_check(STREAM_SETPROPERTY) return await self._request(STREAM_SETPROPERTY, identifier, parameters={ 'property': stream_property, 'value': value }) async def stream_add_stream(self, stream_uri): """Add a stream.""" params = {"streamUri": stream_uri} result, error = await self._transact(STREAM_ADDSTREAM, params) if (isinstance(result, dict) and ("id" in result)): self.synchronize((await self.status())[0]) return result or error async def stream_remove_stream(self, identifier): """Remove a Stream.""" result = await self._request(STREAM_REMOVESTREAM, identifier) if (isinstance(result, dict) and ("id" in result)): self.synchronize((await self.status())[0]) return result def group(self, group_identifier): """Get a group.""" return self._groups[group_identifier] def stream(self, stream_identifier): """Get a stream.""" return self._streams[stream_identifier] def client(self, client_identifier): """Get a client.""" return self._clients[client_identifier] @property def groups(self): """Get groups.""" return list(self._groups.values()) @property def clients(self): """Get clients.""" return list(self._clients.values()) @property def streams(self): """Get streams.""" return list(self._streams.values()) def synchronize(self, status): """Synchronize snapserver.""" self._version = status['server']['server']['snapserver']['version'] new_groups = {} new_clients = {} new_streams = {} for stream in status.get('server').get('streams'): if stream.get('id') in self._streams: new_streams[stream.get('id')] = self._streams[stream.get('id')] new_streams[stream.get('id')].update(stream) else: new_streams[stream.get('id')] = Snapstream(stream) _LOGGER.debug('stream found: %s', new_streams[stream.get('id')]) for group in status.get('server').get('groups'): if group.get('id') in self._groups: new_groups[group.get('id')] = self._groups[group.get('id')] new_groups[group.get('id')].update(group) else: new_groups[group.get('id')] = Snapgroup(self, group) for client in group.get('clients'): if client.get('id') in self._clients: new_clients[client.get('id')] = self._clients[client.get('id')] new_clients[client.get('id')].update(client) else: new_clients[client.get('id')] = Snapclient(self, client) _LOGGER.debug('client found: %s', new_clients[client.get('id')]) _LOGGER.debug('group found: %s', new_groups[group.get('id')]) self._groups = new_groups self._clients = new_clients self._streams = new_streams # pylint: disable=too-many-arguments async def _request(self, method, identifier, key=None, value=None, parameters=None): """Perform request with identifier.""" params = {'id': identifier} if key is not None and value is not None: params[key] = value if isinstance(parameters, dict): params.update(parameters) result, error = await self._transact(method, params) if isinstance(result, dict) and key in result: return result.get(key) return result or error def _on_server_connect(self): """Handle server connection.""" _LOGGER.debug('Server connected') if self._on_connect_callback_func and callable(self._on_connect_callback_func): self._on_connect_callback_func() def _on_server_disconnect(self, exception): """Handle server disconnection.""" _LOGGER.debug('Server disconnected: %s', str(exception)) if self._on_disconnect_callback_func and callable(self._on_disconnect_callback_func): self._on_disconnect_callback_func(exception) self._protocol = None self._transport = None if (not self._is_stopped) and self._reconnect: self._reconnect_cb() def _on_server_update(self, data): """Handle server update.""" self.synchronize(data) if self._on_update_callback_func and callable(self._on_update_callback_func): self._on_update_callback_func() def _on_group_mute(self, data): """Handle group mute.""" group = self._groups.get(data.get('id')) group.update_mute(data) for client_id in group.clients: self._clients.get(client_id).callback() def _on_group_name_changed(self, data): """Handle group name changed.""" self._groups.get(data.get('id')).update_name(data) def _on_group_stream_changed(self, data): """Handle group stream change.""" group = self._groups.get(data.get('id')) group.update_stream(data) for client_id in group.clients: self._clients.get(client_id).callback() def _on_client_connect(self, data): """Handle client connect.""" client = None if data.get('id') in self._clients: client = self._clients[data.get('id')] client.update_connected(True) else: client = Snapclient(self, data.get('client')) self._clients[data.get('id')] = client if self._new_client_callback_func and callable(self._new_client_callback_func): self._new_client_callback_func(client) _LOGGER.debug('client %s connected', client.friendly_name) def _on_client_disconnect(self, data): """Handle client disconnect.""" self._clients[data.get('id')].update_connected(False) _LOGGER.debug('client %s disconnected', self._clients[data.get('id')].friendly_name) def _on_client_volume_changed(self, data): """Handle client volume change.""" self._clients.get(data.get('id')).update_volume(data) def _on_client_name_changed(self, data): """Handle client name changed.""" self._clients.get(data.get('id')).update_name(data) def _on_client_latency_changed(self, data): """Handle client latency changed.""" self._clients.get(data.get('id')).update_latency(data) def _on_stream_meta(self, data): # deprecated """Handle stream metadata update.""" stream = self._streams[data.get('id')] stream.update_meta(data.get('meta')) _LOGGER.debug('stream %s metadata updated', stream.friendly_name) for group in self._groups.values(): if group.stream == data.get('id'): group.callback() def _on_stream_properties(self, data): """Handle stream properties update.""" stream = self._streams[data.get('id')] stream.update_properties(data.get('properties')) _LOGGER.debug('stream %s properties updated', stream.friendly_name) for group in self._groups.values(): if group.stream == data.get('id'): group.callback() for client_id in group.clients: self._clients.get(client_id).callback() def _on_stream_update(self, data): """Handle stream update.""" if data.get('id') in self._streams: self._streams[data.get('id')].update(data.get('stream')) _LOGGER.debug('stream %s updated', self._streams[data.get('id')].friendly_name) self._streams[data.get("id")].callback() for group in self._groups.values(): if group.stream == data.get('id'): group.callback() for client_id in group.clients: self._clients.get(client_id).callback() else: if data.get('stream', {}).get('uri', {}).get('query', {}).get('codec') == 'null': _LOGGER.debug('stream %s is input-only, ignore', data.get('id')) else: _LOGGER.info('stream %s not found, synchronize', data.get('id')) async def async_sync(): self.synchronize((await self.status())[0]) asyncio.ensure_future(async_sync()) def set_on_update_callback(self, func): """Set on update callback function.""" self._on_update_callback_func = func def set_on_connect_callback(self, func): """Set on connection callback function.""" self._on_connect_callback_func = func def set_on_disconnect_callback(self, func): """Set on disconnection callback function.""" self._on_disconnect_callback_func = func def set_new_client_callback(self, func): """Set new client callback function.""" self._new_client_callback_func = func def __repr__(self): """Return string representation.""" return f'Snapserver {self.version} ({self._host})' def _version_check(self, api_call): if version.parse(self.version) < version.parse(_VERSIONS.get(api_call)): raise ServerVersionError( f"{api_call} requires server version >= {_VERSIONS[api_call]}." + f" Current version is {self.version}" ) happyleavesaoc-python-snapcast-aa14561/snapcast/control/stream.py000066400000000000000000000041301457530775600253550ustar00rootroot00000000000000"""Snapcast stream.""" class Snapstream(): """Represents a snapcast stream.""" def __init__(self, data): """Initialize.""" self.update(data) self._callback_func = None @property def identifier(self): """Get stream id.""" return self._stream.get('id') @property def status(self): """Get stream status.""" return self._stream.get('status') @property def name(self): """Get stream name.""" return self._stream.get('uri').get('query').get('name') @property def friendly_name(self): """Get friendly name.""" return self.name if self.name != '' else self.identifier @property def metadata(self): """Get metadata.""" if 'properties' in self._stream: return self._stream['properties'].get('metadata') return self._stream.get('meta') @property def meta(self): """Get metadata. Deprecated.""" return self.metadata @property def properties(self): """Get properties.""" return self._stream.get('properties') @property def path(self): """Get stream path.""" return self._stream.get('uri').get('path') def update(self, data): """Update stream.""" self._stream = data def update_meta(self, data): """Update stream metadata.""" self.update_metadata(data) def update_metadata(self, data): """Update stream metadata.""" if 'properties' in self._stream: self._stream['properties']['metadata'] = data self._stream['meta'] = data def update_properties(self, data): """Update stream properties.""" self._stream['properties'] = data def __repr__(self): """Return string representation.""" return f'Snapstream ({self.name})' def callback(self): """Run callback.""" if self._callback_func and callable(self._callback_func): self._callback_func(self) def set_callback(self, func): """Set callback.""" self._callback_func = func happyleavesaoc-python-snapcast-aa14561/tests/000077500000000000000000000000001457530775600213605ustar00rootroot00000000000000happyleavesaoc-python-snapcast-aa14561/tests/helpers.py000066400000000000000000000002431457530775600233730ustar00rootroot00000000000000"""Asyncio test helpers from https://blog.miguelgrinberg.com/post/unit-testing-asyncio-code""" import asyncio def async_run(coro): return asyncio.run(coro) happyleavesaoc-python-snapcast-aa14561/tests/test_client.py000066400000000000000000000065621457530775600242600ustar00rootroot00000000000000import unittest from unittest import mock from unittest.mock import MagicMock, AsyncMock from helpers import async_run from snapcast.control.client import Snapclient class TestSnapclient(unittest.TestCase): def setUp(self): data = { 'id': 'test', 'host': { 'ip': '0.0.0.0', 'name': 'localhost' }, 'config': { 'name': '', 'latency': 0, 'volume': { 'muted': False, 'percent': 90 } }, 'snapclient': { 'version': '0.0' }, 'connected': True } server = AsyncMock() server.synchronize = MagicMock() group = AsyncMock() group.callback = MagicMock() server.group = MagicMock(return_value=group) server.groups = ['test_group'] self.client = Snapclient(server, data) @mock.patch.object(Snapclient, 'group', new=1) def test_init(self): self.assertEqual(self.client.identifier, 'test') self.assertEqual(self.client.friendly_name, 'localhost') self.assertEqual(self.client.version, '0.0') self.assertEqual(self.client.connected, True) self.assertEqual(self.client.name, '') self.assertEqual(self.client.latency, 0) self.assertEqual(self.client.volume, 90) self.assertEqual(self.client.muted, False) self.assertEqual(self.client.group, 1) @mock.patch.object(Snapclient, 'group') def test_set_volume(self, mock): async_run(self.client.set_volume(100)) self.assertEqual(self.client.volume, 100) def test_set_name(self): async_run(self.client.set_name('test')) self.assertEqual(self.client.name, 'test') def test_set_latency(self): async_run(self.client.set_latency(1)) self.assertEqual(self.client.latency, 1) def test_set_muted(self): async_run(self.client.set_muted(True)) self.assertEqual(self.client.muted, True) @mock.patch.object(Snapclient, 'group') def test_update_volume(self, mock): self.client.update_volume({'volume': {'percent': 50, 'muted': True}}) self.assertEqual(self.client.volume, 50) self.assertEqual(self.client.muted, True) def test_update_name(self): self.client.update_name({'name': 'new name'}) self.assertEqual(self.client.name, 'new name') def test_update_latency(self): self.client.update_latency({'latency': 50}) self.assertEqual(self.client.latency, 50) def test_update_connected(self): self.client.update_connected(False) self.assertEqual(self.client.connected, False) @mock.patch.object(Snapclient, 'group') def test_snapshot_restore(self, mock): async_run(self.client.set_name('first')) self.client.snapshot() async_run(self.client.set_name('other name')) self.assertEqual(self.client.name, 'other name') async_run(self.client.restore()) self.assertEqual(self.client.name, 'first') def test_set_callback(self): cb = MagicMock() self.client.set_callback(cb) self.client.update_connected(False) cb.assert_called_with(self.client) def test_groups_available(self): self.assertEqual(self.client.groups_available(), ['test_group']) happyleavesaoc-python-snapcast-aa14561/tests/test_group.py000066400000000000000000000064351457530775600241350ustar00rootroot00000000000000import unittest from unittest.mock import MagicMock, AsyncMock from helpers import async_run from snapcast.control.group import Snapgroup class TestSnapgroup(unittest.TestCase): def setUp(self): data = { 'id': 'test', 'name': '', 'stream_id': 'test stream', 'muted': False, 'clients': [ {'id': 'a'}, {'id': 'b'} ] } server = AsyncMock() server.synchronize = MagicMock() stream = MagicMock() stream.friendly_name = 'test stream' stream.status = 'playing' client = AsyncMock() client.volume = 50 client.callback = MagicMock() client.update_volume = MagicMock() client.friendly_name = 'A' client.identifier = 'a' server.streams = [stream] server.stream = MagicMock(return_value=stream) server.client = MagicMock(return_value=client) server.clients = [client] self.group = Snapgroup(server, data) def test_init(self): self.assertEqual(self.group.identifier, 'test') self.assertEqual(self.group.name, '') self.assertEqual(self.group.friendly_name, 'A') self.assertEqual(self.group.stream, 'test stream') self.assertEqual(self.group.muted, False) self.assertEqual(self.group.volume, 50) self.assertEqual(self.group.clients, ['a', 'b']) self.assertEqual(self.group.stream_status, 'playing') def test_repr(self): self.assertEqual(self.group.__repr__(), 'Snapgroup (A, test)') def test_update(self): self.group.update({ 'stream_id': 'other stream' }) self.assertEqual(self.group.stream, 'other stream') def test_set_muted(self): async_run(self.group.set_muted(True)) self.assertEqual(self.group.muted, True) def test_set_volume(self): async_run(self.group.set_volume(75)) def test_set_stream(self): async_run(self.group.set_stream('new stream')) self.assertEqual(self.group.stream, 'new stream') def test_set_name(self): async_run(self.group.set_name('test')) self.assertEqual(self.group.name, 'test') def test_add_client(self): async_run(self.group.add_client('c')) # TODO: add assert def test_remove_client(self): async_run(self.group.remove_client('a')) # TODO: add assert def test_streams_by_name(self): self.assertEqual(self.group.streams_by_name().keys(), set(['test stream'])) def test_update_mute(self): self.group.update_mute({'mute': True}) self.assertEqual(self.group.muted, True) def test_update_stream(self): self.group.update_stream({'stream_id': 'other stream'}) self.assertEqual(self.group.stream, 'other stream') def test_snapshot_restore(self): async_run(self.group.set_muted(False)) self.group.snapshot() async_run(self.group.set_muted(True)) self.assertEqual(self.group.muted, True) async_run(self.group.restore()) self.assertEqual(self.group.muted, False) def test_set_callback(self): cb = MagicMock() self.group.set_callback(cb) self.group.update_mute({'mute': True}) cb.assert_called_with(self.group) happyleavesaoc-python-snapcast-aa14561/tests/test_server.py000066400000000000000000000311201457530775600242740ustar00rootroot00000000000000import asyncio import copy import unittest from unittest import mock from unittest.mock import AsyncMock, MagicMock from snapcast.control.server import Snapserver from snapcast.control import create_server SERVER_STATUS = { 'host': { 'arch': 'x86_64', 'ip': '', 'mac': '', 'name': 'T400', 'os': 'Linux Mint 17.3 Rosa' }, 'snapserver': { 'controlProtocolVersion': 1, 'name': 'Snapserver', 'protocolVersion': 1, 'version': '0.26.0' } } return_values = { 'Server.GetStatus': { 'server': { 'groups': [ { 'id': 'test', 'stream_id': 'stream', 'clients': [ { 'id': 'test', 'host': { 'mac': 'abcd', 'ip': '0.0.0.0', }, 'config': { 'name': '', 'latency': 0, 'volume': { 'muted': False, 'percent': 90 } }, 'lastSeen': { 'sec': 10, 'usec': 100 }, 'snapclient': { 'version': '0.0' }, 'connected': True } ] } ], 'server': SERVER_STATUS, 'streams': [ { 'id': 'stream', 'status': 'playing', 'uri': { 'query': { 'name': 'stream' } }, 'properties': { 'canControl': False, 'metadata': { 'title': 'Happy!', } } } ] } }, 'Client.SetName': { 'name': 'test name' }, 'Server.GetRPCVersion': { 'major': 2, 'minor': 0, 'patch': 1 }, 'Client.SetLatency': { 'latency': 50 }, 'Client.SetVolume': { 'volume': { 'percent': 50, 'muted': True } }, 'Server.DeleteClient': { 'server': { 'groups': [ { 'clients': [] } ], 'server': SERVER_STATUS, # DeleteClient calls synchronize 'streams': [ ] } }, 'Group.GetStatus': { 'group': { 'clients': [] } }, 'Group.SetMute': { 'mute': True }, 'Group.SetStream': { 'stream_id': 'stream' }, 'Group.SetClients': { 'clients': ['test'] }, 'Stream.SetMeta': { 'foo': 'bar' }, 'Stream.SetProperty': 'ok', 'Stream.AddStream': { 'id': 'stream 2' }, 'Stream.RemoveStream': { 'id': 'stream 2' }, } def mock_transact(key): return AsyncMock(return_value=(return_values[key], None)) class TestSnapserver(unittest.TestCase): def _run(self, coro): return asyncio.run(coro) @mock.patch.object(Snapserver, 'start', new=AsyncMock()) def setUp(self): self.loop = MagicMock() self.server = self._run(create_server(self.loop, 'abcd')) self.server.synchronize(return_values.get('Server.GetStatus')) @mock.patch.object(Snapserver, 'status', new=AsyncMock( return_value=(None, {"code": -1, "message": "failed"}))) @mock.patch.object(Snapserver, '_do_connect', new=AsyncMock()) @mock.patch.object(Snapserver, 'stop', new=mock.MagicMock()) def test_start_fail(self): with self.assertRaises(OSError): self._run(self.server.start()) @mock.patch.object(Snapserver, '_transact', new=mock_transact('Server.GetStatus')) @mock.patch.object(Snapserver, '_do_connect', new=AsyncMock()) def test_start(self): self.server._version = None self._run(self.server.start()) self.assertEqual(self.server.version, '0.26.0') def test_init(self): self.assertEqual(self.server.version, '0.26.0') self.assertEqual(len(self.server.clients), 1) self.assertEqual(len(self.server.groups), 1) self.assertEqual(len(self.server.streams), 1) self.assertEqual(self.server.group('test').identifier, 'test') self.assertEqual(self.server.stream('stream').identifier, 'stream') self.assertEqual(self.server.client('test').identifier, 'test') @mock.patch.object(Snapserver, '_transact', new=mock_transact('Server.GetStatus')) def test_status(self): status, _ = self._run(self.server.status()) self.assertEqual(status['server']['server']['snapserver']['version'], '0.26.0') @mock.patch.object(Snapserver, '_transact', new=mock_transact('Server.GetRPCVersion')) def test_rpc_version(self): version, _ = self._run(self.server.rpc_version()) self.assertEqual(version, {'major': 2, 'minor': 0, 'patch': 1}) @mock.patch.object(Snapserver, '_transact', new=mock_transact('Client.SetName')) def test_client_name(self): name = self._run(self.server.client_name('test', 'test name')) self.assertEqual(name, 'test name') @mock.patch.object(Snapserver, '_transact', new=mock_transact('Client.SetLatency')) def test_client_latency(self): result = self._run(self.server.client_latency('test', 50)) self.assertEqual(result, 50) @mock.patch.object(Snapserver, '_transact', new=mock_transact('Client.SetVolume')) def test_client_volume(self): vol = {'percent': 50, 'muted': True} result = self._run(self.server.client_volume('test', vol)) self.assertEqual(result, vol) @mock.patch.object(Snapserver, '_transact', new=mock_transact('Server.DeleteClient')) def test_delete_client(self): self._run(self.server.delete_client('test')) self.assertEqual(len(self.server.clients), 0) @mock.patch.object(Snapserver, '_transact', new=mock_transact('Group.GetStatus')) def test_group_status(self): result = self._run(self.server.group_status('test')) self.assertEqual(result, {'clients': []}) @mock.patch.object(Snapserver, '_transact', new=mock_transact('Group.SetMute')) def test_group_mute(self): result = self._run(self.server.group_mute('test', True)) self.assertEqual(result, True) @mock.patch.object(Snapserver, '_transact', new=mock_transact('Group.SetStream')) def test_group_stream(self): result = self._run(self.server.group_stream('test', 'stream')) self.assertEqual(result, 'stream') @mock.patch.object(Snapserver, '_transact', new=mock_transact('Group.SetClients')) def test_group_clients(self): result = self._run(self.server.group_clients('test', ['test'])) self.assertEqual(result, ['test']) @mock.patch.object(Snapserver, '_transact', new=mock_transact('Stream.SetMeta')) def test_stream_setmeta(self): result = self._run(self.server.stream_setmeta('stream', {'foo': 'bar'})) self.assertEqual(result, {'foo': 'bar'}) @mock.patch.object(Snapserver, '_transact', new=mock_transact('Stream.SetProperty')) def test_stream_setproperty(self): result = self._run(self.server.stream_setproperty('stream', 'foo', 'bar')) self.assertEqual(result, 'ok') @mock.patch.object(Snapserver, '_transact', new=mock_transact('Stream.AddStream')) @mock.patch.object(Snapserver, 'synchronize', new=MagicMock()) def test_stream_addstream(self): result = self._run(self.server.stream_add_stream('pipe:///tmp/test?name=stream 2')) self.assertDictEqual(result, {'id': 'stream 2'}) @mock.patch.object(Snapserver, '_transact', new=mock_transact('Stream.RemoveStream')) @mock.patch.object(Snapserver, 'synchronize', new=MagicMock()) def test_stream_removestream(self): result = self._run(self.server.stream_remove_stream('stream 2')) self.assertDictEqual(result, {'id': 'stream 2'}) def test_synchronize(self): status = copy.deepcopy(return_values.get('Server.GetStatus')) status['server']['server']['snapserver']['version'] = '0.12' self.server.synchronize(status) self.assertEqual(self.server.version, '0.12') def test_on_server_connect(self): cb = mock.MagicMock() self.server.set_on_connect_callback(cb) self.server._on_server_connect() cb.assert_called_with() def test_on_server_disconnect(self): cb = mock.MagicMock() self.server.set_on_disconnect_callback(cb) e = Exception() self.server._on_server_disconnect(e) cb.assert_called_with(e) def test_on_server_update(self): cb = mock.MagicMock() self.server.set_on_update_callback(cb) status = copy.deepcopy(return_values.get('Server.GetStatus')) status['server']['server']['snapserver']['version'] = '0.12' self.server._on_server_update(status) self.assertEqual(self.server.version, '0.12') cb.assert_called_with() def test_on_group_mute(self): data = { 'id': 'test', 'mute': True } self.server._on_group_mute(data) self.assertEqual(self.server.group('test').muted, True) def test_on_group_stream_changed(self): data = { 'id': 'test', 'stream_id': 'other' } self.server._on_group_stream_changed(data) self.assertEqual(self.server.group('test').stream, 'other') def test_on_client_connect(self): cb = mock.MagicMock() self.server.set_new_client_callback(cb) data = { 'id': 'new', 'client': { 'id': 'new', 'connected': True, 'config': { 'name': '' }, 'host': { 'name': 'new' } } } self.server._on_client_connect(data) self.assertEqual(self.server.client('new').connected, True) cb.assert_called_with(self.server.client('new')) def test_on_client_disconnect(self): data = { 'id': 'test' } self.server._on_client_disconnect(data) self.assertEqual(self.server.client('test').connected, False) def test_on_client_volume_changed(self): data = { 'id': 'test', 'volume': { 'percent': 50, 'muted': True } } self.server._on_client_volume_changed(data) self.assertEqual(self.server.client('test').volume, 50) self.assertEqual(self.server.client('test').muted, True) def test_on_client_name_changed(self): data = { 'id': 'test', 'name': 'new' } self.server._on_client_name_changed(data) self.assertEqual(self.server.client('test').name, 'new') def test_on_client_latency_changed(self): data = { 'id': 'test', 'latency': 50 } self.server._on_client_latency_changed(data) self.assertEqual(self.server.client('test').latency, 50) def test_on_stream_update(self): data = { 'id': 'stream', 'stream': { 'id': 'stream', 'status': 'idle', 'uri': { 'query': { 'name': 'stream' } } } } self.server._on_stream_update(data) self.assertEqual(self.server.stream('stream').status, 'idle') def test_on_meta_update(self): data = { 'id': 'stream', 'meta': { 'TITLE': 'Happy!' } } self.server._on_stream_meta(data) self.assertDictEqual(self.server.stream('stream').meta, data['meta']) def test_on_properties_update(self): data = { 'id': 'stream', 'properties': { 'canControl': True, 'metadata': { 'title': 'Unhappy!', } } } self.server._on_stream_properties(data) self.assertDictEqual(self.server.stream('stream').properties, data['properties']) happyleavesaoc-python-snapcast-aa14561/tests/test_stream.py000066400000000000000000000055051457530775600242710ustar00rootroot00000000000000import unittest from snapcast.control.stream import Snapstream class TestSnapstream(unittest.TestCase): def setUp(self): data_meta = { 'id': 'test', 'status': 'playing', 'uri': { 'query': { 'name': '' } }, 'meta': { 'TITLE': 'Happy!', } } data = { 'id': 'test', 'status': 'playing', 'uri': { 'path': '/tmp/snapfifo', 'query': { 'name': '' } }, 'properties': { 'canControl': False, 'metadata': { 'title': 'Happy!', } } } self.stream_meta = Snapstream(data_meta) self.stream = Snapstream(data) def test_init(self): self.assertEqual(self.stream.identifier, 'test') self.assertEqual(self.stream.status, 'playing') self.assertEqual(self.stream.name, '') self.assertEqual(self.stream.friendly_name, 'test') self.assertEqual(self.stream.path, '/tmp/snapfifo') self.assertDictEqual(self.stream_meta.meta, {'TITLE': 'Happy!'}) self.assertDictEqual(self.stream.properties['metadata'], {'title': 'Happy!'}) self.assertDictEqual(self.stream.properties, {'canControl': False, 'metadata': {'title': 'Happy!'}}) self.assertDictEqual(self.stream.metadata, {'title': 'Happy!'}) def test_update(self): self.stream.update({ 'id': 'test', 'status': 'idle' }) self.assertEqual(self.stream.status, 'idle') def test_update_meta(self): self.stream_meta.update_meta({ 'TITLE': 'Unhappy!' }) self.assertDictEqual(self.stream_meta.meta, { 'TITLE': 'Unhappy!' }) # Verify that other attributes are still present self.assertEqual(self.stream.status, 'playing') def test_update_metadata(self): self.stream.update_metadata({ 'title': 'Unhappy!' }) self.assertDictEqual(self.stream.metadata, { 'title': 'Unhappy!' }) # Verify that other attributes are still present self.assertEqual(self.stream.status, 'playing') def test_update_properties(self): self.stream.update_properties({ 'canControl': True, 'metadata': { 'title': 'Unhappy!', } }) self.assertDictEqual(self.stream.properties, { 'canControl': True, 'metadata': { 'title': 'Unhappy!', } }) # Verify that other attributes are still present self.assertEqual(self.stream.status, 'playing') happyleavesaoc-python-snapcast-aa14561/tox.ini000066400000000000000000000011571457530775600215350ustar00rootroot00000000000000[tox] envlist = py310, py311, lint skip_missing_interpreters = True [tool:pytest] testpaths = tests [flake8] exclude = .tox # match pylint line length max-line-length = 100 [testenv] ignore_errors = True setenv = LANG=en_US.UTF-8 PYTHONPATH={toxinidir}:{toxinidir}/snapcast PYTHON_ENV=test deps = pytest pytest-cov pytest-sugar pylint flake8 pydocstyle commands = py.test --cov-report term-missing --cov snapcast [testenv:lint] ignore_errors = True commands = pylint --output-format=colorized snapcast/control flake8 snapcast/control pydocstyle snapcast/control