starpy.manager
index
/usr/lib/python2.5/site-packages/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
twisted.internet.error

 
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)
clientConnectionFailed(self, connector, reason)
Connection failed, report to our callers
login(self, ip='localhost', port=5038, timeout=5)
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 at 0x84c108c>
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:
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>
__providedBy__ = <zope.interface.declarations.Declaration object at 0x82bbb6c>
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)
agentLogoff(self, agent, soft)
Logs off the specified agent for the queue system.
agents(self)
Retrieve agents information
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
dbGet(self, family, key)
This action retrieves a value from the AstDB database
dbPut(self, family, key, value)
Sets a key value in the AstDB database
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
extensionState(self, exten, context)
This command reports the extension state for the given extension. If the extension has a hint, this will report the status of the device connected to the extension
 
The following are the possible extension states:
 
-2    Extension removed
-1    Extension hint not found
 0    Idle
 1    In use
 2    Busy
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.
getConfig(self, filename)
Retrieves the data from an Asterisk configuration file
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
meetmeMute(self, meetme, usernum)
Mute a usernum in a given meetme
meetmeUnmute(self, meetme, usernum)
Unmute a specified user in a given meetme
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, variable={}, async=False)
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
variable -- variables associated to the call
async -- make the origination asynchronous
park(self, channel, channel2, timeout)
Park channel
parkedCalls(self)
Retrieve set of parked calls via multi-event callback
pauseMonitor(self, channel)
Temporarily stop recording the channel
ping(self)
Check to see if the manager is alive...
playDTMF(self, channel, digit)
Play DTMF on a given channel
queueAdd(self, queue, interface, penalty=0, paused=True)
Add given interface to named queue
queuePause(self, queue, interface, paused=True)
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
sipShowPeers(self, peer)
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
unpauseMonitor(self, channel)
Resume recording a channel
updateConfig(self, srcfile, dstfile, reload, headers={})
userEvent(self, event, **headers)
Sends an arbitrary event to the Asterisk Manager Interface.
waitEvent(self, timeout)
Waits for an event to occur
 
After calling this action, Asterisk will send you a Success response as soon as another event is queued by the AMI
zapDNDoff(self, channel)
Toggles the do not disturb state on the specified Zap channel to off
zapDNDon(self, channel)
Toggles the do not disturb state on the specified Zap channel to on
zapDialOffhook(self, channel, number)
Dials the specified number on the Zap channel while the phone is off-hook
zapHangup(self, channel)
Hangs up the specified Zap channel
zapRestart(self, channel)
Completly restarts the Zaptel channels, terminating any calls in progress
zapShowChannels(self)
List all zap channels
zapTransfer(self, channel)
Transfers zap 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>

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 at 0x82bbb6c>
connected = 0
transport = None

 
Data
        reactor = <twisted.internet.selectreactor.SelectReactor object at 0x83fdd0c>