stc-broadcast.go 17 KB

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