Beispiel #1
0
def endpoint_config() -> pj.EpConfig:
    """Creates the PJSUA2 Endpoint configuration object."""
    LOGGER.trace("Creating endpoint config")
    ep_cfg = pj.EpConfig()
    ep_cfg.uaConfig.maxCalls = doorpi.INSTANCE.config["sipphone.max_calls"]
    stun_server = doorpi.INSTANCE.config["sipphone.stunserver"]
    if stun_server:
        ep_cfg.uaConfig.stunServer.append(stun_server)
    # Ensure PJSIP callbacks will be handled by our python worker thread
    ep_cfg.uaConfig.threadCnt = 0
    ep_cfg.uaConfig.mainThreadOnly = True

    ep_cfg.logConfig.msgLogging = False  # Don't log full SIP messages
    ep_cfg.logConfig.level = 5
    ep_cfg.logConfig.consoleLevel = 4
    ep_cfg.logConfig.decor = False

    native_logger = ".".join(__name__.split(".")[:-1] + ["native"])
    logwriter = DoorPiLogWriter(
        cast(doorpi.DoorPiLogger, logging.getLogger(native_logger))
    )
    ep_cfg.logConfig.writer = logwriter
    # Bind the LogWriter's lifetime to the sipphone object, so that
    # it won't be garbage-collected prematurely.
    sp: glue.Pjsua2 = doorpi.INSTANCE.sipphone  # type: ignore
    sp._logwriter = logwriter  # pylint: disable=protected-access

    return ep_cfg
Beispiel #2
0
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()
Beispiel #3
0
Datei: test.py Projekt: ctier/cc
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()
Beispiel #4
0
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()
Beispiel #5
0
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()
Beispiel #6
0
    def __init__(self):
        print("Init config")

        self.epConfig = pj.EpConfig()
        self.udp = SipTransportConfig(pj.PJSIP_TRANSPORT_UDP, 5060, True)

        print("transport created")

        self.accounts = []
        self.accounts.append(self._test_account())

        print("test account configured")

        self._configureEndpoint()
Beispiel #7
0
    def __init__(self, logger):
        logger.debug("Init config")

        self.epConfig = pj.EpConfig()
        self.udp = SipTransportConfig(pj.PJSIP_TRANSPORT_UDP, 5060, True)

        logger.debug("transport created")

        self.accounts = []
        self.accounts.append(self._test_account())

        logger.debug("test account configured")

        self.logger = logger
        self.pjLogWriter = PJLogWriter()
        self._configureEndpoint()
Beispiel #8
0
    def loadFile(self, file):
        json = pj.JsonDocument()
        json.loadFile(file)
        root = json.getRootContainer()
        self.epConfig = pj.EpConfig()
        self.epConfig.readObject(root)

        tp_node = root.readArray("transports")
        self.udp.readObject(tp_node)
        self.tcp.readObject(tp_node)
        if tp_node.hasUnread():
            self.tls.readObject(tp_node)

        acc_node = root.readArray("accounts")
        while acc_node.hasUnread():
            acfg = AccConfig()
            acfg.readObject(acc_node)
            self.accounts.append(acfg)
Beispiel #9
0
    def endpoint_config() -> pj.EpConfig:
        logger.trace("Creating endpoint config")
        ep_cfg = pj.EpConfig()
        ep_cfg.uaConfig.maxCalls = conf.get_int(SIPPHONE_SECTION, "max_calls",
                                                8)
        stun_server = conf.get_string(SIPPHONE_SECTION, "stun_server", "")
        if stun_server:
            ep_cfg.uaConfig.stunServer.append(stun_server)
        # Ensure PJSIP callbacks will be handled by our python worker thread
        ep_cfg.uaConfig.threadCnt = 0
        ep_cfg.uaConfig.mainThreadOnly = True

        ep_cfg.logConfig.msgLogging = False  # Don't log full SIP messages
        ep_cfg.logConfig.level = 5
        ep_cfg.logConfig.consoleLevel = 4
        ep_cfg.logConfig.decor = False

        logwriter = DoorPiLogWriter(logger.getChild("native"))
        ep_cfg.logConfig.writer = logwriter
        # Bind the LogWriter's lifetime to the sipphone object, so that
        # it won't be garbage-collected prematurely.
        DoorPi().sipphone.__logwriter = logwriter

        return ep_cfg
Beispiel #10
0
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()
Beispiel #11
0
 def __init__(self):
     self.epConfig = pj.EpConfig()  # pj.EpConfig()
     self.udp = SipTransportConfig(pj.PJSIP_TRANSPORT_UDP, True)
     self.tcp = SipTransportConfig(pj.PJSIP_TRANSPORT_TCP, True)
     self.tls = SipTransportConfig(pj.PJSIP_TRANSPORT_TLS, False)
     self.accounts = []  # Array of AccConfig
Beispiel #12
0
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()
Beispiel #13
0
    def __init__(self):
        super().__init__()
        """
        Initialize PJSUA2
        """
        self.ep = Endpoint()
        self.ep.libCreate()

        self.ep_cfg = pj.EpConfig()
        # self.ep_cfg.uaConfig.threadCnt = 0
        # self.ep_cfg.uaConfig.mainThreadOnly = True
        self.ep_cfg.logConfig.level = 1

        self.ep.libInit(self.ep_cfg)

        self.ts_cfg = pj.TransportConfig()
        self.ep.transportCreate(pj.PJSIP_TRANSPORT_UDP, self.ts_cfg)
        self.ep.libStart()
        """
        Initialize Account
        """
        self.acc = None
        self.domain = DEFAULT_DOMAIN

        self.buddy_list = {}
        self.chat_list = {}
        """
        Initialize UI
        """
        self.title('SIP Client')
        self.resizable(width=False, height=False)
        self.geometry('+{}+{}'.format(int(self.winfo_screenwidth() / 2),
                                      int(self.winfo_screenheight() / 2)))

        self.buddy = tk.Entry(self, font=FONT_CONTENT, width=30)
        self.buddy.grid(row=0, column=0, columnspan=3, padx=10, pady=10)
        self.buddy.bind('<Return>', self._add_buddy)

        self.buddy_view = ttk.Treeview(self,
                                       column=['1', '2'],
                                       show='headings',
                                       selectmode='browse')
        self.buddy_view.column('1', width=80, anchor='center')
        self.buddy_view.column('2', width=200, anchor='center')
        self.buddy_view.heading('1', text='Buddies')
        self.buddy_view.heading('2', text='Status')
        self.buddy_view.grid(row=1, column=0, columnspan=3, padx=10, pady=10)
        self.buddy_view.bind('<Double-Button-1>', self._create_chat)
        self.buddy_view.bind('<BackSpace>', self._delete_buddy)

        tk.Button(self,
                  text='Logout',
                  font=FONT_CONTENT,
                  width=8,
                  command=self._login).grid(row=2, column=0, padx=10, pady=10)
        tk.Button(self,
                  text='Exit',
                  font=FONT_CONTENT,
                  width=8,
                  command=self._exit).grid(row=2, column=2, padx=10, pady=10)

        self._login()

        # self._on_timer()

        self.mainloop()
Beispiel #14
0
 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")