Привет, мне надо переделать класс так чтобы я мог делать параллельные звонки


class SIPWorker:
    def __init__(self, sip_server, sip_user, sip_pass, stt, tts):
      self.sip_server = sip_server
      self.sip_user = sip_user
      self.sip_pass = sip_pass
      self.command_queue = queue.Queue()
      self.result_queue = queue.Queue()
      self.thread = None
      self.running = False
      self.company = None
      self.stt = stt
      self.tts = tts
      self.call = None

    def start(self):
      if self.running:
          return
          
      self.running = True
      self.thread = threading.Thread(target=self._run, daemon=True)
      self.thread.start()
      
      # Ждем инициализации
      while not hasattr(self, 'ep'):
          time.sleep(0.1)

    def _run(self):

      try:
        # Всё в одном потоке - регистрация не нужна
        self.ep = pj.Endpoint()
        self.ep.libCreate()
        
        # Конфигурация endpoint
        ep_cfg = pj.EpConfig()
        ep_cfg.medConfig.maxCalls = 5
        ep_cfg.medConfig.threadCnt = 0

        ep_cfg.medConfig.threadCnt = 0  # No worker threads for audio
        #ep_cfg.medConfig.noVad = True   # Disable VAD (Voice Activity Detection) if not needed
        ep_cfg.medConfig.noAudioDev = True

        ep_cfg.logConfig.level = 0
        ep_cfg.logConfig.consoleLevel = 0
         
        self.ep.libInit(ep_cfg)
        
        tcfg = pj.TransportConfig()
        tcfg.port = 5060
        tcfg.qosType = pj.PJ_QOS_TYPE_VOICE
        tcfg.portRange = 0
        self.ep.transportCreate(pj.PJSIP_TRANSPORT_UDP, tcfg)
        
        acc_cfg = pj.AccountConfig()
        acc_cfg.idUri = f"sip:{self.sip_user}@{self.sip_server}"
        acc_cfg.regConfig.registrarUri = f"sip:{self.sip_server};expires=3600"
        
        cred = pj.AuthCredInfo("digest", "*", self.sip_user, 0, self.sip_pass)
        acc_cfg.sipConfig.authCreds.append(cred)

        # Устанавливаем интервал регистрации (в секундах)
        acc_cfg.regConfig.retryIntervalSec = 60
        acc_cfg.regConfig.firstRetryIntervalSec = 60
        acc_cfg.regConfig.delayBeforeRefreshSec = 120

        # Если сервер требует определенный Expires
        acc_cfg.regConfig.registrarTimeoutSec = 3600
  
        self.acc = Account(self.stt, self.tts)
        self.acc.create(acc_cfg)
        
        self.ep.libStart()

        self.ep.instance().audDevManager().setNullDev()

        # поддержка регистрации
        CHECK_INTERVAL = 60  # раз в минуту проверяем
        REREGISTER_TIMEOUT = 1*60  # 5 минут
        last_check = 0

    
        # Основной цикл обработки
        while self.running:
          # Обработка команд
          
          now = time.time()
          if now - last_check > CHECK_INTERVAL:
              last_check = now

              if self.acc.is_reg:
                  idle = now - self.acc.last_call_time
                  if idle > REREGISTER_TIMEOUT:
                      logger.warning("No calls for 5 minutes, forcing re-registration")
                      try:
                          # Отключаем регистрацию
                          self.acc.setRegistration(False)
                          time.sleep(2)  # небольшая пауза
                          # Включаем регистрацию заново
                          self.acc.setRegistration(True)
                      except Exception as e:
                          logger.error(f"Failed to re-register: {e}")


          try:
              cmd = self.command_queue.get_nowait()
              if cmd[0] == 'call':
                  self._make_call(cmd[1])
              elif cmd[0] == 'stop':
                  break
          except queue.Empty:
              pass
          # Обработка событий
          self.ep.libHandleEvents(10)
          time.sleep(0.1)
              
      except Exception as e:
          logger.error(f"SIP error: {e}")
      finally:
          self._cleanup()
          
    def reg_company(self, company):
      self.company = company
      
    def _make_call(self, phone):
      
        result = {'status': 'error', 'message': 'noreg'}
        
        if self.acc.is_reg == True:
          
          try:
              self.call = Call(acc=self.acc, stt=self.stt, tts=self.tts, company=self.company)
              call_prm = pj.CallOpParam(True)
              call_prm.opt.audioCount = 1
              call_prm.opt.videoCount = 0
              call_prm.opt.timeoutSec = 10
             
              self.call.makeCall(f"sip:{phone}@{self.sip_server}", call_prm)
            
              result = self.call.wait_for_completion()
   
              self.acc.removeCall(self.call)
              
          except Exception as e:
              result = {'status': 'error', 'message': str(e)}
              
              
        return self.result_queue.put(result)
         
    def make_call(self, phone):
      self.command_queue.put(('call', phone))
      return self.result_queue.get()

    def make_calloff(self, phone):
      self.command_queue.put(('call', phone))
      # Отключить звонок
      return self.result_queue.get()

    def _cleanup(self):
      if hasattr(self, 'ep') and self.ep:
        self.ep.libDestroy()

    def stop(self):
      self.command_queue.put(('stop', None))
      self.running = False
      if self.thread:
        self.thread.join()

class k_SIP:
    def __init__(self, sip_server, sip_user, sip_pass, stt, tts):
        self.worker = SIPWorker(sip_server, sip_user, sip_pass, stt, tts)
        
    def start(self):
        self.worker.start()
        
    def reg_company(self, company):
        return self.worker.reg_company(company)
        
    def make_call(self, phone):
        return self.worker.make_call(phone)
        
    def stop(self):
        self.worker.stop()