bot.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. #!/usr/bin/env python3
  2. # encoding:utf-8
  3. import os
  4. import time
  5. import json
  6. import wave
  7. import queue
  8. import threading
  9. import traceback
  10. import sys
  11. import pjsua2 as pj
  12. from enum import Enum
  13. from datetime import datetime
  14. from src.core.callcenter import registry
  15. from src.core.callcenter.cache import Cache
  16. from src.core.datasource import SIP_SERVER, SERVE_HOST
  17. from src.core.voip.constant import *
  18. import requests
  19. from src.core.callcenter.api import BotChatRequest,ChatMessage
  20. from src.core import singleton_keys
  21. from src.core.callcenter.snowflake import Snowflake
  22. from src.core.callcenter.data_handler import *
  23. calls = {}
  24. # recording_file = '/code/src/core/voip/incoming_call.wav'
  25. # player_file1 = '/code/src/core/voip/test111.wav'
  26. # player_file2 = '/code/src/core/voip/test222.wav'
  27. class BotStatus(Enum):
  28. # 等待用户讲话,未超时
  29. wait_speaking_not_timeout = 1
  30. # 等待用户讲话,已超时但用户仍在持续讲话
  31. wait_speaking_timeout_user_speaking = 2
  32. # 机器人讲话过程中
  33. speaking = 3
  34. # 等待用户讲话结束
  35. wait_user_speaking_end = 4
  36. # 等待大模型输出
  37. wait_gpt_return = 5
  38. class UserStatus(Enum):
  39. # ASR返回值为sentenceBegin后将状态置为Speaking
  40. speaking = 1
  41. # ASR返回值为sentenceEnd后,将状态置为Silence
  42. silence = 2
  43. class MyAudioMediaPort(pj.AudioMediaPort):
  44. def __init__(self, call, aud_media=None, asr=None):
  45. pj.AudioMediaPort.__init__(self)
  46. # # 打开一个 .pcm 文件来保存音频流(可选:保存为 .wav)
  47. # self.wav = wave.open(f"{recording_file}", "wb")
  48. # self.wav.setnchannels(1)
  49. # self.wav.setsampwidth(2) # 假设每个样本是 16 位(2 字节)
  50. # self.wav.setframerate(16000)
  51. print("MyAudioMediaPort::come in, debugger")
  52. self.call = call
  53. self.aud_media = aud_media
  54. self.asr = asr
  55. self.first = True
  56. self.user_asr_texts = []
  57. def onFrameRequested(self, frame):
  58. print("Request audio frame:", frame)
  59. def onFrameReceived(self, frame):
  60. # self.wav.writeframes(bytes(frame.buf))
  61. if self.asr: # 如果ASR实例存在,则发送音频数据
  62. if self.first:
  63. self.first = False
  64. self.logger.info("Received audio frame: %s %s", frame.buf, frame.size)
  65. self.asr.send_audio(frame.buf)
  66. try:
  67. asr_text = self.get_asr_text()
  68. play_complete = self.call.is_play_complete()
  69. current_time = time.time() # 实时当前时间
  70. if self.call.inputType == '1.0':
  71. time_difference = int(current_time - self.call.inputLongStart)
  72. # print('current_time - self.call.inputLongStart:',time_difference > 35, self.call.txtLock , play_complete)
  73. if time_difference > 35 and play_complete:
  74. self.user_asr_texts.append(f"DTMF({self.call.digit})DTMF")
  75. user_asr_text = self.user_asr_texts[0] if len(self.user_asr_texts) == 1 else '###'.join(self.user_asr_texts)
  76. self.user_asr_texts.clear()
  77. self.call.chat(user_asr_text)
  78. # print("测试超长", user_asr_text)
  79. elif asr_text:
  80. self.user_asr_texts.append(asr_text)
  81. if time_difference > int(self.call.wait_time):
  82. self.call.reset_wait_time()
  83. else:
  84. if asr_text and not play_complete:
  85. self.user_asr_texts.append(asr_text)
  86. if (asr_text and play_complete) or (play_complete and self.user_asr_texts):
  87. if asr_text:
  88. self.user_asr_texts.append(asr_text)
  89. user_asr_text = self.user_asr_texts[0] if len(self.user_asr_texts) == 1 else '###'.join(self.user_asr_texts)
  90. self.user_asr_texts.clear()
  91. self.call.chat(user_asr_text)
  92. if self.call.wait_time and self.call.wait_time != "0" and play_complete and not asr_text:
  93. self.call.wait_time_check(current_time, self.call.wait_time)
  94. message_queue_size = self.call.message_queue.qsize()
  95. if (message_queue_size > 0 and not self.call.cur_player_file) or (message_queue_size > 0 and play_complete):
  96. # self.call.logger.info('onFrameReceived:message_queue_size=', message_queue_size, 'play_complete=', play_complete, asr_text)
  97. self.call.cur_player_file, self.call.wait_time, self.call.inputType,self.call.action, self.call.node_id = self.get_player_file()
  98. # 重置播放完成标志和超时计时器,确保新的播放从头开始计时
  99. self.call.reset_wait_time()
  100. self.call.send_bot_speaker(self.call.cur_player_file)
  101. except:
  102. pass
  103. def get_asr_text(self):
  104. try:
  105. asr_text = self.call.user_asr_text_queue.get(block=False)
  106. self.call.logger.info('get_asr_text: %s', asr_text)
  107. return asr_text
  108. except:
  109. pass
  110. def get_player_file(self):
  111. try:
  112. message = self.call.message_queue.get(block=False)
  113. player_file = [item.voice_url for item in message.contents if item.content_type == 'voice']
  114. return player_file, message.wait_time, message.inputType, message.action, message.node_id
  115. except Exception as e:
  116. traceback.print_exc()
  117. class MyAudioMediaPlayer(pj.AudioMediaPlayer):
  118. def __init__(self, player_id, sink, on_complete=None):
  119. pj.AudioMediaPlayer.__init__(self)
  120. self.player_id = player_id
  121. self.sink = sink
  122. self.on_complete = on_complete
  123. def onEof2(self):
  124. # self.stopTransmit(self.sink)
  125. if self.on_complete:
  126. self.on_complete(self.player_id)
  127. # Subclass to extend the Account and get notifications etc.
  128. class Account(pj.Account):
  129. def __init__(self, agent, user_part, **kwargs):
  130. pj.Account.__init__(self)
  131. self.agent = agent
  132. self.user_part = user_part
  133. self.calls = {}
  134. self.kwargs = kwargs
  135. def onRegState(self, prm):
  136. ai = self.getInfo()
  137. print("***OnRegState: " + prm.reason, ai.id,ai.isDefault,ai.uri,ai.regIsConfigured,ai.regIsActive,ai.regExpiresSec,ai.regStatus,ai.regStatusText,ai.regLastErr,ai.onlineStatus,ai.onlineStatusText)
  138. def onIncomingCall(self, prm):
  139. ai = self.getInfo()
  140. print("***onIncomingCall: ", prm.callId, ai.id,ai.isDefault,ai.uri,ai.regIsConfigured,ai.regIsActive,ai.regExpiresSec,ai.regStatus,ai.regStatusText,ai.regLastErr,ai.onlineStatus,ai.onlineStatusText)
  141. call = MyCall(self.agent, self, self.user_part, prm.callId, **self.kwargs)
  142. call_op_param = pj.CallOpParam(True)
  143. call_op_param.statusCode = pj.PJSIP_SC_OK
  144. call.answer(call_op_param)
  145. self.calls[prm.callId] = call
  146. class MyCall(pj.Call):
  147. def __init__(self, agent, acc, user_part, call_id, **kwargs):
  148. pj.Call.__init__(self, acc, call_id)
  149. self.agent = agent
  150. self.logger = agent.logger
  151. self.user_part = user_part
  152. self.call_id = call_id
  153. self.kwargs = kwargs
  154. self.aud_media = None
  155. self.audio_port = None
  156. self.audio_player = None
  157. self.asr = None
  158. self.session_id = kwargs.get('variable_sip_h_P-LIBRA-CallId')
  159. self.device_id = kwargs.get('variable_sip_h_P-LIBRA-DeviceId')
  160. self.call_phone = kwargs.get("Caller-Caller-ID-Number")
  161. self.logger.info("self.session_id:%s, self.call_phone:%s", self.session_id,self.call_phone)
  162. self.taskId = "10001"
  163. # self.scripts = build_demo_script()
  164. self.user_asr_text_queue = queue.Queue(maxsize=100)
  165. self.message_queue = queue.Queue(maxsize=3)
  166. self.player_complete_dict = {}
  167. self.wait_time = None
  168. self.inputType = None #记录按键类型 1为长按键类型
  169. self.digit = '' # 存储长按键内容
  170. self.action = None
  171. self.node_id= 'start'
  172. self.cur_player_file = None #当前播放的文件
  173. from src.core.voip.asr import TestSt
  174. self.asr = TestSt(call_id, message_receiver=self.on_receiver_asr_result) # 创建ASR实例
  175. self.asr.start() # 启动ASR线程
  176. self.start_time = time.time() # 当前机器人对话开始时间
  177. # 超时设置
  178. self.play_start_time = time.time() # 倒计时开始时间
  179. self.play_complete_flag = False # 倒计时开始标志
  180. self.txtLock = False
  181. self.inputLongStart = time.time() #长按键开始时间
  182. self.inter_action_total = 0
  183. self.statistics_lock = False
  184. def wait_time_check(self, current_time, wait_time):
  185. try:
  186. # 确保 wait_time 是整数类型
  187. wait_time = int(wait_time)
  188. # 如果播放尚未完成,重置标志并返回
  189. if not self.play_complete_flag:
  190. self.play_complete_flag = True
  191. self.play_start_time = current_time
  192. # print(f"开始计时: {self.play_start_time}")
  193. elapsed_time = int(current_time - self.play_start_time)
  194. # print(f"当前时间: {current_time}, 已过时间: {elapsed_time}, 最大等待时间: {wait_time}")
  195. if elapsed_time > wait_time:
  196. # self.user_asr_text_queue.put("ASR408error")
  197. self.chat('ASR408error')
  198. registry.BOT_ASR_408.labels(self.taskId).inc()
  199. except ValueError as e:
  200. self.logger.info(f"无效的等待时间参数: {wait_time}, 错误: {e}")
  201. self.reset_wait_time()
  202. def reset_wait_time(self):
  203. self.play_complete_flag = False # 重置播放完成标志
  204. self.play_start_time = None # 重置开始计时时间
  205. def is_play_complete(self): #语音机器人是否播放结束
  206. if self.cur_player_file:
  207. player_id = murmur3_32(self.cur_player_file)
  208. return self.player_complete_dict.get(player_id)
  209. def onDtmfDigit(self, prm):
  210. # 判断是否播放完成 否则不记录用户说的内容
  211. if not self.is_play_complete():
  212. return
  213. digit = prm.digit
  214. self.reset_wait_time()
  215. # 假设为超长类型按键 把用户输入的按键进行拼接 如果为# 则把用户输入所有按键放入队列并发送文本机器人
  216. # 如果为非正常按键服务 输入以后直接发送文本机器人
  217. if self.inputType == '1.0':
  218. if digit != '#':
  219. self.digit += digit
  220. elif digit == '#':
  221. # self.user_asr_text_queue.put(f"DTMF({self.digit})DTMF")
  222. self.chat(f"DTMF({self.digit})DTMF")
  223. else:
  224. self.user_asr_text_queue.put(f"DTMF({digit})DTMF")
  225. def onCallState(self, prm):
  226. call_info = self.getInfo()
  227. # pj.PJSIP_INV_STATE_NULL
  228. # pj.PJSIP_INV_STATE_CALLING
  229. # pj.PJSIP_INV_STATE_INCOMING
  230. # pj.PJSIP_INV_STATE_EARLY
  231. # pj.PJSIP_INV_STATE_CONNECTING
  232. # pj.PJSIP_INV_STATE_CONFIRMED
  233. # pj.PJSIP_INV_STATE_DISCONNECTED
  234. if call_info.state == pj.PJSIP_INV_STATE_CONFIRMED:
  235. # 当呼叫状态为已确认(即接通)
  236. self.bot_say_hello()
  237. if call_info.state == pj.PJSIP_INV_STATE_DISCONNECTED:
  238. self.logger.info("通话结束:%s", self.user_part)
  239. self.release()
  240. def onCallMediaState(self, prm):
  241. call_info = self.getInfo()
  242. # print("Call Media state: ", call_info.stateText)
  243. for media in call_info.media:
  244. if media.type == pj.PJMEDIA_TYPE_AUDIO and \
  245. (media.status == pj.PJSUA_CALL_MEDIA_ACTIVE):
  246. self.logger.info("Call Media state 111: %s", call_info.stateText)
  247. self.aud_media = self.getAudioMedia(media.index)
  248. try:
  249. # 建立双向通道
  250. self.receive_user_speaker()
  251. # self.bot_say_hello()
  252. except Exception as e:
  253. traceback.print_exc()
  254. def receive_user_speaker(self):
  255. self.audio_port = MyAudioMediaPort(self, self.aud_media, self.asr)
  256. self.audio_port.createPort("Incoming Call Port", build_audio_format())
  257. self.aud_media.startTransmit(self.audio_port)
  258. def send_bot_speaker(self, player_file):
  259. if not player_file :
  260. return
  261. player_id = murmur3_32(player_file)
  262. self.player_complete_dict[player_id] = False
  263. # print('self.player_complete_dict[player_id]D:', player_id, player_file, self.player_complete_dict[player_id])
  264. self.logger.info(f"[DEBUG] Sending bot speaker, player_file: {player_file}, player_id: {player_id}")
  265. self.audio_player = MyAudioMediaPlayer(player_id, self.aud_media, on_complete=self.on_media_player_complete)
  266. # self.audio_player.createPlayer(player_file[0], pj.PJMEDIA_FILE_NO_LOOP)
  267. self.audio_player.createPlaylist(player_file, f'my_hello_playlist{player_id}', pj.PJMEDIA_FILE_NO_LOOP)
  268. self.audio_player.startTransmit(self.aud_media)
  269. def on_receiver_asr_result(self, message, *args):
  270. # 判断是否播放完成 否则不记录用户说的内容
  271. if not self.is_play_complete():
  272. return
  273. message = json.loads(message)
  274. if message["header"]["status"] == 20000000:
  275. if message["header"]["name"] == "SentenceEnd":
  276. result = message["payload"]["result"]
  277. # self.logger.info("asr返回内容Result:%s", result)
  278. self.user_asr_text_queue.put(result)
  279. elif message["header"]["name"] == "TranscriptionResultChanged":
  280. self.reset_wait_time()
  281. else:
  282. self.logger.info(f"Status is not {message['header']['status']}")
  283. registry.ASR_ERRORS.labels(message['header']['status']).inc()
  284. def on_media_player_complete(self, player_id):
  285. self.logger.info('player complete')
  286. self.player_complete_dict[player_id] = True
  287. self.digit = ''
  288. self.inputLongStart = time.time()
  289. #播放完毕执行的动作
  290. self.say_end_action(self.action)
  291. def bot_say_hello(self):
  292. self.chat(user_asr_text="start")
  293. def chat(self, user_asr_text=None):
  294. # 调用文本机器人接口
  295. ToTextBotAgent(user_asr_text,self)
  296. def say_end_action(self, action):
  297. self.logger.info('handling_release %s', action.action_code)
  298. action_code = action.action_code
  299. if action_code == 'hang': # 挂断
  300. self.agent.hangup(self.user_part)
  301. self.end_statistics()
  302. elif action_code == 'transfer': # 转人工
  303. self.agent.transfer(user_part=self.user_part, call_id=self.session_id, device_id=self.device_id)
  304. self.end_statistics()
  305. #更新通话记录
  306. self.agent.dataHandleServer.update_record(self.session_id, service_category=2)
  307. def end_statistics(self):
  308. if not self.statistics_lock:
  309. self.statistics_lock = True
  310. self.logger.info(f"self.inter_action_total:{self.inter_action_total}")
  311. latency = (time.time() - self.start_time)
  312. registry.BOT_CALL_DURATION.labels(self.taskId).observe(latency)
  313. registry.BOT_INTERACTION_ROUNDS.labels(self.taskId).observe(self.inter_action_total)
  314. def release(self):
  315. self.logger.info('liuwei::debugger::release:: come in ')
  316. if self.audio_port:
  317. # self.audio_port.stopTransmit()
  318. self.audio_port = None # 或调用相关销毁方法
  319. if self.audio_player:
  320. # self.audio_player.stopTransmit()
  321. self.audio_player = None # 或调用播放器停止方法
  322. if self.aud_media:
  323. # self.audio_media.stopTransmit()
  324. self.aud_media = None
  325. self.asr.close()
  326. # 远程挂机之后要将分机号回收
  327. self.agent.hangup(self.user_part)
  328. # self.agent.release(self.user_part)
  329. self.end_statistics()
  330. class ToTextBotAgent:
  331. def __init__(self, user_asr_text, call_agent):
  332. if not user_asr_text or (call_agent.action and call_agent.action.action_code != 'normal'):
  333. # print("ASR文本为空,终止执行。")
  334. return
  335. self.call_agent = call_agent
  336. self.request_data = BotChatRequest(
  337. nodeId=self.call_agent.node_id,
  338. userId=self.call_agent.call_phone,
  339. sessionId= self.call_agent.session_id,
  340. recordId="",
  341. taskId=self.call_agent.taskId,
  342. asrText=user_asr_text,
  343. ext= None
  344. )
  345. self.call_agent.logger.info("user_asr_text发送结果: %s", user_asr_text)
  346. if user_asr_text != 'ASR408error':
  347. self.call_agent.inter_action_total += 1
  348. # 发送请求并处理响应
  349. # self.test_request(self.request_data)
  350. self.to_quest(self.request_data)
  351. def to_quest(self, request: BotChatRequest):
  352. headers = {'Content-Type': 'application/json'}
  353. request_data = request.to_json_string()
  354. url = f"http://{SERVE_HOST}:40072/botservice"
  355. start_time = time.time()
  356. self.call_agent.logger.info(f"请求数据:{request_data},url:{url}")
  357. with requests.Session() as session:
  358. session.headers.update({'Content-Type': 'application/json'})
  359. try:
  360. response = session.post(url=url, json=json.loads(request_data), timeout=10)
  361. # response = requests.post(url=url, json=json.loads(request_data), headers=headers, timeout=10) # 使用占位URL
  362. self.call_agent.logger.info(f"sessionId={ self.call_agent.session_id}, chat::request:{request_data}, response:{response.text}")
  363. if response.status_code == 200:
  364. response_data = response.json()
  365. if "data" in response_data and response_data["code"]==0:
  366. data = response_data["data"]
  367. parsed_response = ChatMessage.from_json(data)
  368. self.call_agent.message_queue.put(parsed_response)
  369. else:
  370. self.call_agent.logger.info("响应中没有 'data' 字段")
  371. else:
  372. # 错误处理
  373. self.call_agent.logger.info(f"请求失败,状态码: {response.status_code}, 响应内容: {response.text}")
  374. except requests.RequestException as e:
  375. traceback.print_exc()
  376. self.call_agent.logger.error(f"TaskId={request.taskId}, 请求发生异常: {e}, URL: {url}")
  377. finally:
  378. latency = (time.time() - start_time)
  379. registry.BOT_REQUEST_COUNT.inc()
  380. registry.BOT_REQUEST_LATENCY.labels(request.taskId).observe(latency)
  381. session.close()
  382. # 模拟接口请求返回
  383. def test_request(self, params: BotChatRequest):
  384. self.call_agent.logger.info("test_request::params= %s", params)
  385. response_data = {
  386. "node_id": "1.0",
  387. "contents": [],
  388. "wait_time": "6",
  389. "action": {
  390. "action_code": "normal",
  391. "action_content": "正常通话"
  392. },
  393. "inputType": "0"
  394. }
  395. self.call_agent.logger.info("asrText: %s", params.asrText)
  396. if params.asrText == 'start': #欢迎语
  397. response_data['contents'].append({
  398. "content_type": "voice",
  399. "content": "",
  400. "voice_url": '/code/src/core/voip/scripts/1_00.wav',
  401. "voice_content": "五一北京到上海的高铁票还有吗?"
  402. })
  403. response_data['inputType'] = '1.0'
  404. elif params.asrText == 'ASR408error': #超时执行
  405. response_data['contents'].append({
  406. "content_type": "voice",
  407. "content": "",
  408. "voice_url": '/code/src/core/voip/scripts/4_00.wav',
  409. "voice_content": "waitTime超时"
  410. })
  411. elif "DTMF" in params.asrText and self.call_agent.inputType =='1.0': #长按键超30s执行
  412. response_data['contents'].append({
  413. "content_type": "voice",
  414. "content": "",
  415. "voice_url": '/code/src/core/voip/scripts/2_00.wav',
  416. "voice_content": "sds"
  417. })
  418. else :
  419. response_data['contents'] = [
  420. {
  421. "content_type": "voice",
  422. "content": "",
  423. "voice_url": '/code/src/core/voip/test111.wav',
  424. "voice_content": "测试第二个录音文件"
  425. },
  426. {
  427. "content_type": "voice",
  428. "content": "",
  429. "voice_url": '/code/src/core/voip/test222.wav',
  430. "voice_content": "五一北京到上海的高铁票还有吗?"
  431. }
  432. ]
  433. try:
  434. parsed_response = ChatMessage.from_json(response_data)
  435. self.call_agent.message_queue.put(parsed_response)
  436. except Exception as e:
  437. traceback.print_exc() # 打印完整的错误信息
  438. return None
  439. @singleton_keys
  440. class BotAgent:
  441. def __init__(self, app, user_part_range=range(1001, 1011), host="192.168.100.159", port="5060", password="slibra@#123456"):
  442. self.app = app
  443. self.logger = app.logger
  444. self.user_part_range, self.host, self.port, self.password = user_part_range, host, port, password
  445. self.user_part_pool = queue.Queue(maxsize=len(user_part_range))
  446. self.accounts = {}
  447. self.calls = {}
  448. self.ep = pj.Endpoint()
  449. self.is_stopping = False
  450. self.acd_service = None
  451. self.cache = Cache(app)
  452. self.dataHandleServer = DataHandleServer(app)
  453. threading.Thread(target=self.create_pjsua2, daemon=True).start()
  454. def create_pjsua2(self, timeout_sec=86400):
  455. start_time = time.time()
  456. try:
  457. self.cache.set_register_per_hours(expire=timeout_sec - (60*3))
  458. # Create and initialize the library
  459. ep_cfg = pj.EpConfig()
  460. ep_cfg.uaConfig.threadCnt = 12
  461. ep_cfg.uaConfig.mainThreadOnly = False
  462. ep_cfg.uaConfig.maxCalls = 20
  463. ep_cfg.uaConfig.maxAccounts = 20
  464. ep_cfg.medConfig.noVad = True
  465. ep_cfg.logConfig.level = 3
  466. ep_cfg.logConfig.consoleLevel = 3
  467. self.ep.libCreate()
  468. self.ep.libInit(ep_cfg)
  469. aud_dev_mgr = self.ep.audDevManager()
  470. aud_dev_mgr.setNullDev() # 使用虚拟音频设备(如果没有实际设备)
  471. # Set up media configuration, particularly jitter buffer
  472. media_cfg = pj.MediaConfig()
  473. media_cfg.jbMinPre = 4 # Minimum pre-fetch frames
  474. media_cfg.jbMaxPre = 16 # Maximum pre-fetch frames
  475. media_cfg.noVad = True # Disable Voice Activity Detection if needed
  476. self.ep.medConfig = media_cfg # Apply media config to endpoint
  477. # Create SIP transport. Error handling sample is shown
  478. sipTpConfig = pj.TransportConfig()
  479. sipTpConfig.port = 30506
  480. self.ep.transportCreate(pj.PJSIP_TRANSPORT_UDP, sipTpConfig)
  481. # Start the library
  482. self.ep.libStart()
  483. for user_part in self.user_part_range:
  484. acfg = pj.AccountConfig()
  485. acfg.idUri = f"sip:{user_part}@{self.host}:{self.port}"
  486. acfg.regConfig.registrarUri = f"sip:{self.host}:{self.port}"
  487. cred = pj.AuthCredInfo("digest", "*", f"{user_part}", 0, self.password)
  488. acfg.sipConfig.authCreds.append(cred)
  489. acfg.regConfig.timeoutSec = timeout_sec # 注册超时时间(秒)
  490. acfg.regConfig.retryIntervalSec = 10 # 重试间隔时间(秒)
  491. acfg.regConfig.firstRetryIntervalSec = 10 # 首次重试间隔时间(秒)
  492. # acfg.natConfig.iceEnabled = True
  493. # acfg.natConfig.turnEnabled = True
  494. # acfg.natConfig.turnServer = f"stun:{self.host}:3478"
  495. # acfg.natConfig.turnUsername = "username"
  496. # acfg.natConfig.turnPassword = "password"
  497. # Create the account
  498. acc = Account(self, user_part=user_part)
  499. acc.create(acfg)
  500. self.user_part_pool.put(user_part)
  501. self.accounts[user_part] = acc
  502. except:
  503. traceback.print_exc()
  504. finally:
  505. latency = time.time() - start_time
  506. registry.BOT_CREATE_ACCOUNT_LATENCY.observe(latency)
  507. self.logger.info("create pjsua latency: %.3fs", latency)
  508. while not self.is_stopping:
  509. registry.BOT_AGENT_LIVES.set(self.user_part_pool.qsize())
  510. self.register_per_hours()
  511. self.ep.libHandleEvents(100)
  512. def register_per_hours(self):
  513. _lock = self.cache.lock_register_per_hours()
  514. if not _lock and len(self.accounts) == len(self.user_part_range):
  515. self.restart()
  516. def transfer(self, user_part, call_id, device_id, service_id='00000000000000000'):
  517. if self.acd_service:
  518. self.acd_service.transfer_to_agent(call_id, device_id, service_id, hold=True)
  519. # sip_headers = {'P-LIBRA-HangUpReason': 'transferToAgent', 'P-LIBRA-ServiceId': service_id}
  520. try_count = 100
  521. while try_count >0:
  522. if self.cache.get_after_play_hold_music(call_id):
  523. self.hangup(user_part)
  524. break
  525. time.sleep(0.1)
  526. def hangup(self, user_part, reason="NORMAL_CLEARING", **sip_headers):
  527. call_op_param = pj.CallOpParam(True)
  528. call_op_param.statusCode = pj.PJSIP_SC_OK
  529. call_op_param.reason = reason
  530. call_op_param.txOption = pj.SipTxOption()
  531. sip_header_vector = pj.SipHeaderVector()
  532. for k, v in sip_headers.items():
  533. _sip_header = pj.SipHeader()
  534. _sip_header.hName = str(k)
  535. _sip_header.hValue = str(v)
  536. self.logger.info('hangup, header_name=%s, header_value=%s'%(k, v))
  537. sip_header_vector.push_back(_sip_header)
  538. call_op_param.txOption.headers = sip_header_vector
  539. try:
  540. acc = self.accounts.get(user_part)
  541. if acc:
  542. for k, v in acc.calls.items():
  543. try:
  544. v.hangup(call_op_param)
  545. except:
  546. traceback.print_exc()
  547. except:
  548. traceback.print_exc()
  549. finally:
  550. # 机器人主动挂机回收分机号
  551. self.release(user_part)
  552. def register(self, **kwargs):
  553. self.logger.info('register,come in, pool.size :%d', self.user_part_pool.qsize())
  554. user_part = self.user_part_pool.get()
  555. acc = self.accounts.get(user_part)
  556. self.logger.info('register, user_part :%d, pool.size :%d', user_part, self.user_part_pool.qsize())
  557. if acc:
  558. self.logger.info('register==========> %s', acc.getId())
  559. # ps = pj.PresenceStatus()
  560. # ps.status = pj.PJSUA_BUDDY_STATUS_ONLINE
  561. # ps.activity = pj.PJRPID_ACTIVITY_AWAY
  562. # ps.note = "Away"
  563. # acc.setOnlineStatus(ps)
  564. # acc.setRegistration(renew=True)
  565. acc.kwargs = kwargs
  566. return user_part
  567. def unregister(self, user_part):
  568. acc = self.accounts.get(user_part)
  569. if acc:
  570. acc.setRegistration(renew=False)
  571. # 用户远程挂机回收分机号
  572. self.release(user_part)
  573. def release(self, user_part):
  574. if not user_part:
  575. self.logger.info("release, user_part is None")
  576. return
  577. def element_in_queue(q, element):
  578. with q.mutex: # 确保线程安全
  579. for item in list(q.queue): # 将队列转换为列表进行遍历
  580. if item == element:
  581. return True
  582. return False
  583. if element_in_queue(self.user_part_pool, user_part):
  584. self.logger.info("release, already exists, user_part :%d, pool.size :%d", user_part, self.user_part_pool.qsize())
  585. return
  586. self.user_part_pool.put(user_part)
  587. self.logger.info("release, user_part :%d, pool.size :%d", user_part, self.user_part_pool.qsize())
  588. def restart(self):
  589. self.destroy()
  590. self.is_stopping = False
  591. threading.Thread(target=self.create_pjsua2, daemon=True).start()
  592. def destroy(self):
  593. self.is_stopping = True
  594. try:
  595. while not self.user_part_pool.empty():
  596. self.user_part_pool.get_nowait()
  597. except:
  598. pass
  599. self.accounts.clear()
  600. self.calls.clear()
  601. # Destroy the library
  602. self.ep.libDestroy()
  603. def __del__(self):
  604. self.destroy()
  605. # if __name__ == '__main__':
  606. # import logging
  607. # logger = logging.getLogger('voip')
  608. # bot = BotAgent(logger)