def _create_endpoint(self, account_id: str, registration_uri: str, username: str, password: str): class MyAccountCallback(pjsua.AccountCallback): sem = None def __init__(self, account=None): pjsua.AccountCallback.__init__(self, account) def wait(self): self.sem = threading.Semaphore(0) self.sem.acquire() def on_reg_state(self): if self.sem: if self.account.info().reg_status >= 200: self.sem.release() acc_cfg = pjsua.AccountConfig() acc_cfg.id = account_id acc_cfg.reg_uri = registration_uri acc_cfg.auth_cred = [pjsua.AuthCred("*", username, password)] acc_cb = MyAccountCallback() acc = self.lib.create_account(acc_cfg, cb=acc_cb) print("\n") print('Registering %s' % registration_uri) acc_cb.wait() reg_status = acc.info().reg_status reg_reason = acc.info().reg_reason if reg_status != 200: print('Registration failed (%s) status= %s (%s)' % (registration_uri, reg_status, reg_reason)) exit(1) print('Registration completed (%s) status= %s (%s)' % (registration_uri, reg_status, reg_reason)) return acc
def initAccounts(self): for cc_code, acc in self.accounts.items(): #sipscc = pj.AccountConfig(str(acc['domain']), str(acc['username']), str(acc['password']), # str(acc['domain'])) sipscc = pj.AccountConfig() sipscc.id = str(acc['domain']) + "<sip:" + str( acc['username']) + "@" + str(acc['domain']) + ">" sipscc.domain = str(acc['domain']) sipscc.auth_cred = [ pj.AuthCred("*", str(acc['username']), str(acc['password'])) ] sipscc.reg_uri = "sip:" + str(acc['domain']) if acc.has_key('proxy'): sipscc.proxy = [str(acc['proxy'][0])] if acc.has_key('srtp'): sipscc.use_srtp = str(acc['srtp']) if acc.has_key('srtp_sig'): sipscc.srtp_secure_signaling = str(acc['srtp_sig']) if acc.has_key('auth_algo'): sipscc.auth_initial_algorithm = str(acc['auth_algo']) if acc['transport'] == 'UDP': transport_type = pj.TransportType.UDP transport = pj.Lib.instance().create_transport(transport_type) sipscc.transport_id = transport._id acc['transport_object'] = transport else: transport_type = pj.TransportType.TCP #TCP transport is already created in initLib function of SipPhone class acc['acc_config'] = sipscc
def register(self, login, server, password, realm="*"): config = pj.AccountConfig() config.id = "sip:" + login + "@" + server config.reg_uri = "sip:" + server + ";transport=tcp" config.auth_cred = [pj.AuthCred(realm, login, password)] account_callback = NoopAccountCallback() self.account = self.pjsip.create_account(config, cb=account_callback) account_callback.wait()
def create_AccountConfig(): logger.debug("create_AccountConfig") # Doc: http://www.pjsip.org/python/pjsua.htm#AccountConfig server = conf.get(SIPPHONE_SECTION, "server") username = conf.get(SIPPHONE_SECTION, "username") password = conf.get(SIPPHONE_SECTION, "password") realm = conf.get(SIPPHONE_SECTION, "realm") AccountConfig = pj.AccountConfig() AccountConfig.id = "sip:" + username + "@" + server AccountConfig.reg_uri = "sip:" + server AccountConfig.auth_cred = [pj.AuthCred(realm, username, password)] AccountConfig.allow_contact_rewrite = conf.get_bool( SIPPHONE_SECTION, 'account.allow_contact_rewrite', 0) AccountConfig.reg_timeout = conf.get_int(SIPPHONE_SECTION, 'account.reg_timeout', 10) return AccountConfig
def main(argv): global broker global pj global lib global args app_name = "SIP2MQTT" parser = argparse.ArgumentParser( description= 'A SIP monitoring tool that publishes incoming calls with CallerID to an MQTT channel' ) requiredNamed = parser.add_argument_group('required named arguments') requiredNamed.add_argument("-a", "--mqtt_domain", type=str, required=True, help="the MQTT broker domain string", default=os.environ.get('MQTT_DOMAIN', None)) requiredNamed.add_argument("-t", "--mqtt_port", type=int, required=True, help="the MQTT broker port number", default=os.environ.get('MQTT_PORT', None)) parser.add_argument("--mqtt_keepalive", type=int, required=False, help="the MQTT broker keep alive in seconds", default=60) parser.add_argument("--mqtt_protocol", type=str, required=False, help="the MQTT broker protocol", default="MQTTv311", choices=['MQTTv31', 'MQTTv311']) requiredNamed.add_argument("-u", "--mqtt_username", type=str, required=True, help="the MQTT broker username", default=os.environ.get('MQTT_USERNAME', None)) requiredNamed.add_argument("-p", "--mqtt_password", type=str, required=False, help="the MQTT broker password", default=os.environ.get('MQTT_PASSWORD', None)) parser.add_argument("--mqtt_topic", type=str, required=False, help="the MQTT broker topic", default=os.environ.get('MQTT_TOPIC', "home/sip")) requiredNamed.add_argument("-d", "--sip_domain", type=str, required=True, help="the SIP domain", default=os.environ.get('SIP_DOMAIN', None)) parser.add_argument("--sip_port", type=int, required=False, help="the SIP transport port number", default=os.environ.get('SIP_PORT', 5060)) requiredNamed.add_argument("-n", "--sip_username", type=str, required=True, help="the SIP username", default=os.environ.get('SIP_USERNAME', None)) requiredNamed.add_argument("-s", "--sip_password", type=str, required=False, help="the SIP password", default=os.environ.get('SIP_PASSWORD', None)) parser.add_argument("--sip_display", type=str, required=False, help="the SIP user display name", default=app_name) parser.add_argument("--log_level", type=int, required=False, help="the application log level", default=3, choices=[0, 1, 2, 3]) parser.add_argument("-v", "--verbosity", action="count", help="increase output verbosity", default=3) args = parser.parse_args() log_level = logging.INFO #Deault logging level if args.verbosity == 1: log_level = logging.ERROR elif args.verbosity == 2: log_level = logging.WARN elif args.verbosity == 3: log_level = logging.INFO elif args.verbosity >= 4: log_level = logging.DEBUG # Configure logging # logging.basicConfig(filename="sip2mqtt.log", format="%(asctime)s - %(levelname)s - %(message)s", # datefmt="%m/%d/%Y %I:%M:%S %p", level=log_level) root = logging.getLogger() root.setLevel(log_level) # ch = logging.StreamHandler(sys.stdout) # ch.setLevel(log_level) # formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # ch.setFormatter(formatter) # root.addHandler(ch) # A more docker-friendly approach is to output to stdout logging.basicConfig(stream=sys.stdout, format="%(asctime)s - %(levelname)s - %(message)s", datefmt="%m/%d/%Y %I:%M:%S %p", level=log_level) # Log startup messages and our configuration parameters logging.info("------------------------") logging.info("Starting up...") logging.info("--- MQTT Broker Configuration ---") logging.info("Domain: " + args.mqtt_domain) logging.info("Port: " + str(args.mqtt_port)) logging.info("Protocol: " + args.mqtt_protocol) logging.info("Username: "******"Keepalive Interval: " + str(args.mqtt_keepalive)) logging.info("Status Topic: " + args.mqtt_topic) logging.info("--- SIP Configuration ---") logging.info("Domain: " + args.sip_domain) logging.info("Username: "******"DisplayName: " + args.sip_display) try: # Handle mqtt connection and callbacks broker = mqtt.Client(client_id="", clean_session=True, userdata=None, protocol=eval("mqtt." + args.mqtt_protocol)) broker.username_pw_set(args.mqtt_username, password=args.mqtt_password) broker.on_connect = mqtt_connect #broker.on_message = mqtt_message #don't need this callback for now broker.connect(args.mqtt_domain, args.mqtt_port, args.mqtt_keepalive) # Create library instance of Lib class lib = pj.Lib() ua = pj.UAConfig() ua.user_agent = app_name mc = pj.MediaConfig() mc.clock_rate = 8000 lib.init(ua_cfg=ua, log_cfg=pj.LogConfig(level=args.verbosity, callback=None), media_cfg=mc) lib.create_transport(pj.TransportType.UDP, pj.TransportConfig(args.sip_port)) lib.set_null_snd_dev() lib.start() acc_cfg = pj.AccountConfig() acc_cfg.id = "sip:" + args.sip_username + "@" + args.sip_domain acc_cfg.reg_uri = "sip:" + args.sip_domain acc_cfg.auth_cred = [ pj.AuthCred(args.sip_domain, args.sip_username, args.sip_password) ] acc_cfg.allow_contact_rewrite = False acc = lib.create_account(acc_cfg) acc_cb = SMAccountCallback(acc) acc.set_callback(acc_cb) logging.info("-- Registration Complete --") logging.info('SIP: Status = ' + str(acc.info().reg_status) + ' (' + acc.info().reg_reason + ')') except pj.Error, e: logging.critical(("Exception: " + str(e))) lib.destroy() sys.exit(1)
lib.set_null_snd_dev() # Create UDP transport which listens to any available port transport = lib.create_transport(pj.TransportType.UDP, pj.TransportConfig(VOIP_SERVER_PORT)) RECORDING = True lib.start() # configure client account acc_cfg = pj.AccountConfig() acc_cfg.id = "sip:" + SIP_CALLER_ID + "@" + VOIP_SERVER acc_cfg.reg_uri = "sip:" + VOIP_SERVER acc_cfg.proxy = ["sip:" + VOIP_SERVER] acc_cfg.auth_cred = [ pj.AuthCred(VOIP_SERVER, SIP_CALLER_ID, SIP_CALLER_PASSWORD) ] acc = lib.create_account(acc_cfg) acc_cb = MyAccountCallback(acc) acc.set_callback(acc_cb) acc_cb.wait() print "\n" print "Registration complete, status=", acc.info( ).reg_status, "(" + acc.info().reg_reason + ")" print "destination - (sip:xxx@host):" dst = "sip:" + SIP_DESTINATION_NUMBER + "@" + VOIP_SERVER # Make call # for i in range(0, PARALLEL_CALLS):
realm = "asterisk" # username = raw_input("Auth Username [6003]: ") if ((username) and len(username) > 0): pass else: username = "******" # passwd = raw_input("Auth Password [**********]: ") if ((passwd) and len(passwd) > 0): pass else: passwd = "**********" print "---------------------------------------------------------------------" acc_cfg.auth_cred = [pj.AuthCred(realm, username, passwd)] acc_cb = MyAccountCallback() acc = lib.create_account(acc_cfg, cb=acc_cb) acc_cb.wait() # Conditions are not correct, because when "IP address change detected for account", all other accounts is Forbidden if ((str(acc.info().reg_status) == "200") or (str(acc.info().reg_status) == "403")): succeed = 1 else: print "" print "Registration failed, status=", acc.info().reg_status, \ "(" + acc.info().reg_reason + ")" print "" print "Please try again !"
#print "port", transport.info().port, "\n" host = "186.209.79.48" # Start the library lib.start() # for i in range(1, 100): ramal = sys.argv[1] print ramal senha_ramal = "teste" + str(ramal) acc_cfg = pj.AccountConfig() acc_cfg.id = "sip:" + str(ramal) + "@" + host acc_cfg.reg_uri = "sip:" + host acc_cfg.auth_cred = [pj.AuthCred("*", str(ramal), senha_ramal)] acc_cb = MyAccountCallback() # Create local account acc = lib.create_account(acc_cfg, cb=acc_cb) time.sleep(1) my_sip_uri = "sip:" + transport.info().host + ":" + str( transport.info().port) while True: time.sleep(5) # Menu loop # while True: # print "My SIP URI is", my_sip_uri
# Create UDP transport which listens to any available port transport = lib.create_transport(pj.TransportType.UDP, pj.TransportConfig(0)) print "\nListening on", transport.info().host, print "port", transport.info().port, "\n" # Start the library lib.start() # Create local account acc_cfg = pj.AccountConfig() acc_cfg.id = "sip:[email protected]" acc_cfg.reg_uri = "sip:uphreak.com" acc_cfg.proxy = [ "sip:uphreak.com;lr" ] acc_cfg.auth_cred = [ pj.AuthCred("*", "alice", "secretpassword") ] acc_cb = MyAccountCallback() acc = lib.create_account(acc_cfg, cb=MyAccountCallback()) # If argument is specified then make call to the URI if len(sys.argv) > 1: lck = lib.auto_lock() current_call = make_call(sys.argv[1]) print 'Current call is', current_call del lck my_sip_uri = "sip:" + transport.info().host + \ ":" + str(transport.info().port) # Menu loop
# logging config. lib.init(log_cfg = pj.LogConfig(level=LOG_LEVEL, callback=log_cb)) # Create UDP transport which listens to any available port transport = lib.create_transport(pj.TransportType.UDP) print "\nListening on", transport.info().host, print "port", transport.info().port, "\n" # Start the library lib.start() # Create account acc_cfg = pj.AccountConfig() acc_cfg.id = os.getenv('SIP_ID') acc_cfg.reg_uri = os.getenv('SIP_REGISTRAR') acc_cfg.auth_cred = [ pj.AuthCred(os.getenv('SIP_REALM', '*'), os.getenv('SIP_USERNAME'), os.getenv('SIP_PASSWORD')) ] acc_cfg.reg_timeout = int(os.getenv('SIP_REG_TIMEOUT', '300')) except pj.Error, e: print "Exception: " + str(e) gpio.output(led_yellow, gpio.LOW) lib.destroy() lib = None sys.exit(1) # kill -SIGUSR1 to simulate call button pressed signal.signal(signal.SIGUSR1, signal_handler) signal.signal(signal.SIGUSR2, signal_handler) call_start = None call_timeout = datetime.timedelta(seconds=int(os.getenv('CALL_TIMEOUT', '120')))
def main(): # Create library instance lib = pj.Lib() try: lib.init(log_cfg = pj.LogConfig(level=LOG_LEVEL, callback=log_cb)) lib.set_null_snd_dev() transport = lib.create_transport(pj.TransportType.UDP, pj.TransportConfig(0)) print "\nListening on", transport.info().host, print "port", transport.info().port, "\n" lib.start() acc_cfg = pj.AccountConfig() acc_cfg.id = 'sip:' + PJSIP_ID acc_cfg.reg_uri = 'sip:' + PJSIP_REGISTAR acc_cfg.proxy = [ 'sip:' + PJSIP_PROXY ] acc_cfg.auth_cred = [ pj.AuthCred("*", PJSIP_USERNAME, PJSIP_PASSWORD) ] acc = lib.create_account(acc_cfg, cb=MyAccountCallback()) #my_sip_uri = "sip:" + transport.info().host + ":" + str(transport.info().port) global conversation, brain conversation = ConversationVOIP(DEFAULT_LOCALE, API_KEY, callback = update_status) brain = Brain(conversation, MODULES) print 'Modules loaded:' for m in brain.modules: print m.__name__ # Menu loop while True: print print "My SIP URI is", acc_cfg.id print "Menu: h=hangup call, q=quit" input = sys.stdin.readline().rstrip("\r\n") if input == "h": if not current_call: print "There is no call" continue current_call.hangup() elif input == "q": if current_call : current_call.hangup() break transport = None acc.delete() acc = None lib.destroy() lib = None except pj.Error, e: print "Exception: " + str(e) lib.destroy() lib = None
lib.init(log_cfg=pj.LogConfig(level=LOG_LEVEL, callback=log_cb)) # Create UDP transport which listens to any available port transport = lib.create_transport(pj.TransportType.UDP) print "\nListening on", transport.info().host, print "port", transport.info().port, "\n" # Start the library lib.start() # Create account acc_cfg = pj.AccountConfig() acc_cfg.id = os.getenv('SIP_ID') acc_cfg.reg_uri = os.getenv('SIP_REGISTRAR') acc_cfg.auth_cred = [ pj.AuthCred(os.getenv('SIP_REALM', '*'), os.getenv('SIP_USERNAME'), os.getenv('SIP_PASSWORD')) ] acc_cfg.reg_timeout = int(os.getenv('SIP_REG_TIMEOUT', '300')) except pj.Error, e: print "Exception: " + str(e) gpio.output(led_yellow, gpio.LOW) lib.destroy() lib = None sys.exit(1) # kill -SIGUSR1 to simulate call button pressed signal.signal(signal.SIGUSR1, signal_handler) call_start = None call_timeout = datetime.timedelta(
lib = pjsua.Lib() try: lib.init(log_cfg=pjsua.LogConfig(level=4, callback=log_cb)) lib.create_transport(pjsua.TransportType.UDP, pjsua.TransportConfig(5080)) lib.set_null_snd_dev() lib.start() lib.handle_events() acc_cfg = pjsua.AccountConfig() acc_cfg.id = "sip:" + os.environ['sipid'] + "@" + os.environ['sipsrv'] acc_cfg.reg_uri = "sip:" + os.environ['sipsrv'] acc_cfg.proxy = ["sip:" + os.environ['sipsrv'] + ";lr"] acc_cfg.auth_cred = [ pjsua.AuthCred("*", os.environ['sipid'], os.environ['sippass']) ] acc_cb = MyAccountCallback() acc = lib.create_account(acc_cfg, cb=acc_cb) acc_cb.wait() print "\n" print "Registration complete, status=", acc.info().reg_status, \ "(" + acc.info().reg_reason + ")" #YOURDESTINATION is landline or mobile number you want to call dst_uri = "sip:" + telnum + "@sip.ippi.com" in_call = True
lib = pjsua.Lib() try: lib.init(log_cfg=pjsua.LogConfig(level=4, callback=log_cb)) lib.create_transport(pjsua.TransportType.UDP, pjsua.TransportConfig(5080)) lib.set_null_snd_dev() lib.start() lib.handle_events() acc_cfg = pjsua.AccountConfig() acc_cfg.id = "sip:[email protected]" acc_cfg.reg_uri = "sip:YOURSIPSERVER.COM" acc_cfg.proxy = ["sip:PROXY.YOURSIPSERVER.COM;lr"] acc_cfg.auth_cred = [ pjsua.AuthCred("*", "*****@*****.**", "YOURPASSWORD") ] acc_cb = MyAccountCallback() acc = lib.create_account(acc_cfg, cb=acc_cb) acc_cb.wait() print "\n" print "Registration complete, status=", acc.info().reg_status, \ "(" + acc.info().reg_reason + ")" #YOURDESTINATION is landline or mobile number you want to call dst_uri = "sip:[email protected]" in_call = True
current_call = None # nothing to play player = None # result result = 10 # start library lib.start() # create transport transport = lib.create_transport(pj.TransportType.UDP) if auth: acc_cfg = pj.AccountConfig() acc_cfg.id = 'sip:' + auth_login + '@' + auth_domain acc_cfg.reg_uri = 'sip:' + auth_domain acc_cfg.proxy = [ 'sip:' + auth_domain + ';lr' ] acc_cfg.auth_cred = [ pj.AuthCred("*", auth_login, auth_pass) ] acc = lib.create_account(acc_cfg, cb=acc_cb()) acc.set_transport(transport) else: acc = lib.create_account_for_transport(transport) # wait until account is registered while current_account == None: time.sleep( 1 ) if player != None: lib.player_destroy( player ) player = None if player == None:
lib.init(log_cfg=pj.LogConfig(level=3, callback=log_cb)) transportConfig = pj.TransportConfig() transportConfig.port = 5080 # Create UDP transport which listens to any available port transport = lib.create_transport(pj.TransportType.UDP, transportConfig) # Start the library lib.start() acc_cfg = pj.AccountConfig() acc_cfg.id = "%s" % sipId acc_cfg.reg_uri = "%s" % sipRegUrl acc_cfg.proxy = ["%s" % sipProxy] acc_cfg.auth_cred = [pj.AuthCred("*", "%s" % sipUser, "%s" % sipPassword)] acc_ck = CallbackAccount() acc = lib.create_account(acc_cfg, cb=acc_ck) # Wait for ENTER before quitting print "Press <ENTER> to quit" input = sys.stdin.readline().rstrip("\r\n") # We're done, shutdown the library lib.destroy() lib = None except pj.Error, e: print "Exception: " + str(e) lib.destroy()
def __init__(self): super( Example,self ).__init__() self.initUI() lib = pj.Lib() current_call = None my_ua_cfg = pj.UAConfig() my_ua_cfg.nameserver = ['8.8.8.8', '8.8.4.4'] my_ua_cfg.user_agent = "hanxiaotian_bupt" # http://www.pjsip.org/python/pjsua.htm#MediaConfig my_media_cfg = pj.MediaConfig() my_media_cfg.enable_ice = True # # Procedure: Initialize > Create Transpot > Start > Handle calls > Shutdown # # https://trac.pjsip.org/repos/wiki/Python_SIP/Settings#StartupandShutdown # Initialize the Library lib.init(ua_cfg=my_ua_cfg, media_cfg=my_media_cfg, log_cfg = pj.LogConfig(level=3, callback=log_cb)) # Create One or More Transports transport = lib.create_transport(pj.TransportType.TCP, pj.TransportConfig()) #transport = lib.create_transport(pj.TransportType.UDP, pj.TransportConfig(0)) #transport = lib.create_transport(pj.TransportType.TLS, pj.TransportConfig(port=5060)) # SSL lib.set_null_snd_dev() # Starting the Library lib.start() lib.handle_events() # # Registration # acc_cfg = pj.AccountConfig() succeed = 0 while (succeed == 0): print "---------------------------------------------------------------------" acc_cfg.id = "sip:[email protected]" # acc_cfg.reg_uri = "sip:10.103.241.142;transport=tcp" # acc_cfg.proxy = [] server = "10.103.241.142" acc_cfg.proxy = [ "sip:10.103.241.142;transport=tcp;lr" ] # realm = "han" # username = "******" # passwd = "101" print "---------------------------------------------------------------------" acc_cfg.auth_cred = [pj.AuthCred(realm, username ,passwd)] self.acc_cb = MyAccountCallback() self.acc = lib.create_account(acc_cfg, cb=self.acc_cb) self.acc_cb.wait() # Conditions are not correct, because when "IP address change detected for account", all other accounts is Forbidden if ((str(self.acc.info().reg_status) == "200") or (str(self.acc.info().reg_status) == "403")): succeed = 1 else: print "" print "Registration failed, status=", self.acc.info().reg_status, \ "(" + self.acc.info().reg_reason + ")" print "" print "Please try again !"
# # Confbot settings # import pjsua as pj # Set of admins. If empty then everyone is admin! admins = set([]) # acc_cfg holds the account config (set it to None to disable account) acc_cfg = None acc_cfg = pj.AccountConfig() if acc_cfg: acc_cfg.id = "sip:[email protected]" acc_cfg.reg_uri = "sip:pjsip.org" acc_cfg.proxy = [ "sip:pjsip.org;lr;transport=tcp" ] acc_cfg.auth_cred = [ pj.AuthCred("*", "bot", "secretpass") ] acc_cfg.publish_enabled = True #acc_cfg.require_timer = True # Transport configs (set them to None to disable the transport) udp_cfg = pj.TransportConfig(5080) tcp_cfg = pj.TransportConfig(0) #tcp_cfg = None # Logging Config (you can also set it to None to use default values) def log_cb(level, str, len): print str, log_cfg = pj.LogConfig() #log_cfg.callback = log_cb