« Previous - Version 13/14 (diff) - Next » - Current version
Tijmen de Mes, 04/19/2012 04:07 pm


Sample Code

This sample code implements a minimalist VoIP client. After installing the SDK, copy and paste this code into your Python interpreter to run it.

 1#/usr/bin/python
 2
 3from application.notification import NotificationCenter
 4
 5from sipsimple.account import AccountManager
 6from sipsimple.application import SIPApplication
 7from sipsimple.core import SIPURI, ToHeader
 8from sipsimple.lookup import DNSLookup, DNSLookupError
 9from sipsimple.storage import FileStorage
10from sipsimple.session import Session
11from sipsimple.streams import AudioStream
12from sipsimple.threading.green import run_in_green_thread
13
14from threading import Event
15
16class SimpleCallApplication(SIPApplication):
17
18    def __init__(self):
19        SIPApplication.__init__(self)
20        self.ended = Event()
21        self.callee = None
22        self.session = None
23        notification_center = NotificationCenter()
24        notification_center.add_observer(self)
25
26    def call(self, callee):
27        self.callee = callee
28        self.start(FileStorage('config'))
29
30    @run_in_green_thread
31    def _NH_SIPApplicationDidStart(self, notification):
32        self.callee = ToHeader(SIPURI.parse(self.callee))
33        try:
34            routes = DNSLookup().lookup_sip_proxy(self.callee.uri, ['udp']).wait()
35        except DNSLookupError, e:
36            print 'DNS lookup failed: %s' % str(e)
37        else:
38            account = AccountManager().default_account
39            self.session = Session(account)
40            self.session.connect(self.callee, routes, [AudioStream(account)])
41
42    def _NH_SIPSessionGotRingIndication(self, notification):
43        print 'Ringing!'
44
45    def _NH_SIPSessionDidStart(self, notification):
46        audio_stream = notification.data.streams[0]
47        print 'Audio session established using "%s" codec at %sHz' % (audio_stream.codec, audio_stream.sample_rate)
48
49    def _NH_SIPSessionDidFail(self, notification):
50        print 'Failed to connect'
51        self.stop()
52
53    def _NH_SIPSessionDidEnd(self, notification):
54        print 'Session ended'
55        self.stop()
56
57    def _NH_SIPApplicationDidEnd(self, notification):
58        self.ended.set()
59
60# place an audio call to the specified SIP URI in user@domain format
61target_uri="sip:3333@sip2sip.info" 
62application = SimpleCallApplication()
63application.call(target_uri)
64print "Placing call to %s, press Enter to quit the program" % target_uri
65raw_input()
66application.session.end()
67application.ended.wait()