File: test-client.py

package info (click to toggle)
emacspeak 40.0%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 16,208 kB
  • ctags: 5,818
  • sloc: xml: 55,354; lisp: 53,656; cpp: 1,893; tcl: 1,535; python: 1,370; makefile: 832; sh: 818; perl: 281; ansic: 241
file content (59 lines) | stat: -rw-r--r-- 2,020 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
53
54
55
56
57
58
59
#!/usr/bin/python
# A Python client for HTTPSpeaker.
__id__ = "$Id$"
__author__ = "Jason White"
__version__ = "$Revision$"
__date__ = "$Date$"
__copyright__ = "Copyright 2011 Jason White"
__license__ = "LGPL"

from httplib import HTTPConnection, HTTPResponse

class HTTPSpeakerError(Exception):
    "Holds the HTTP status code and reason phrase returned by the server in the event of an error."
    def __init__(self, status, reason):
        self.status = status
        self.reason = reason
    def __str__(self):
        return "Status code " + str(self.status) + ": " + self.reason

class HTTPSpeakerClient:
    """Emacspeak HTTP speech client, for HTTPSpeaker instances."""
    def __init__(self, host="127.0.0.1", port=8000):
        "Initialize client to connect to server at given host and port."
        self._connection=HTTPConnection(host, port)

    def postCommand(self, command, arg=""):
        """Post command, with argument arg (default, empty), to the speech server.
        Returns the body of the server's HTTP response, if any. On error, HTTPSpeakerError is raised."""
        body = command
        if arg:
            body += ": " + arg
        self._connection.request("POST", "/", body, {"Content-type": "text/plain"})
        response=self._connection.getresponse()
        if response.status != 200:
            raise HTTPSpeakerError(response.status, response.reason)
        return response.read()

    def speak(self, text):
        "Speak the supplied string."
        self.postCommand("speak", text)

    def stop(self):
        "Stop speaking."
        self.postCommand("stop")

    def isSpeaking(self):
        "Return '0' when not speaking."
        return self.postCommand("isSpeaking")

    def close(self):
        "Close the connection to the speech server."
        self._connection.close()

# Test the server (assumes localhost:8000).
if __name__ == '__main__':
    client = HTTPSpeakerClient()
    client.speak("Hello, world!")
    print client.isSpeaking()
    client.close()