starpy.manager
index
/home/mcfletch/pylive/starpy/manager.py

Asterisk Manager Interface for the Twisted networking framework
 
The Asterisk Manager Interface is a simple line-oriented protocol that allows
for basic control of the channels active on a given Asterisk server.
 
Module defines a standard Python logging module log 'AMI'

 
Modules
       
twisted.protocols.basic
twisted.internet.defer
starpy.error
logging
twisted.internet.protocol
socket

 
Classes
       
ClientFactory(Factory)
AMIFactory
LineOnlyReceiver(Protocol)
AMIProtocol

 
class AMIFactory(ClientFactory)
    A factory for AMI protocols
 
 
Method resolution order:
AMIFactory
ClientFactory
Factory

Methods defined here:
__init__(self, username, secret)
login(self, ip='localhost', port=5038)
Connect, returning our (singleton) protocol instance with login completed
 
XXX This is messy, we'd much rather have the factory able to create
large numbers of protocols simultaneously

Data and other attributes defined here:
protocol = <class starpy.manager.AMIProtocol>
Protocol for the interfacing with the Asterisk Manager Interface (AMI)
 
Provides most of the AMI Action interfaces.
Auto-generates ActionID fields for all calls.
 
Events and messages are passed around as simple dictionaries with 
all-lowercase keys.  Values are case-sensitive.
 
XXX Want to allow for timeouts
 
Attributes:
        count -- total count of messages sent from this protocol 
        hostName -- used along with count and ID to produce unique IDs
        messageCache -- stores incoming message fragments from the manager

Methods inherited from ClientFactory:
clientConnectionFailed(self, connector, reason)
Called when a connection has failed to connect.
 
It may be useful to call connector.connect() - this will reconnect.
 
@type reason: L{twisted.python.failure.Failure}
clientConnectionLost(self, connector, reason)
Called when an established connection is lost.
 
It may be useful to call connector.connect() - this will reconnect.
 
@type reason: L{twisted.python.failure.Failure}
startedConnecting(self, connector)
Called when a connection has been started.
 
You can call connector.stopConnecting() to stop the connection attempt.
 
@param connector: a Connector object.

Methods inherited from Factory:
buildProtocol(self, addr)
Create an instance of a subclass of Protocol.
 
The returned instance will handle input on an incoming server
connection, and an attribute "factory" pointing to the creating
factory.
 
Override this method to alter how Protocol instances get created.
 
@param addr: an object implementing L{twisted.internet.interfaces.IAddress}
doStart(self)
Make sure startFactory is called.
 
Users should not call this function themselves!
doStop(self)
Make sure stopFactory is called.
 
Users should not call this function themselves!
startFactory(self)
This will be called before I begin listening on a Port or Connector.
 
It will only be called once, even if the factory is connected
to multiple ports.
 
This can be used to perform 'unserialization' tasks that
are best put off until things are actually running, such
as connecting to a database, opening files, etcetera.
stopFactory(self)
This will be called before I stop listening on all Ports/Connectors.
 
This can be overridden to perform 'shutdown' tasks such as disconnecting
database connections, closing files, etc.
 
It will be called, for example, before an application shuts down,
if it was connected to a port. User code should not call this function
directly.

Data and other attributes inherited from Factory:
__implemented__ = <implementedBy twisted.internet.protocol.Factory>
__implements__ = (<MetaInterface twisted.internet.interfaces.IProtocolFactory>,)
__providedBy__ = <zope.interface.declarations.Declaration object>
noisy = True
numPorts = 0

 
class AMIProtocol(LineOnlyReceiver)
    Protocol for the interfacing with the Asterisk Manager Interface (AMI)
 
Provides most of the AMI Action interfaces.
Auto-generates ActionID fields for all calls.
 
Events and messages are passed around as simple dictionaries with 
all-lowercase keys.  Values are case-sensitive.
 
XXX Want to allow for timeouts
 
Attributes:
        count -- total count of messages sent from this protocol 
        hostName -- used along with count and ID to produce unique IDs
        messageCache -- stores incoming message fragments from the manager
 
 
Method resolution order:
AMIProtocol
LineOnlyReceiver
Protocol
BaseProtocol

Methods defined here:
__init__(self, *args, **named)
Initialise the AMIProtocol, arguments are ignored
absoluteTimeout(self, channel, timeout)
Set timeout value for the given channel (in seconds)
changeMonitor(self, channel, filename)
Change the file to which the channel is to be recorded
cleanup(self, result, actionid)
Cleanup callbacks on completion
collectDeferred(self, message, stopEvent)
Collect all responses to this message until stopEvent or error
 
returns deferred returning sequence of events/responses
command(self, command)
Run asterisk console command, return deferred result for line of lines
 
returns deferred returning list of lines (strings) of the command
output.
 
See listCommands to see available commands
connectionLost(self, reason)
Connection lost, clean up callbacks
connectionMade(self)
Handle connection to the AMI port (auto-login)
 
This is a Twisted customisation point, we use it to automatically 
log into the connection we've just established.
 
XXX Should probably use proper Twisted-style credential negotiations
deregisterEvent(self, event, function=None)
Deregister callback for the given event-type
 
event -- event name (or names) to be deregistered, see registerEvent
function -- the function to be removed from the callbacks or None to
        remove all callbacks for the event
 
