File: twisted_example.py

package info (click to toggle)
python-mpd 3.1.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 472 kB
  • sloc: python: 3,148; makefile: 201; sh: 9
file content (52 lines) | stat: -rw-r--r-- 1,502 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from __future__ import print_function
from mpd import MPDProtocol
from twisted.internet import protocol
from twisted.internet import reactor


class MPDApp(object):
    # Example application which deals with MPD

    def __init__(self, protocol):
        self.protocol = protocol

    def __call__(self, result):
        # idle result callback
        print("Subsystems: {}".format(list(result)))

        def status_success(result):
            # status query success
            print("Status success: {}".format(result))

        def status_error(result):
            # status query failure
            print("Status error: {}".format(result))

        # query player status
        self.protocol.status().addCallback(status_success).addErrback(status_error)


class MPDClientFactory(protocol.ClientFactory):
    protocol = MPDProtocol

    def buildProtocol(self, addr):
        print("Create MPD protocol")
        protocol = self.protocol()
        protocol.factory = self
        protocol.idle_result = MPDApp(protocol)
        return protocol

    def clientConnectionFailed(self, connector, reason):
        print("Connection failed - goodbye!: {}".format(reason))
        reactor.stop()

    def clientConnectionLost(self, connector, reason):
        print("Connection lost - goodbye!: {}".format(reason))
        if reactor.running:
            reactor.stop()


if __name__ == "__main__":
    factory = MPDClientFactory()
    reactor.connectTCP("localhost", 6600, factory)
    reactor.run()