Question

I try to use python-mpd2 for a project. However, the connection breaks after about one minute.

I with my inferior python skills I try to make a proxy to overcome this problem. The aim is to reconnect, if the connection breaks.

This is as far as I get

import mpd

class MPDProxy:
    def __init__(self, host="localhost", port=6600, timeout=10):
        self.client = MPDClient()
        self.host = host
        self.port = port

        self.client.timeout = timeout
        self.establish_connection(host, port)

    def establish_connection(self, host, port):
        self.client.connect(host, port)

    def call(self, function, *args):
        try:
            return self.client.function(*args)
        except mpd.ConnectionError:
            self.establish_connection(self.host, self.port)
            return self.client.function(*args)

However, the call method does not work.

>>> client = MPDProxy()
>>> client.call(status)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'status' is not defined

As far as I understand this error message, it says "I don't know no method called 'status'", which I somehow understand. However, I don't see how to solve this problem (yet).

Was it helpful?

Solution

With the help of some friends, stackoverflow and some further reading I could solve this issue. Here's the code

import mpd

class MPDProxy:
    def __init__(self, host="localhost", port=6600, timeout=10):
        self.client = mpd.MPDClient()
        self.host = host
        self.port = port

        self.client.timeout = timeout
        self.connect(host, port)

    def __getattr__(self, name):
        return self._call_with_reconnect(getattr(self.client, name))

    def connect(self, host, port):
        self.client.connect(host, port)

    def _call_with_reconnect(self, func):
        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except mpd.ConnectionError:
                self.connect(self.host, self.port)
                return func(*args, **kwargs)
        return wrapper

mpd_proxy = MPDProxy()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top