def pjInit(self): """Initialize the PJSIP library. Called once by the worker thread.""" logger.info("Initializing native library") self.__ep = pj.Endpoint() # N.B.: from PJSIP's perspective, the thread that calls # libCreate() is the main thread. Combined with # ``uaConfig.mainThreadOnly``, this ensures that all PJSIP # events will be handled here, and not by any native threads. self.__ep.libCreate() self.__ep.libInit(Config.endpoint_config()) self.__ep.transportCreate(pj.PJSIP_TRANSPORT_UDP, Config.transport_config()) Config.setup_audio(self.__ep) self.__ep.libStart() logger.debug("Creating account") self.__account = AccountCallback() self.__account.create(Config.account_config()) self.__phone.dialtone = DialTonePlayer(**Config.dialtone_config()) self.__phone.recorder = CallRecorder(**Config.recorder_config()) # Make sure the library can fully start up while True: e = self.__ep.libHandleEvents( 20) # note: libHandleEvents() takes milliseconds if e == 0: break if e < 0: raise RuntimeError( "Error while initializing PJSUA2: {msg} ({errno})".format( errno=-e, msg=self.__ep.utilStrError(-e))) logger.debug("Initialization complete")
def ua_run_ua_test(): print "UA test run.." ep_cfg = pj.EpConfig() ep = pj.Endpoint() ep.libCreate() ep.libInit(ep_cfg) ep.libStart() print "************* Endpoint started ok, now shutting down... *************" ep.libDestroy()
def ua_run_log_test(): print "Logging test.." ep_cfg = pj.EpConfig() lw = MyLogWriter() ep_cfg.logConfig.writer = lw ep_cfg.logConfig.decor = ep_cfg.logConfig.decor & ~(pj.PJ_LOG_HAS_CR | pj.PJ_LOG_HAS_NEWLINE) ep = pj.Endpoint() ep.libCreate() ep.libInit(ep_cfg) ep.libDestroy()
def ua_run_ua_test(): write("UA test run.." + "\r\n") ep_cfg = pj.EpConfig() ep = pj.Endpoint() ep.libCreate() ep.libInit(ep_cfg) ep.libStart() write( "************* Endpoint started ok, now shutting down... *************" + "\r\n") ep.libDestroy()
def ua_tonegen_test(): write("UA tonegen test.." + "\r\n") ep_cfg = pj.EpConfig() ep = pj.Endpoint() ep.libCreate() ep.libInit(ep_cfg) ep.libStart() tonegen = pj.ToneGenerator() tonegen.createToneGenerator() tone = pj.ToneDesc() tone.freq1 = 400 tone.freq2 = 600 tone.on_msec = 1000 tone.off_msec = 1000 tones = pj.ToneDescVector() tones.append(tone) digit = pj.ToneDigit() digit.digit = '0' digit.on_msec = 1000 digit.off_msec = 1000 digits = pj.ToneDigitVector() digits.append(digit) adm = ep.audDevManager() spk = adm.getPlaybackDevMedia() tonegen.play(tones, True) tonegen.startTransmit(spk) time.sleep(5) tonegen.stop() tonegen.playDigits(digits, True) time.sleep(5) dm = tonegen.getDigitMap() write(dm[0].digit + "\r\n") dm[0].freq1 = 400 dm[0].freq2 = 600 tonegen.setDigitMap(dm) tonegen.stop() tonegen.playDigits(digits, True) time.sleep(5) tonegen = None ep.libDestroy()
def ua_run_test_exception(): print "Exception test.." ep = pj.Endpoint() ep.libCreate() got_exception = False try: ep.natDetectType() except pj.Error, e: got_exception = True print " Got exception: status=%u, reason=%s,\n title=%s,\n srcFile=%s, srcLine=%d" % \ (e.status, e.reason, e.title, e.srcFile, e.srcLine) assert e.status == 370050 assert e.reason.find("PJNATH_ESTUNINSERVER") >= 0 assert e.title == "pjsua_detect_nat_type()"
def __init__(self, sipphone: glue.Pjsua2) -> None: self.__phone = sipphone self.__config = doorpi.INSTANCE.config.view("sipphone") self.hangup = False LOGGER.info("Initializing native library") self.__ep = pj.Endpoint() # N.B.: from PJSIP's perspective, the thread that calls # libCreate() is the main thread. Combined with # ``uaConfig.mainThreadOnly``, this ensures that all PJSIP # events will be handled here, and not by any native threads. self.__ep.libCreate() self.__ep.libInit(config.endpoint_config()) self.__ep.transportCreate( pj.PJSIP_TRANSPORT_UDP, config.transport_config() ) config.setup_audio(self.__ep) self.__ep.libStart() LOGGER.debug("Creating account") self.__account = AccountCallback() self.__account.create(config.account_config()) self.__phone.dialtone = DialTonePlayer(**config.dialtone_config()) self.__phone.recorder = CallRecorder(**config.recorder_config()) # Make sure the library can fully start up while True: # note: libHandleEvents() takes milliseconds num_ev = self.__ep.libHandleEvents(20) if num_ev == 0: break if num_ev < 0: raise RuntimeError( "Error while initializing PJSUA2: {msg} ({errno})".format( errno=-num_ev, msg=self.__ep.utilStrError(-num_ev) ) ) # register tick actions eh = doorpi.INSTANCE.event_handler eh.register_action( "OnTimeRapidTick", CheckAction(self.handleNativeEvents) ) eh.register_action("OnTimeTick", CheckAction(self.checkHangupAll)) eh.register_action("OnTimeTick", CheckAction(self.checkCallTime)) eh.register_action("OnTimeRapidTick", CheckAction(self.createCalls)) eh.fire_event_sync("OnSIPPhoneStart", EVENT_SOURCE) LOGGER.debug("Initialization complete")
def ua_run_test_exception(): write("Exception test.." + "\r\n") ep = pj.Endpoint() ep.libCreate() got_exception = False try: ep.natDetectType() except pj.Error as e: #t, e = sys.exc_info()[:2] got_exception = True write(" Got exception: status=%u, reason=%s,\n title=%s,\n srcFile=%s, srcLine=%d" % \ (e.status, e.reason, e.title, e.srcFile, e.srcLine) + "\r\n") assert e.status == 370050 assert e.reason.find("PJNATH_ESTUNINSERVER") >= 0 assert e.title == "pjsua_detect_nat_type()" assert got_exception
def _configureEndpoint(self): print("configuring endpoint") # UaConfig self.epConfig.uaConfig.maxCalls = 4 #default is 4, max is 32 # self.epConfig.uaConfig.threadCnt = 1 # self.epConfig.uaConfig.mainThreadOnly = False self.epConfig.uaConfig.userAgent = "mkBusy UA {}".format(pj.Endpoint().libVersion().full) # LogConfig # self.epConfig.logConfig.msgLogging = 1 # self.epConfig.logConfig.level = 5 # self.epConfig.logConfig.consoleLevel = 5 # self.epConfig.logConfig.writer = self.pjLogWriter # MediaConfig self.epConfig.medConfig.clockRate = 16000
def pjsua2_test(): # Create and initialize the library global ep ep_cfg = pj.EpConfig() ep_cfg.uaConfig.threadCnt = 0 ep_cfg.uaConfig.mainThreadOnly = False ep = pj.Endpoint() ep.libCreate() ep.libInit(ep_cfg) # Create SIP transport. Error handling sample is shown sipTpConfig = pj.TransportConfig() sipTpConfig.port = 12345 tp = ep.transportCreate(pj.PJSIP_TRANSPORT_UDP, sipTpConfig) # Start the library ep.libStart() acfg = pj.AccountConfig() acfg.idUri = "sip:192.168.1.11:12345" # Create the account acc = Account(ep) acc.create(acfg) #Get device list and collect device IDs of two virtual devices created ep.audDevManager().refreshDevs() devList = ep.audDevManager().enumDev() fullRecorderDeviceID = 0 devID = 0 for dev in devList: print(dev.name) if (dev.name == "FullRecorder"): acc.fullRecorderDeviceID = devID if (dev.name == "CallerVoice"): acc.callerVoiceRecorderDeviceID = devID ep.audDevManager().setPlaybackDev(acc.callerVoiceRecorderDeviceID) #acc.amr=ep.audDevManager().getPlaybackDevMedia() acc.amr = pj.AudioMediaRecorder.typecastFromAudioMedia( ep.audDevManager().getPlaybackDevMedia()) acc.amr.createRecorder(file_name="123.wav") ep.mediaAdd(acc.amr) devID = devID + 1 ep.audDevManager().setPlaybackDev(acc.fullRecorderDeviceID) while True: ep.libHandleEvents(10) if (acc.acceptCall == True): acc.acceptCall = False call_prm = pj.CallOpParam() call_prm.statusCode = 200 acc.c.answer(call_prm) if (acc.c.canConnectPlayer == True and acc.c.am != None): acc.c.canConnectPlayer = False player = pj.AudioMediaPlayer() #Play welcome message fn = u'/PJSUA2/example/welcomeFull.wav' player.createPlayer(fn, pj.PJMEDIA_FILE_NO_LOOP) # This will connect the sound device/mic to the call audio media player.startTransmit(acc.c.am) #player.startTransmit( ep.audDevManager().getPlaybackDevMedia()); #ep.audDevManager().setPlaybackDev(self.acc.callerVoiceRecorderDeviceID); #player.startTransmit(acc.amr) """ ep.audDevManager().refreshDevs(); devList=ep.audDevManager().enumDev() devID=0 for dev in devList: print(dev.name) """ ep.libDestroy()
def pjsua2_test(): global ep # Create and initialize the library ep_cfg = pj.EpConfig() ep_cfg.logConfig.level = 5; ep = pj.Endpoint() ep.libCreate() ep.libInit(ep_cfg) ep.audDevManager().setNullDev() for codec in ep.codecEnum2(): priority = 0 if 'PCMA/8000' in codec.codecId: priority = 255 ep.codecSetPriority(codec.codecId, priority) # Create SIP transport. Error handling sample is shown sipTpConfig = pj.TransportConfig(); sipTpConfig.port = 15060; ep.transportCreate(pj.PJSIP_TRANSPORT_UDP, sipTpConfig); # Start the library ep.libStart(); acfg = pj.AccountConfig(); acfg.idUri = "sip:1002@asterisk"; acfg.regConfig.registrarUri = "sip:asterisk"; cred = pj.AuthCredInfo("digest", "*", "1002", 0, "12345"); acfg.sipConfig.authCreds.append( cred ) # Create the account acc = pj.Account() acc.create(acfg) # Here we don't have anything else to do.. while not acc.getInfo().regIsActive: print('========== registering') time.sleep(0.1) if acc.getInfo().regStatus != 200: print('++++++++++++++++++') print('no registration') return call = Call(acc) prm = pj.CallOpParam(True) prm.opt.audioCount = 1 prm.opt.videoCount = 0 call.makeCall("sip:8080@asterisk", prm) while call.getInfo().state != pj.PJSIP_INV_STATE_CONFIRMED: print(call.getInfo().stateText) time.sleep(0.1) f = open('output.lpcm', 'wb') f2 = open('hw.raw', 'rb') hwraw = f2.read() n = 320 [call.putFrame(hwraw[i:i+320]) for i in range(0, len(hwraw), n)] for i in range(10): time.sleep(1) data = call.getFrames() if data: f.write(data) f.close() prm = pj.CallOpParam() call.hangup(prm) # Destroy the library ep.hangupAllCalls() print('unregistering') acc.delete()
def startup(self): self._logger.debug("entered startup()") ep_cfg = pjsua2.EpConfig() ep_cfg.uaConfig.mainThreadOnly = True ep_cfg.uaConfig.threadCnt = 0 version = pkg_resources.require("gtkapplication")[0].version ep_cfg.uaConfig.userAgent = "pyphone-{0}".format(version) self._logger.debug('ep_cfg.uaConfig.userAgent = %s', ep_cfg.uaConfig.userAgent) ep_cfg.logConfig.msgLogging = 1 ep_cfg.logConfig.level = 5 ep_cfg.logConfig.consoleLevel = 5 decor = pjsua2.PJ_LOG_HAS_YEAR | pjsua2.PJ_LOG_HAS_MONTH | pjsua2.PJ_LOG_HAS_DAY_OF_MON | pjsua2.PJ_LOG_HAS_TIME | pjsua2.PJ_LOG_HAS_MICRO_SEC | pjsua2.PJ_LOG_HAS_SENDER | pjsua2.PJ_LOG_HAS_NEWLINE | pjsua2.PJ_LOG_HAS_SPACE | pjsua2.PJ_LOG_HAS_THREAD_SWC | pjsua2.PJ_LOG_HAS_INDENT self._logger.debug('decor = %s', decor) ep_cfg.logConfig.decor = decor ep_cfg.logConfig.filename = "logs/pjsip.log" ep_cfg.logConfig.fileFlags = pjsua2.PJ_O_APPEND pjsip_log_writer = gtkapplication.api.sip.logger.PjLogger() ep_cfg.logConfig.writer = pjsip_log_writer sip_container = gtkapplication.api.sip.pjsip_container.sip_container sip_container.pjsip_log_writer = pjsip_log_writer sip_container.ep = pjsua2.Endpoint() ep = sip_container.ep ep.libCreate() ep.libInit(ep_cfg) pjsip_version = ep.libVersion().full self._logger.debug('pjsip_version = %s', pjsip_version) sip_udp_tranport_config = pjsua2.TransportConfig() sip_udp_tranport_config.port = 5060 sip_udp_tranport_config.enabled = 1 ep.transportCreate(pjsua2.PJSIP_TRANSPORT_UDP, sip_udp_tranport_config) self._logger.debug("transport created") acfg = pjsua2.AccountConfig() acfg.idUri = gtkapplication.data.config_data.PROFILE_DATA['sip_uri'] acfg.regConfig.registrarUri = gtkapplication.data.config_data.PROFILE_DATA[ 'sip_registrar_uri'] acfg.regConfig.registerOnAdd = True acfg.regConfig.timeoutSec = 60 acfg.regConfig.retryIntervalSec = 60 aci = pjsua2.AuthCredInfo() aci.scheme = "digest" aci.realm = "*" aci.username = gtkapplication.data.config_data.PROFILE_DATA[ 'sip_username'] aci.dataType = 0 aci.data = gtkapplication.data.config_data.PROFILE_DATA['sip_password'] aciv = pjsua2.AuthCredInfoVector() aciv.append(aci) acfg.sipConfig.authCreds = aciv sip_container.sip_account_list.append( gtkapplication.api.sip.account.Account(acfg)) sip_account = sip_container.sip_account_list[0] sip_account.cfg = acfg sip_account.create(acfg, True) presence_status = pjsua2.PresenceStatus() presence_status.status = pjsua2.PJSUA_BUDDY_STATUS_ONLINE sip_account.setOnlineStatus(presence_status) self._logger.debug("sip account created: %r", sip_account) bcfg = pjsua2.BuddyConfig() bcfg.uri = gtkapplication.data.config_data.PROFILE_DATA[ 'sip_buddy_uri'] bcfg.subscribe = True buddy = gtkapplication.api.sip.buddy.Buddy(sip_account) buddy.create(sip_account, bcfg) sip_account.server_buddy = buddy contact_manager = gtkapplication.api.contacts.contact_manager.ContactManager( ) contact_manager.create_free_buddy_contacts(sip_account) acfg = pjsua2.AccountConfig() acfg.idUri = gtkapplication.data.config_data.PROFILE_DATA[ 'twilio_sip_uri'] acfg.regConfig.registrarUri = gtkapplication.data.config_data.PROFILE_DATA[ 'twilio_sip_registrar_uri'] self._logger.debug("twilio sip_uri = '%s', registrar = %s", acfg.idUri, acfg.regConfig.registrarUri) acfg.regConfig.registerOnAdd = True acfg.regConfig.timeoutSec = 60 acfg.regConfig.retryIntervalSec = 60 aci = pjsua2.AuthCredInfo() aci.scheme = "digest" aci.realm = "*" aci.username = gtkapplication.data.config_data.PROFILE_DATA[ 'twilio_sip_username'] aci.dataType = 0 aci.data = gtkapplication.data.config_data.PROFILE_DATA[ 'twilio_sip_password'] aciv = pjsua2.AuthCredInfoVector() aciv.append(aci) acfg.sipConfig.authCreds = aciv sip_container.sip_account_list.append( gtkapplication.api.sip.account.Account(acfg)) twilio_sip_account = sip_container.sip_account_list[1] twilio_sip_account.cfg = acfg twilio_sip_account.create(acfg, True) presence_status = pjsua2.PresenceStatus() presence_status.status = pjsua2.PJSUA_BUDDY_STATUS_ONLINE twilio_sip_account.setOnlineStatus(presence_status) ep.libStart() self._logger.debug("after libStart()") tone_generator = pjsua2.ToneGenerator() tone_generator.createToneGenerator(16000, 1) sip_container.tone_generator = tone_generator self._logger.debug("tone generator created") self._source_tag = GObject.timeout_add(50, self.poll_pjsip_events_timer, False) self._logger.debug("timer started source_tag is %s", self._source_tag) self._logger.info("timer started")