returns success boolean
dispatchEvent(self, event)
Given an incoming event, dispatch to registered handlers
dispatchIncoming(self)
Dispatch any finished incoming events/messages
errorUnlessResponse(self, message, expected='Success')
Raise a AMICommandFailure error unless message['response'] == expected
 
If == expected, returns the message
events(self, eventmask=False)
Determine whether events are generated
generateActionId(self)
Generate a unique action ID
 
Assumes that hostName must be unique among all machines which talk
to a given AMI server.  With that is combined the memory location of
the protocol object (which should be machine-unique) and the count of
messages that this manager has created so far.
 
Generally speaking, you shouldn't need to know the action ID, as the
protocol handles the management of them automatically.
getVar(self, channel, variable)
Retrieve the given variable from the channel
hangup(self, channel)
Tell channel to hang up
lineReceived(self, line)
Handle Twisted's report of an incoming line from the manager
listCommands(self)
List the set of commands available
 
Returns a single message with each command-name as a key
login(self)
Log into the AMI interface (done automatically on connection)
 
Uses factory.username and factory.secret
logoff(self)
Log off from the manager instance
mailboxCount(self, mailbox)
Get count of messages in the given mailbox
mailboxStatus(self, mailbox)
Get status of given mailbox
monitor(self, channel, file, format, mix)
Record given channel to a file (or attempt to anyway)
originate(self, channel, context=None, exten=None, priority=None, timeout=None, callerid=None, account=None, application=None, data=None)
Originate call to connect channel to given context/exten/priority
 
channel -- the outgoing channel to which will be dialed
context/exten/priority -- the dialplan coordinate to which to connect 
        the channel (i.e. where to start the called person)
timeout -- duration before timeout in seconds (note: not Asterisk standard!)
callerid -- callerid to display on the channel
account -- account to which the call belongs
application -- alternate application to Dial to use for outbound dial 
data -- data to pass to application
parkedCalls(self)
Retrieve set of parked calls via multi-event callback
ping(self)
Log off from the manager instance
queueAdd(self, queue, interface, penalty=0, paused=True)
Add given interface to named queue
queueRemove(self, queue, interface)
Remove given interface from named queue
queueStatus(self)
Retrieve information about active queues via multiple events
queues(self)
Retrieve information about active queues via multiple events
redirect(self, channel, context, exten, priority, extraChannel=None)
Transfer channel(s) to given context/exten/priority
registerEvent(self, event, function)
Register callback for the given event-type
 
event -- string name for the event, None to match all events, or 
        a tuple of string names to match multiple events.
 
        See http://www.voip-info.org/wiki/view/asterisk+manager+events
        for list of events and the data they bear.  Includes:
                
                Newchannel -- note that you can receive multiple Newchannel
                        events for a single channel!
                Hangup
                Newexten
                Newstate
                Reload
                Shutdown
                ExtensionStatus
                Rename
                Newcallerid
                Alarm
                AlarmClear
                Agentcallbacklogoff
                Agentcallbacklogin
                Agentlogin
                Agentlogoff
                MeetmeJoin
                MeetmeLeave
                MessageWaiting
                Join
                Leave
                AgentCalled
                ParkedCall
                Cdr
                ParkedCallsComplete
                QueueParams
                QueueMember
        
        among other standard events.  Also includes user-defined events.
function -- function taking (protocol,event) as arguments or None 
        to deregister the current function.
 
Multiple functions may be registered for a given event
sendDeferred(self, message)
Send with a single-callback deferred object
 
Returns deferred that fires when a response to this message is received
sendMessage(self, message, responseCallback=None)
Send the message to the other side, return deferred for the result
 
returns the actionid for the message
setCDRUserField(self, channel, userField, append=True)
Set/add to a user field in the CDR for given channel
setVar(self, channel, variable, value)
Set channel variable to given value
sipPeers(self)
List all known sip peers
status(self, channel=None)
Retrieve status for the given (or all) channels via multi-event callback
 
channel -- channel name or None to retrieve all channels
 
returns deferred returning list of Status Events for each requested 
channel
stopMonitor(self, channel)
Stop monitoring the given channel

Data and other attributes defined here:
END_DATA = '--END COMMAND--'
VERSION_PREFIX = 'Asterisk Call Manager'
amiVersion = None
count = 0

Methods inherited from LineOnlyReceiver:
dataReceived(self, data)
Translates bytes into lines, and calls lineReceived.
lineLengthExceeded(self, line)
Called when the maximum line length has been reached.
Override if it needs to be dealt with in some special way.
sendLine(self, line)
Sends a line to the other end of the connection.

Data and other attributes inherited from LineOnlyReceiver:
MAX_LENGTH = 16384
delimiter = '\r\n'

Data and other attributes inherited from Protocol:
__implemented__ = <implementedBy twisted.internet.protocol.Protocol>
__implements__ = (<MetaInterface twisted.internet.interfaces.IProtocol>,)

Methods inherited from BaseProtocol:
makeConnection(self, transport)
Make a connection to a transport and a server.
 
This sets the 'transport' attribute of this Protocol, and calls the
connectionMade() callback.

Data and other attributes inherited from BaseProtocol:
__providedBy__ = <zope.interface.declarations.Declaration object>
connected = 0
transport = None

 
Data
        reactor = <twisted.internet.selectreactor.SelectReactor instance>