= PJSUA Python Module = [[TracNav(Python_SIP/TOC)]] == Developing Python SIP Application == #develop === Concepts === #concepts ==== Asynchronous Operations ==== If you have developed applications with PJSIP you'll know about this already, but this concept probably needs to be explained a little bit here to new PJSIP users. In PJSIP, all operations that involve sending and receiving SIP messages are asynchronous, meaning that the function that invokes the operation will complete immediately, and you will be given the completion status as callbacks. Take a look for example the {{{make_call()}}} method of the [http://www.pjsip.org/python/pjsua.htm#Account Account] class. This function is used to initiate outgoing call to a destination. When this function returns successfully, it does not mean that the call has been established, but rather that the call has been '''initiated''' successfully. You will be given the report of the call completion (such as ''Ringing'' or ''Connected''/''Confirmed''' events) in the {{{on_state()}}} callback of [http://www.pjsip.org/python/pjsua.htm#CallCallback CallCallback] class. ==== Where to Start ==== The [http://www.pjsip.org/python/pjsua.htm PJSUA Python Module Reference Manual] shows quite few classes there, and it doesn't show clearly where to start. But actually the concept is quite simple, with the main classes described below. '''[http://www.pjsip.org/python/pjsua.htm#Lib Lib] class:''' :: This is the main class of the library. You need to instantiate one and exactly one of this class, and from the instance you initialize and start the library, and create other objects such as transports and accounts. '''[http://www.pjsip.org/python/pjsua.htm#Transport Transport] class:''' :: A transport more or less specifies a listening socket. You need to create one or more SIP transports before the application can send or receive SIP messages, and the transport creation will return a Transport object. There is not much use of the Transport object, except to add a local account (which is optional if you have a real account) and to display list of listening socket addresses to users if you want to. '''[http://www.pjsip.org/python/pjsua.htm#Account Account] class:''' :: An account specifies the identity of the person (or endpoint) on one side of SIP conversation. At least one Account instance needs to be created before anything else, and from the account instance you can start making/receiving calls as well as adding buddies. '''[http://www.pjsip.org/python/pjsua.htm#Call Call] class:''' :: This class is used to manipulate calls, such as to answer the call, hangup the call, put the call on hold, transfer the call, etc. '''[http://www.pjsip.org/python/pjsua.htm#Buddy Buddy] class:''' :: This class represents a remote buddy (a person, or a SIP endpoint). You can subscribe to presence status of a buddy to know whether the buddy is online/offline/etc., and you can send and receive instant messages to/from the buddy. ==== Basic Usage Pattern ==== With the methods of the main classes above, you will be able to invoke various operations quite easily. But how can we get events/notifications from these classes? It's with the callback classes. Callback classes also provide the mean to ''connect'' pjsua objects with your application's objects. The idea is like this. All the pjsua main classes above (''Lib'', ''Account'', ''Call'', and ''Buddy'') are final classes, meaning they are not intended to be subclasses or derived. Each of these classes (except ''Lib'') have their corresponding callback class ([http://www.pjsip.org/python/pjsua.htm#AccountCallback AccountCallback], [http://www.pjsip.org/python/pjsua.htm#CallCallback CallCallback], and [http://www.pjsip.org/python/pjsua.htm#BuddyCallback BuddyCallback]), and events emitted by these classes will be sent to the callback class. These callback classes are subclass-able, and in fact you must derive a class from these callback class in order to customize the processing of the events. It's probably much easier to explain with an example. First derive a class from the appropriate callback class, say [http://www.pjsip.org/python/pjsua.htm#CallCallback CallCallback] class: {{{ #!python class MyCallCallback(pjsua.CallCallback): # You can put glue attributes here. # e.g. we'll put an imaginary text control here text_ctrl = None def __init__(self, call=None): pjsua.CallCallback.__init__(self, call) def on_state(self): text_ctrl.set_text("Call state is " + self.call.info().state_text) }}} As you can see above, the primary objective of deriving a class from the callback class is to customize the processing of an event. And in your callback class, you can put your own object attributes there to connect the call object with your application objects. Then you ''install'' your callback to the Call object like this: {{{ #!python def make_call(dst_uri): my_cb = MyCallCallback(none) try: call = acc.make_call(dst_uri, cb=my_cb) except pjsua.Error, err: print 'Error making call', err return None return call }}} or using {{{set_callback()}}} method like this: {{{ #!python def make_call(dst_uri): my_cb = MyCallCallback(none) try: call = acc.make_call(dst_uri) call.set_callback(my_cb) except pjsua.Error, err: print 'Error making call', err return None return call }}} This later method is not preferred since it is possible to loose events with this method, e.g. due to the use of multi-threading, events may be emitted by the call object while the callback is not installed. It is possible to avoid loosing events this way by using library lock though, as will be explained later. I hope the snippet above will give you a bit of info on the basic pattern used by the library. More will be explained in later sections. ==== Error Handling ==== By convention, we use exceptions as means to report error, as this would make the program flows more naturally. Operations which yield error will raise [http://www.pjsip.org/python/pjsua.htm#Error pjsua.Error] exception. Here is a sample: {{{ #!python import pjsua try: call = acc.make_call('sip:buddy@example.org') except pjsua.Error, err: print 'Exception has occured:', err except: print 'Ouch..' }}} The sample above will print the full error information to stdout. If you prefer to display the error in more structured manner, the [http://www.pjsip.org/python/pjsua.htm#Error pjsua.Error] class has several members to explain the error, such as the object name that raised the error, the operation name, and the error message itself. ==== Threading and Concurrency ==== For platforms that require polling, the pjsua module provides it's own worker thread to poll pjsip, so it is not necessary to instantiate own your polling thread. Having said that the application should be prepared to have the callbacks called by different thread than the main thread. The pjsua module should be thread safe. Internally, the pjsua module actually is not re-entrant, since we found there is a deadlock somewhere when more than one threads are used. The library uses one single lock object to prevent the main thread and pjsua module worker thread from deadlocking. The {{{lib.auto_lock()}}} returns an object that automatically acquires the library lock and it will automatically release the lock when the object is destroyed. So to protect a function, the code will be like this: {{{ #!python def my_function(): # this will acquire library lock: lck = pjsua.Lib.instance().auto_lock() # and when lck is destroyed, the lock will be released }}}