stc-broadcast.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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.SetTimer {
  201. active.QueueTimer.Stop()
  202. active.SetTimer = false
  203. }
  204. } else {
  205. alstatus.PaStatus("", "PAD-TMS", "refuse")
  206. }
  207. case 0x0b: // reset all PAD
  208. AlarmHoldResetAll(packet[8]) // reset all pad
  209. //case 0x0c: // recored config
  210. // RecordStorageConf(packet[8:]) // RCD setting
  211. case 0x0d: // ICP answer PAD
  212. if priority.CheckPriority("PAD-ICP") {
  213. action.InterruptRunningTask("PAD-ICP") //PAD-ICP interrupt other
  214. if active.SetTimer {
  215. active.QueueTimer.Stop()
  216. active.SetTimer = false
  217. }
  218. AlarmHandleICP(packet) //
  219. } else {
  220. alstatus.PaStatus("", "PAD-ICP", "refuse")
  221. }
  222. //default:
  223. //fmt.Printf("Unknown command: %x\n", packet[5])
  224. }
  225. }
  226. // STN , 自动报站广播
  227. func StationAnn(data []byte) (err error) {
  228. specialVoice := int(data[8])
  229. delay := data[9]
  230. cycleCount := data[10]
  231. datalen := int(data[11])
  232. filename := msgdata.SubstrByRune(string(data[12:]), 0, datalen-4)
  233. //set spc voice tag
  234. priority.SpecialVoice = specialVoice
  235. action.PlaybackPacu(strconv.Quote(filename), int(cycleCount), int(delay), "STN")
  236. return nil
  237. }
  238. // 激活信号
  239. func Active(data [2]byte) {
  240. //var info model.Sysinfo
  241. //active.Actived = true
  242. Signal := int(data[0])
  243. Master := int(data[1])
  244. //lfshook.NewLogger().Logger.Infof("Active data : %x", Signal)
  245. if !active.Master && active.CabNum == "8" { //slave role , check the Master data from STC
  246. if Master == 8 {
  247. active.Master = true
  248. }
  249. } else if !active.Master && active.CabNum == "1" {
  250. if Master == 1 {
  251. active.Master = true
  252. }
  253. }
  254. if active.Master && !utils.IsAsteriskOn() {
  255. utils.ExecCmd("/etc/init.d/asterisk", "start")
  256. } else if !active.Master && utils.IsAsteriskOn() {
  257. utils.ExecCmd("/etc/init.d/asterisk", "stop")
  258. }
  259. switch Signal {
  260. case 0:
  261. //lfshook.NewLogger().Logger.Infof("=================Inactive==================")
  262. active.ActivedCab = ""
  263. action.InActiveHangup()
  264. case 1:
  265. active.ActivedCab = "1"
  266. //lfshook.NewLogger().Logger.Infof("=================active===MC1===============")
  267. case 8:
  268. active.ActivedCab = "8"
  269. //lfshook.NewLogger().Logger.Infof("=================active===MC8===============")
  270. }
  271. }
  272. // SPC ,特殊服务消息广播
  273. func SpecialAnn(data []byte) {
  274. delay := data[8]
  275. cycleCount := data[9]
  276. datalen := int(data[10])
  277. filename := msgdata.SubstrByRune(string(data[11:]), 0, datalen-4)
  278. if int(cycleCount) == 255 {
  279. action.PlaybackPacu(strconv.Quote(filename), 9999999, int(delay), "SPC")
  280. } else {
  281. action.PlaybackPacu(strconv.Quote(filename), int(cycleCount), int(delay), "SPC")
  282. }
  283. }
  284. // EMG ,紧急服务消息广播
  285. func EmgMsg(data []byte) {
  286. delay := data[8]
  287. cycleCount := data[9]
  288. datalen := int(data[10])
  289. filename := msgdata.SubstrByRune(string(data[11:]), 0, datalen-4)
  290. if int(cycleCount) == 255 {
  291. action.PlaybackPacu(strconv.Quote(filename), 9999999, int(delay), "EMG")
  292. } else {
  293. action.PlaybackPacu(strconv.Quote(filename), int(cycleCount), int(delay), "EMG")
  294. }
  295. }
  296. // 停止指定类型广播
  297. func AnnStop(data [4]byte) {
  298. lfshook.NewLogger().Logger.Infof("=========AnnStop Type %x", data[0])
  299. switch data[0] {
  300. case 0x03:
  301. action.HangupTask("DCS") //STOP DCS
  302. case 0x04:
  303. action.HangupTask("EMG") //STOP EMG
  304. case 0x07:
  305. action.HangupTask("SPC") //STOP SPC
  306. case 0x08:
  307. action.HangupTask("STN") //STOP STN
  308. case 0x09:
  309. action.HangupTask("CHK") //STOP CHK
  310. case 0x0a:
  311. action.HangupTask("VOL") //STOP VOL
  312. default:
  313. action.InterruptRunningTask("")
  314. }
  315. }
  316. // DCS 语音
  317. func DcsAnn(data []byte) {
  318. delay := data[8]
  319. cycleCount := data[9]
  320. datalen := int(data[10])
  321. filename := msgdata.SubstrByRune(string(data[11:]), 0, datalen-4)
  322. if int(cycleCount) == 255 {
  323. action.PlaybackPacu(strconv.Quote(filename), 9999999, int(delay), "DCS")
  324. } else {
  325. action.PlaybackPacu(strconv.Quote(filename), int(cycleCount), int(delay), "DCS")
  326. }
  327. }
  328. // tone-test广播
  329. func ToneTest(data []byte) {
  330. check := data[8]
  331. delay := data[9]
  332. cycleCount := data[10]
  333. datalen := int(data[11])
  334. filename := msgdata.SubstrByRune(string(data[12:]), 0, datalen-4)
  335. switch check {
  336. case 0x01: //start
  337. action.PlaybackPacu(strconv.Quote(filename), int(cycleCount), int(delay), "VOL")
  338. case 0x02: //stop
  339. action.HangupAllExcept("")
  340. }
  341. }
  342. // 自检广播
  343. func SelfCheck(data []byte) {
  344. check := data[8]
  345. delay := data[9]
  346. //cycleCount := data[10]
  347. cycleCount := 0x32
  348. datalen := int(data[11])
  349. filename := msgdata.SubstrByRune(string(data[12:]), 0, datalen-4)
  350. switch check {
  351. case 0x01: //start
  352. action.PlaybackPacu(strconv.Quote(filename), int(cycleCount), int(delay), "CHK")
  353. case 0x02: //stop
  354. action.HangupAllExcept("")
  355. }
  356. }
  357. // 全局变量:记录正在抑制的 exten
  358. var (
  359. suppressedExts = sync.Map{} // map[string]struct{},值存在即表示被抑制
  360. //suppressionMu sync.Mutex // 保护初始化和清理操作(可选)
  361. )
  362. // suppressKey 生成用于抑制的 key(可以根据需求扩展)
  363. func suppressKey(exten string, handler byte) string {
  364. return fmt.Sprintf("%s_h%x", exten, handler)
  365. }
  366. // ICP操作乘客报警(根据激活信息判断转到1车还是8车================)
  367. func AlarmHandleICP(data []byte) {
  368. handler := data[8]
  369. carr := data[12]
  370. pos := data[13]
  371. exten := fmt.Sprintf("24%c%c", carr, pos)
  372. key := suppressKey(exten, handler)
  373. //Drop other handler in 2 sec
  374. //PACUs---call---->ICP1
  375. //PAD---->Chanspy(WEq)-->ICP1;PAD--->Call---->ICP2
  376. if handler == 0x01 {
  377. if _, loaded := suppressedExts.LoadOrStore(key, struct{}{}); loaded {
  378. lfshook.NewLogger().Logger.Infof("Suppressed duplicate ICP Alarm (handler=0x01) for exten: %s within 4 seconds", exten)
  379. return
  380. }
  381. time.AfterFunc(4*time.Second, func() {
  382. suppressedExts.Delete(key)
  383. lfshook.NewLogger().Logger.Debugf("Suppression released for key: %s", key)
  384. })
  385. }
  386. switch handler {
  387. case 0x01: //answer(ICP+Alarm+PACU)
  388. //NotifyPaiu(exten, "answer")
  389. priority.ICPAnswer = 1
  390. if priority.PADStart == 0 {
  391. alstatus.PaStatus(exten, "PAD", "start")
  392. priority.PADStart = 1
  393. }
  394. lfshook.NewLogger().Logger.Infof("================ICP Answer PAD================:%s ", exten)
  395. if active.ActivedCab == "1" {
  396. action.Dial("0402", "0511", "pad-rule-pacus", "ani1", exten, "1") // PACUs dial ICP1
  397. //goto ami event ConfbridgeJoin, ICP answer PAD
  398. } else if active.ActivedCab == "8" {
  399. action.Dial("0402", "0511", "pad-rule-pacus", "ani8", exten, "8") // PACUs dial ICP8
  400. //goto ami event ConfbridgeJoin, ICP answer PAD
  401. } else if active.ActivedCab == "" { // No cab occupied
  402. action.Dial("0402", "0511", "pad-rule-pacus", "ani1", exten, "1") // PACUs dial ICP1
  403. }
  404. case 0x02: //hold 重新放回队列里面
  405. active.NotifyPaiu(exten, "hold")
  406. err := action.RedirectInQueue(exten, "0300", "queues-icp-redirect", "1")
  407. if err != nil {
  408. lfshook.NewLogger().Info(err)
  409. }
  410. action.InterruptRunningTask("")
  411. //action.HangupICP()
  412. case 0x03: //hangup
  413. //NotifyPaiu(exten, "hangup")
  414. lfshook.NewLogger().Logger.Infof("=============STC== Hangup PAD=============== ")
  415. action.Hangup(exten) //Pad
  416. //action.HangupICP()
  417. action.InterruptRunningTask("")
  418. }
  419. }
  420. // TMS操作乘客报警(根据激活信息判断转到1车还是8车================)
  421. func AlarmHandleTMS(data []byte) {
  422. handler := data[8]
  423. //extlen := data[9]
  424. carr := data[12]
  425. pos := data[13]
  426. exten := fmt.Sprintf("24%c%c", carr, pos)
  427. PacuNum := fmt.Sprintf("21%c%c", carr, pos)
  428. key := suppressKey(exten, handler)
  429. //Drop other handler in 2 sec
  430. // 只对 handler == 0x01 做 2 秒去重
  431. if handler == 0x01 {
  432. if _, loaded := suppressedExts.LoadOrStore(key, struct{}{}); loaded {
  433. lfshook.NewLogger().Logger.Infof("Suppressed duplicate ICP Alarm (handler=0x01) for exten: %s within 4 seconds", exten)
  434. return // 已存在,说明在2秒窗口期内,直接丢弃
  435. }
  436. // 设置4秒后删除该 key,允许下次通过
  437. time.AfterFunc(4*time.Second, func() {
  438. suppressedExts.Delete(key)
  439. lfshook.NewLogger().Logger.Debugf("Suppression released for key: %s", key)
  440. })
  441. }
  442. switch handler {
  443. case 0x01: //answer(ICP+Alarm+PACU)
  444. //PACU---call---->ICP1
  445. //PAD---->Chanspy(WEq)-->ICP1;PAD--->Call---->ICP2
  446. if priority.PADStart == 0 {
  447. alstatus.PaStatus(exten, "PAD", "start")
  448. priority.PADStart = 1
  449. }
  450. priority.ICPAnswer = 1
  451. lfshook.NewLogger().Logger.Infof("================TMS Answer PAD:%s===PACU:%s==========", exten, PacuNum)
  452. if action.ExtenStatus(PacuNum) == "Idle" {
  453. if active.ActivedCab == "1" {
  454. action.Dial("0403", PacuNum, "default", PacuNum, exten, "1") // PACU dial ICP1
  455. //goto ami event BridgeEnter, ICP8 whisper ICP1
  456. } else if active.ActivedCab == "8" {
  457. action.Dial("0403", PacuNum, "default", PacuNum, exten, "8") // PACU dial ICP8
  458. //goto ami event BridgeEnter, ICP1 whisper ICP8
  459. }
  460. } else {
  461. action.RedirectInQueue(exten, "0405", "default", exten) // PAD dial ICPs
  462. }
  463. case 0x02: //hold 重新放回队列里面
  464. active.NotifyPaiu(exten, "hold")
  465. err := action.RedirectInQueue(exten, "0300", "queues-icp-redirect", "1")
  466. if err != nil {
  467. lfshook.NewLogger().Info(err)
  468. }
  469. action.HangupAllLocalChan()
  470. case 0x03: //hangup
  471. //NotifyPaiu(exten, "hangup")
  472. action.Hangup(exten) //Pad
  473. action.HangupAllLocalChan()
  474. action.HangupICP()
  475. }
  476. }
  477. // 挂断所有报警器
  478. func AlarmHoldResetAll(handler byte) {
  479. //hangup all actived PAD
  480. action.HangupAllPAD()
  481. //hangup running task
  482. action.InterruptRunningTask("AlarmHoldResetAll") //Reset PAD ALL
  483. }
  484. /*
  485. func RecordStorageConf(data []byte) {
  486. var info model.RcdConf
  487. info.PadRcdEnable = strconv.Itoa(int(data[0]))
  488. info.PadRcdStorageDays = strconv.Itoa(int(data[1]))
  489. info.PaRcdStorageDays = strconv.Itoa(int(data[2]))
  490. info.CpaRcdStorageDays = strconv.Itoa(int(data[3]))
  491. info.PadRcdDelDays = strconv.Itoa(int(data[4]))
  492. info.PaRcdDelDays = strconv.Itoa(int(data[5]))
  493. info.CpaRcdDelDays = strconv.Itoa(int(data[6]))
  494. //info.OpaRcdStorageDays = int(data[7])
  495. //info.OpaRcdDelDays = int(data[8])
  496. //lfshook.NewLogger().Infof("=============Set record Conf : %+v", info)
  497. filePath := "/etc/asterisk/recording.conf"
  498. _, err := os.Stat(filePath)
  499. if err != nil {
  500. logrus.Error(err)
  501. return
  502. }
  503. iniFile, err := ini.Load(filePath)
  504. if err != nil {
  505. logrus.Error(err)
  506. return
  507. }
  508. iniFile.Section("general").Key("PADRCD").SetValue(info.PadRcdEnable)
  509. iniFile.Section("general").Key("PADRCDDAYS").SetValue(info.PadRcdStorageDays)
  510. iniFile.Section("general").Key("PARCDDAYS").SetValue(info.PaRcdStorageDays)
  511. iniFile.Section("general").Key("CPARCDDAYS").SetValue(info.CpaRcdStorageDays)
  512. iniFile.Section("general").Key("PADRCDDELDAYS").SetValue(info.PadRcdDelDays)
  513. iniFile.Section("general").Key("PARCDDELDAYS").SetValue(info.PaRcdDelDays)
  514. iniFile.Section("general").Key("CPARCDDELDAYS").SetValue(info.CpaRcdDelDays)
  515. iniFile.SaveTo(filePath)
  516. }
  517. */