stc-broadcast.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. package broadcast
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "io"
  7. "net"
  8. "pbx-api-gin/internal/app/ami/action"
  9. "pbx-api-gin/internal/app/stc/active"
  10. msgdata "pbx-api-gin/internal/app/stc/data"
  11. "pbx-api-gin/internal/app/stc/priority"
  12. alstatus "pbx-api-gin/internal/app/stc/sendstatus"
  13. "pbx-api-gin/pkg/lfshook"
  14. "pbx-api-gin/pkg/utils"
  15. "strconv"
  16. "sync"
  17. "time"
  18. )
  19. var tagLog = 0
  20. func HandleStcCmd(ctx context.Context, conn net.Conn) {
  21. for {
  22. select {
  23. case <-ctx.Done():
  24. return
  25. default:
  26. var buf bytes.Buffer
  27. tmp := make([]byte, 1024)
  28. if conn != nil {
  29. n, err := conn.Read(tmp)
  30. if err != nil {
  31. if err != io.EOF {
  32. conn.Close()
  33. }
  34. return
  35. }
  36. buf.Write(tmp[:n])
  37. }
  38. for {
  39. packet, err := msgdata.ExtractPacket(&buf)
  40. if err != nil {
  41. break
  42. }
  43. go processPacket(packet)
  44. }
  45. }
  46. }
  47. }
  48. // 处理单个数据包(原 switch 逻辑迁移过来)
  49. func processPacket(packet []byte) {
  50. if len(packet) < 6 {
  51. lfshook.NewLogger().Logger.Infof("Get data wrong length from STC !")
  52. return
  53. }
  54. //for recv data log debug
  55. if packet[5] != 0x03 && packet[5] != 0x0c && packet[5] != 0x01 {
  56. lfshook.NewLogger().Logger.Infof("Get data from STC:%x", packet)
  57. }
  58. //check if the cmd type is avtive
  59. if packet[5] == 0x03 { // ACTIVE
  60. Active([2]byte{packet[8], packet[9]})
  61. return
  62. }
  63. //check if Master role
  64. if !active.Master {
  65. if tagLog == 0 {
  66. lfshook.NewLogger().Logger.Infof("=========Not Master Role Ignore data !=============")
  67. tagLog = 1
  68. }
  69. return
  70. }
  71. tagLog = 0
  72. switch packet[5] {
  73. case 0x01: //heartbeat
  74. break
  75. case 0x02: // STN
  76. if active.ActivedCab != "" {
  77. if priority.CheckPriority("STN") {
  78. action.InterruptRunningTask("STN") //STN interrupt other
  79. time.Sleep(time.Millisecond * 100) //wait endpoimt release
  80. StationAnn(packet)
  81. } else {
  82. alstatus.PaStatus("", "STN", "refuse")
  83. }
  84. }
  85. case 0x05: // SPC
  86. if active.ActivedCab != "" {
  87. if priority.CheckPriority("SPC") {
  88. action.InterruptRunningTask("SPC") //SPC interrupt other
  89. time.Sleep(time.Millisecond * 100) //wait endpoimt release
  90. SpecialAnn(packet)
  91. } else {
  92. alstatus.PaStatus("", "SPC", "refuse")
  93. }
  94. }
  95. case 0x06: // EMG
  96. if active.ActivedCab != "" {
  97. if priority.CheckPriority("EMG") {
  98. action.InterruptRunningTask("EMG") //EMG interrupt other
  99. time.Sleep(time.Millisecond * 100) //wait endpoimt release
  100. EmgMsg(packet)
  101. } else {
  102. alstatus.PaStatus("", "EMG", "refuse")
  103. }
  104. }
  105. case 0x07: // STOP
  106. AnnStop([4]byte{packet[8], packet[9], packet[10], packet[11]})
  107. case 0x08: // DCS
  108. if active.ActivedCab != "" {
  109. if priority.CheckPriority("DCS") {
  110. action.InterruptRunningTask("DCS") //DCS interrupt other
  111. time.Sleep(time.Millisecond * 100) //wait endpoimt release
  112. DcsAnn(packet)
  113. } else {
  114. alstatus.PaStatus("", "DCS", "refuse")
  115. }
  116. }
  117. case 0x09: // SELF CHECK
  118. if active.ActivedCab != "" {
  119. if priority.CheckPriority("CHK") {
  120. action.InterruptRunningTask("CHK") //CHK interrupt other
  121. time.Sleep(time.Millisecond * 100) //wait endpoimt release
  122. SelfCheck(packet)
  123. } else {
  124. alstatus.PaStatus("", "CHK", "refuse")
  125. }
  126. }
  127. case 0x0a: // Tone-test
  128. if active.ActivedCab != "" {
  129. if priority.CheckPriority("VOL") {
  130. action.InterruptRunningTask("VOL") //VOL interrupt other
  131. time.Sleep(time.Millisecond * 100) //wait endpoimt release
  132. ToneTest(packet)
  133. } else {
  134. alstatus.PaStatus("", "VOL", "refuse")
  135. }
  136. }
  137. case 0x0e: //TMS answer PAD
  138. if priority.CheckPriority("PAD-TMS") {
  139. //Before Answer PAD
  140. if packet[8] == 0x01 {
  141. action.InterruptRunningTask("PAD-TMS") //PAD-ICP interrupt other
  142. time.Sleep(time.Millisecond * 100) //wait endpoimt release
  143. }
  144. AlarmHandleTMS(packet)
  145. if active.QueueTimer != nil {
  146. if active.QueueTimer.Stop() {
  147. lfshook.NewLogger().Logger.Infof("=========Release PAD timer true !============")
  148. } else {
  149. lfshook.NewLogger().Logger.Infof("=========Release PAD timer false ! ============")
  150. }
  151. }
  152. } else {
  153. alstatus.PaStatus("", "PAD-TMS", "refuse")
  154. }
  155. case 0x0b: // reset all PAD
  156. AlarmHoldResetAll(packet[8]) // reset all pad
  157. case 0x0c: // Set PAD time oute
  158. PadTimeOutSetting(packet[8:]) // timeout setting
  159. case 0x0d: // ICP answer PAD
  160. if priority.CheckPriority("PAD-ICP") {
  161. //Before Answer PAD
  162. if packet[8] == 0x01 {
  163. action.InterruptRunningTask("PAD-ICP") //PAD-ICP interrupt other
  164. time.Sleep(time.Millisecond * 100) //wait endpoimt release
  165. }
  166. if active.QueueTimer != nil {
  167. if active.QueueTimer.Stop() {
  168. lfshook.NewLogger().Logger.Infof("=========Release PAD timer true !============")
  169. } else {
  170. lfshook.NewLogger().Logger.Infof("=========Release PAD timer false ! ============")
  171. }
  172. }
  173. AlarmHandleICP(packet)
  174. } else {
  175. alstatus.PaStatus("", "PAD-ICP", "refuse")
  176. }
  177. case 0xf1: //Set remote master
  178. //default:
  179. //fmt.Printf("Unknown command: %x\n", packet[5])
  180. }
  181. }
  182. func PadTimeOutSetting(data []byte) {
  183. Seconds := data[7]
  184. if Seconds != 0 {
  185. active.PADTimeout = int(Seconds)
  186. }
  187. }
  188. // STN , 自动报站广播
  189. func StationAnn(data []byte) (err error) {
  190. specialVoice := int(data[8])
  191. delay := data[9]
  192. cycleCount := data[10]
  193. datalen := int(data[11])
  194. filename := msgdata.SubstrByRune(string(data[12:]), 0, datalen-4)
  195. //set spc voice tag
  196. priority.SpecialVoice = specialVoice
  197. action.PlaybackPacu(strconv.Quote(filename), int(cycleCount), int(delay), "STN")
  198. return nil
  199. }
  200. // 激活信号
  201. func Active(data [2]byte) {
  202. //var info model.Sysinfo
  203. Signal := int(data[0])
  204. //check asterisk available
  205. if active.Master { // master true
  206. if !utils.CheckAsterisk() { //check asterisk not available and set master false
  207. active.Master = false
  208. utils.ExecCmd("/etc/init.d/asterisk", "stop")
  209. }
  210. } else { // master false, check and start asterisk
  211. //Master == false
  212. if !utils.CheckAsterisk() {
  213. if active.CabNum == "8" {
  214. utils.ExecCmd("/etc/init.d/asterisk", "start")
  215. }
  216. }
  217. //Master == false cab == 1
  218. if active.CabNum == "1" {
  219. if utils.CheckAsterisk() {
  220. utils.ExecCmd("/etc/init.d/asterisk", "stop")
  221. }
  222. }
  223. }
  224. switch Signal {
  225. case 0:
  226. if active.ActivedCab != "" {
  227. active.ActivedCab = ""
  228. action.InActiveHangup()
  229. }
  230. case 1:
  231. //active signal from 8 to 1
  232. if active.ActivedCab == "8" || active.ActivedCab == "" {
  233. active.ActivedCab = "1"
  234. action.InActiveHangup()
  235. }
  236. case 8:
  237. //active signal from 1 to 8
  238. if active.ActivedCab == "1" || active.ActivedCab == "" {
  239. active.ActivedCab = "8"
  240. action.InActiveHangup()
  241. }
  242. }
  243. }
  244. // SPC ,特殊服务消息广播
  245. func SpecialAnn(data []byte) {
  246. delay := data[8]
  247. cycleCount := data[9]
  248. datalen := int(data[10])
  249. filename := msgdata.SubstrByRune(string(data[11:]), 0, datalen-4)
  250. if int(cycleCount) == 255 {
  251. action.PlaybackPacu(strconv.Quote(filename), 9999999, int(delay), "SPC")
  252. } else {
  253. action.PlaybackPacu(strconv.Quote(filename), int(cycleCount), int(delay), "SPC")
  254. }
  255. }
  256. // EMG ,紧急服务消息广播
  257. func EmgMsg(data []byte) {
  258. delay := data[8]
  259. cycleCount := data[9]
  260. datalen := int(data[10])
  261. filename := msgdata.SubstrByRune(string(data[11:]), 0, datalen-4)
  262. if int(cycleCount) == 255 {
  263. action.PlaybackPacu(strconv.Quote(filename), 9999999, int(delay), "EMG")
  264. } else {
  265. action.PlaybackPacu(strconv.Quote(filename), int(cycleCount), int(delay), "EMG")
  266. }
  267. }
  268. // 停止指定类型广播
  269. func AnnStop(data [4]byte) {
  270. //lfshook.NewLogger().Logger.Infof("=========AnnStop Type %x", data[0])
  271. switch data[0] {
  272. case 0x03:
  273. action.HangupTask("DCS") //STOP DCS
  274. time.Sleep(time.Millisecond * 100) //wait endpoimt release
  275. case 0x04:
  276. action.HangupTask("EMG") //STOP EMG
  277. time.Sleep(time.Millisecond * 100) //wait endpoimt release
  278. case 0x07:
  279. action.HangupTask("SPC") //STOP SPC
  280. time.Sleep(time.Millisecond * 100) //wait endpoimt release
  281. case 0x08:
  282. action.HangupTask("STN") //STOP STN
  283. time.Sleep(time.Millisecond * 100) //wait endpoimt release
  284. case 0x09:
  285. action.HangupTask("CHK") //STOP CHK
  286. time.Sleep(time.Millisecond * 100) //wait endpoimt release
  287. case 0x0a:
  288. action.HangupTask("VOL") //STOP VOL
  289. time.Sleep(time.Millisecond * 100) //wait endpoimt release
  290. default:
  291. action.InterruptRunningTask("")
  292. time.Sleep(time.Millisecond * 100) //wait endpoimt release
  293. }
  294. }
  295. // DCS 语音
  296. func DcsAnn(data []byte) {
  297. delay := data[8]
  298. cycleCount := data[9]
  299. datalen := int(data[10])
  300. filename := msgdata.SubstrByRune(string(data[11:]), 0, datalen-4)
  301. if int(cycleCount) == 255 {
  302. action.PlaybackPacu(strconv.Quote(filename), 9999999, int(delay), "DCS")
  303. } else {
  304. action.PlaybackPacu(strconv.Quote(filename), int(cycleCount), int(delay), "DCS")
  305. }
  306. }
  307. // tone-test广播
  308. func ToneTest(data []byte) {
  309. check := data[8]
  310. delay := data[9]
  311. cycleCount := data[10]
  312. datalen := int(data[11])
  313. filename := msgdata.SubstrByRune(string(data[12:]), 0, datalen-4)
  314. switch check {
  315. case 0x01: //start
  316. action.PlaybackPacu(strconv.Quote(filename), int(cycleCount), int(delay), "VOL")
  317. case 0x02: //stop
  318. action.HangupAllExcept("")
  319. }
  320. }
  321. // 自检广播
  322. func SelfCheck(data []byte) {
  323. check := data[8]
  324. delay := data[9]
  325. //cycleCount := data[10]
  326. cycleCount := 0x32
  327. datalen := int(data[11])
  328. filename := msgdata.SubstrByRune(string(data[12:]), 0, datalen-4)
  329. switch check {
  330. case 0x01: //start
  331. action.PlaybackPacu(strconv.Quote(filename), int(cycleCount), int(delay), "CHK")
  332. case 0x02: //stop
  333. action.HangupAllExcept("")
  334. }
  335. }
  336. // 全局变量:记录正在抑制的 exten
  337. var (
  338. suppressedExts = sync.Map{} // map[string]struct{},值存在即表示被抑制
  339. //suppressionMu sync.Mutex // 保护初始化和清理操作(可选)
  340. )
  341. // suppressKey 生成用于抑制的 key(可以根据需求扩展)
  342. func suppressKey(exten string, handler byte) string {
  343. return fmt.Sprintf("%s_h%x", exten, handler)
  344. }
  345. // ICP操作乘客报警(根据激活信息判断转到1车还是8车================)
  346. func AlarmHandleICP(data []byte) {
  347. handler := data[8]
  348. carr := data[12]
  349. pos := data[13]
  350. exten := fmt.Sprintf("24%c%c", carr, pos)
  351. key := suppressKey(exten, handler)
  352. //Drop other handler in 2 sec
  353. //PACUs---call---->ICP1
  354. //PAD---->Chanspy(WEq)-->ICP1;PAD--->Call---->ICP2
  355. if handler == 0x01 {
  356. if _, loaded := suppressedExts.LoadOrStore(key, struct{}{}); loaded {
  357. lfshook.NewLogger().Logger.Infof("Suppressed duplicate ICP Alarm (handler=0x01) for exten: %s within 4 seconds", exten)
  358. return
  359. }
  360. time.AfterFunc(4*time.Second, func() {
  361. suppressedExts.Delete(key)
  362. lfshook.NewLogger().Logger.Debugf("Suppression released for key: %s", key)
  363. })
  364. }
  365. switch handler {
  366. case 0x01: //answer(ICP+Alarm+PACU)
  367. //NotifyPaiu(exten, "answer")
  368. priority.ICPAnswer = 1
  369. if priority.PADStart == 0 {
  370. alstatus.PaStatus("", "PAD", "start")
  371. priority.PADStart = 1
  372. }
  373. lfshook.NewLogger().Logger.Infof("================ ICP Answer PAD ================:%s ", exten)
  374. if active.ActivedCab == "1" {
  375. action.Dial("0402", "0511", "pad-rule-pacus", "ani1", exten, "1") // PACUs dial ICP1
  376. //goto ami event ConfbridgeJoin, ICP answer PAD
  377. } else if active.ActivedCab == "8" {
  378. action.Dial("0402", "0511", "pad-rule-pacus", "ani8", exten, "8") // PACUs dial ICP8
  379. //goto ami event ConfbridgeJoin, ICP answer PAD
  380. } else if active.ActivedCab == "" { // No cab occupied
  381. action.Dial("0402", "0511", "pad-rule-pacus", "ani1", exten, "1") // PACUs dial ICP1
  382. }
  383. case 0x02: //hold 重新放回队列里面
  384. active.NotifyPaiu(exten, "hold")
  385. err := action.RedirectInQueue(exten, "0300", "queues-icp-redirect", "1")
  386. if err != nil {
  387. lfshook.NewLogger().Info(err)
  388. }
  389. action.InterruptRunningTask("")
  390. time.Sleep(time.Millisecond * 100) //wait endpoimt release
  391. //action.HangupICP()
  392. case 0x03: //hangup
  393. //NotifyPaiu(exten, "hangup")
  394. lfshook.NewLogger().Logger.Infof("============ Hangup PAD-ICP =============== ")
  395. action.Hangup(exten) //Pad
  396. //action.HangupICP()
  397. action.HangupTask("PAD-ICP")
  398. }
  399. }
  400. // TMS操作乘客报警(根据激活信息判断转到1车还是8车================)
  401. func AlarmHandleTMS(data []byte) {
  402. handler := data[8]
  403. //extlen := data[9]
  404. carr := data[12]
  405. pos := data[13]
  406. exten := fmt.Sprintf("24%c%c", carr, pos)
  407. PacuNum := fmt.Sprintf("21%c%c", carr, pos)
  408. key := suppressKey(exten, handler)
  409. //Drop other handler in 2 sec
  410. // 只对 handler == 0x01 做 2 秒去重
  411. if handler == 0x01 {
  412. if _, loaded := suppressedExts.LoadOrStore(key, struct{}{}); loaded {
  413. lfshook.NewLogger().Logger.Infof("Suppressed duplicate ICP Alarm (handler=0x01) for exten: %s within 4 seconds", exten)
  414. return // 已存在,说明在2秒窗口期内,直接丢弃
  415. }
  416. // 设置4秒后删除该 key,允许下次通过
  417. time.AfterFunc(4*time.Second, func() {
  418. suppressedExts.Delete(key)
  419. lfshook.NewLogger().Logger.Debugf("Suppression released for key: %s", key)
  420. })
  421. }
  422. switch handler {
  423. case 0x01: //answer(ICP+Alarm+PACU)
  424. //PACU---call---->ICP1
  425. //PAD---->Chanspy(WEq)-->ICP1;PAD--->Call---->ICP2
  426. if priority.PADStart == 0 {
  427. alstatus.PaStatus("", "PAD", "start")
  428. priority.PADStart = 1
  429. }
  430. priority.ICPAnswer = 1
  431. lfshook.NewLogger().Logger.Infof("==============TMS Answer PAD Exten:%s PACU:%s==========", exten, PacuNum)
  432. if action.ExtenStatus(PacuNum) == "Idle" {
  433. if active.ActivedCab == "1" {
  434. action.Dial("0403", PacuNum, "default", PacuNum, exten, "1") // PACU dial ICP1
  435. //goto ami event BridgeEnter, ICP8 whisper ICP1
  436. } else if active.ActivedCab == "8" {
  437. action.Dial("0403", PacuNum, "default", PacuNum, exten, "8") // PACU dial ICP8
  438. //goto ami event BridgeEnter, ICP1 whisper ICP8
  439. } else if active.ActivedCab == "" { // No cab occupied
  440. action.Dial("0403", PacuNum, "default", PacuNum, exten, "1") // PACU dial ICP1
  441. }
  442. } else {
  443. action.RedirectInQueue(exten, "0405", "default", exten) // PAD dial ICPs
  444. }
  445. case 0x02: //hold 重新放回队列里面
  446. active.NotifyPaiu(exten, "hold")
  447. err := action.RedirectInQueue(exten, "0300", "queues-icp-redirect", "1")
  448. if err != nil {
  449. lfshook.NewLogger().Info(err)
  450. }
  451. action.HangupAllLocalChan()
  452. case 0x03: //hangup
  453. //NotifyPaiu(exten, "hangup")
  454. action.Hangup(exten) //Pad
  455. action.HangupTask("PAD-ICP")
  456. }
  457. }
  458. // 挂断所有报警器
  459. func AlarmHoldResetAll(handler byte) {
  460. //hangup all actived PAD
  461. action.HangupAllPAD()
  462. //hangup running task
  463. action.InterruptRunningTask("AlarmHoldResetAll") //Reset PAD ALL
  464. time.Sleep(time.Millisecond * 100) //wait endpoimt release
  465. }