I'm doing an implementation of lib pjsua to work with VoIP using python.
from datetime import datetime
from time import sleep
from sys import exit
from pysip.callbacks import AbstractCallCallback, AbstractAccountCallback
from pysip.states import CallState, MediaState
from pysip import Worker, GenericError
now = (lambda: datetime.now().strftime("%H:%M:%S.%f"))
class AccountCallback(AbstractAccountCallback):
def on_incoming_call(self, call):
callid = call.info().sip_call_id
print(f'{now} - {callid} - Nova chamada recebida.')
call.answer(486, "Busy")
class CallCallback(AbstractCallCallback):
def on_state(self):
info = self.call.info()
callid = info.sip_call_id
if info.state == CallState.DISCONNECTED:
print(f'{now()} - {callid} - Chamada finalizada.')
else:
print(f'{now()} - {callid} - Estado alterado. Novo estado: {info.state_text}')
print(f'{now()} - {callid} - Sinalzação: {info.last_code} {info.last_reason}')
def on_media_state(self):
info = self.call.info()
callid = info.sip_call_id
if info.media_state == MediaState.ACTIVE:
Worker.instance().conf_connect(info.conf_slot, 0)
Worker.instance().conf_connect(0, info.conf_slot)
print(f'{now()} - {callid} - Mídia ativada.')
else:
print(f'{now()} - {callid} - Mídia desativada.')
def make_call(acc, destiny):
worker = Worker(logfile='registros.log')
with worker as runner:
account_cb = CallCallback()
account = runner.make_account(**acc)
call = account.make_call(dst_uri=destiny, cb=account_cb)
callid = call.info().sip_call_id
sleep(5)
call.hangup()
return call.info().sip_call_id
if __name__ == '__main__':
destiny = 'sip:[email protected]'
acc = {'username': '1000',
'domain': 'development',
'password': '1000',
'callback': AccountCallback}
try:
callid = make_call(acc, destiny)
print(f'Chamada realizada: {callid}')
except GenericError as error:
print(error)
In this code I was able to generate a full connection and even make the exchange of audio, but after the N seconds sleep of the code, the call terminates as requested, however, the script is not terminated and python remains locked until I kill the process on another tab of the terminal.
All code used is in the above repository. I preferred to link the code to post here, because instead of an isolated block, it is possible to see the script as a whole.