stc-broadcast.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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. lfshook.NewLogger().Logger.Infof("Get data wrong length from STC !")
  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. break
  70. case 0x02: // STN
  71. if active.ActivedCab != "" {
  72. if priority.CheckPriority("STN") {
  73. action.InterruptRunningTask("STN") //STN interrupt other
  74. StationAnn(packet)
  75. } else {
  76. alstatus.PaStatus("", "STN", "refuse")
  77. }
  78. }
  79. case 0x05: // SPC
  80. if active.ActivedCab != "" {
  81. if priority.CheckPriority("SPC") {
  82. action.InterruptRunningTask("SPC") //SPC interrupt other
  83. SpecialAnn(packet)
  84. } else {
  85. alstatus.PaStatus("", "SPC", "refuse")
  86. }
  87. }
  88. case 0x06: // EMG
  89. if active.ActivedCab != "" {
  90. if priority.CheckPriority("EMG") {
  91. action.InterruptRunningTask("EMG") //EMG interrupt other
  92. EmgMsg(packet)
  93. } else {
  94. alstatus.PaStatus("", "EMG", "refuse")
  95. }
  96. }
  97. case 0x07: // STOP
  98. AnnStop([4]byte{packet[8], packet[9], packet[10], packet[11]})
  99. case 0x08: // DCS
  100. if active.ActivedCab != "" {
  101. if priority.CheckPriority("DCS") {
  102. action.InterruptRunningTask("DCS") //DCS interrupt other
  103. DcsAnn(packet)
  104. } else {
  105. alstatus.PaStatus("", "DCS", "refuse")
  106. }
  107. }
  108. case 0x09: // SELF CHECK
  109. if active.ActivedCab != "" {
  110. if priority.CheckPriority("CHK") {
  111. action.InterruptRunningTask("CHK") //CHK interrupt other
  112. SelfCheck(packet)
  113. } else {
  114. alstatus.PaStatus("", "CHK", "refuse")
  115. }
  116. }
  117. case 0x0a: // Tone-test
  118. if active.ActivedCab != "" {
  119. if priority.CheckPriority("VOL") {
  120. action.InterruptRunningTask("VOL") //VOL interrupt other
  121. ToneTest(packet)
  122. } else {
  123. alstatus.PaStatus("", "VOL", "refuse")
  124. }
  125. }
  126. case 0x0e: //TMS answer PAD
  127. if priority.CheckPriority("PAD-TMS") {
  128. //Before Answer PAD
  129. if packet[8] == 0x01 {
  130. action.InterruptRunningTask("PAD-TMS") //PAD-ICP interrupt other
  131. }
  132. AlarmHandleTMS(packet)
  133. if active.SetTimer {
  134. active.QueueTimer.Stop()
  135. active.SetTimer = false
  136. }
  137. } else {
  138. alstatus.PaStatus("", "PAD-TMS", "refuse")
  139. }
  140. case 0x0b: // reset all PAD
  141. AlarmHoldResetAll(packet[8]) // reset all pad
  142. //case 0x0c: // recored config
  143. // RecordStorageConf(packet[8:]) // RCD setting
  144. case 0x0d: // ICP answer PAD
  145. if priority.CheckPriority("PAD-ICP") {
  146. //Before Answer PAD
  147. if packet[8] == 0x01 {
  148. action.InterruptRunningTask("PAD-ICP") //PAD-ICP interrupt other
  149. }
  150. if active.SetTimer {
  151. active.QueueTimer.Stop()
  152. active.SetTimer = false
  153. }
  154. AlarmHandleICP(packet)
  155. } else {
  156. alstatus.PaStatus("", "PAD-ICP", "refuse")
  157. }
  158. case 0xf1: //Set remote master
  159. //default:
  160. //fmt.Printf("Unknown command: %x\n", packet[5])
  161. }
  162. }
  163. // STN , 自动报站广播
  164. func StationAnn(data []byte) (err error) {
  165. specialVoice := int(data[8])
  166. delay := data[9]
  167. cycleCount := data[10]
  168. datalen := int(data[11])
  169. filename := msgdata.SubstrByRune(string(data[12:]), 0, datalen-4)
  170. //set spc voice tag
  171. priority.SpecialVoice = specialVoice
  172. action.PlaybackPacu(strconv.Quote(filename), int(cycleCount), int(delay), "STN")
  173. return nil
  174. }
  175. // 激活信号
  176. func Active(data [2]byte) {
  177. //var info model.Sysinfo
  178. Signal := int(data[0])
  179. //check asterisk available
  180. if active.Master { // master true
  181. if !utils.CheckAsterisk() { //check asterisk not available and set master false
  182. active.Master = false
  183. utils.ExecCmd("/etc/init.d/asterisk", "stop")
  184. }
  185. } else { // master false, check and start asterisk
  186. //Master == false
  187. if !utils.CheckAsterisk() {
  188. if active.CabNum == "8" {
  189. utils.ExecCmd("/etc/init.d/asterisk", "start")
  190. }
  191. }
  192. //Master == false cab == 1
  193. if active.CabNum == "1" {
  194. if utils.CheckAsterisk() {
  195. utils.ExecCmd("/etc/init.d/asterisk", "stop")
  196. }
  197. }
  198. }
  199. switch Signal {
  200. case 0:
  201. active.ActivedCab = ""
  202. action.InActiveHangup()
  203. case 1:
  204. active.ActivedCab = "1"
  205. case 8:
  206. active.ActivedCab = "8"
  207. }
  208. }
  209. // SPC ,特殊服务消息广播
  210. func SpecialAnn(data []byte) {
  211. delay := data[8]
  212. cycleCount := data[9]
  213. datalen := int(data[10])
  214. filename := msgdata.SubstrByRune(string(data[11:]), 0, datalen-4)
  215. if int(cycleCount) == 255 {
  216. action.PlaybackPacu(strconv.Quote(filename), 9999999, int(delay), "SPC")
  217. } else {
  218. action.PlaybackPacu(strconv.Quote(filename), int(cycleCount), int(delay), "SPC")
  219. }
  220. }
  221. // EMG ,紧急服务消息广播
  222. func EmgMsg(data []byte) {
  223. delay := data[8]
  224. cycleCount := data[9]
  225. datalen := int(data[10])
  226. filename := msgdata.SubstrByRune(string(data[11:]), 0, datalen-4)
  227. if int(cycleCount) == 255 {
  228. action.PlaybackPacu(strconv.Quote(filename), 9999999, int(delay), "EMG")
  229. } else {
  230. action.PlaybackPacu(strconv.Quote(filename), int(cycleCount), int(delay), "EMG")
  231. }
  232. }
  233. // 停止指定类型广播
  234. func AnnStop(data [4]byte) {
  235. //lfshook.NewLogger().Logger.Infof("=========AnnStop Type %x", data[0])
  236. switch data[0] {
  237. case 0x03:
  238. action.HangupTask("DCS") //STOP DCS
  239. case 0x04:
  240. action.HangupTask("EMG") //STOP EMG
  241. case 0x07:
  242. action.HangupTask("SPC") //STOP SPC
  243. case 0x08:
  244. action.HangupTask("STN") //STOP STN
  245. case 0x09:
  246. action.HangupTask("CHK") //STOP CHK
  247. case 0x0a:
  248. action.HangupTask("VOL") //STOP VOL
  249. default:
  250. action.InterruptRunningTask("")
  251. }
  252. }
  253. // DCS 语音
  254. func DcsAnn(data []byte) {
  255. delay := data[8]
  256. cycleCount := data[9]
  257. datalen := int(data[10])
  258. filename := msgdata.SubstrByRune(string(data[11:]), 0, datalen-4)
  259. if int(cycleCount) == 255 {
  260. action.PlaybackPacu(strconv.Quote(filename), 9999999, int(delay), "DCS")
  261. } else {
  262. action.PlaybackPacu(strconv.Quote(filename), int(cycleCount), int(delay), "DCS")
  263. }
  264. }
  265. // tone-test广播
  266. func ToneTest(data []byte) {
  267. check := data[8]
  268. delay := data[9]
  269. cycleCount := data[10]
  270. datalen := int(data[11])
  271. filename := msgdata.SubstrByRune(string(data[12:]), 0, datalen-4)
  272. switch check {
  273. case 0x01: //start
  274. action.PlaybackPacu(strconv.Quote(filename), int(cycleCount), int(delay), "VOL")
  275. case 0x02: //stop
  276. action.HangupAllExcept("")
  277. }
  278. }
  279. // 自检广播
  280. func SelfCheck(data []byte) {
  281. check := data[8]
  282. delay := data[9]
  283. //cycleCount := data[10]
  284. cycleCount := 0x32
  285. datalen := int(data[11])
  286. filename := msgdata.SubstrByRune(string(data[12:]), 0, datalen-4)
  287. switch check {
  288. case 0x01: //start
  289. action.PlaybackPacu(strconv.Quote(filename), int(cycleCount), int(delay), "CHK")
  290. case 0x02: //stop
  291. action.HangupAllExcept("")
  292. }
  293. }
  294. // 全局变量:记录正在抑制的 exten
  295. var (
  296. suppressedExts = sync.Map{} // map[string]struct{},值存在即表示被抑制
  297. //suppressionMu sync.Mutex // 保护初始化和清理操作(可选)
  298. )
  299. // suppressKey 生成用于抑制的 key(可以根据需求扩展)
  300. func suppressKey(exten string, handler byte) string {
  301. return fmt.Sprintf("%s_h%x", exten, handler)
  302. }
  303. // ICP操作乘客报警(根据激活信息判断转到1车还是8车================)
  304. func AlarmHandleICP(data []byte) {
  305. handler := data[8]
  306. carr := data[12]
  307. pos := data[13]
  308. exten := fmt.Sprintf("24%c%c", carr, pos)
  309. key := suppressKey(exten, handler)
  310. //Drop other handler in 2 sec
  311. //PACUs---call---->ICP1
  312. //PAD---->Chanspy(WEq)-->ICP1;PAD--->Call---->ICP2
  313. if handler == 0x01 {
  314. if _, loaded := suppressedExts.LoadOrStore(key, struct{}{}); loaded {
  315. lfshook.NewLogger().Logger.Infof("Suppressed duplicate ICP Alarm (handler=0x01) for exten: %s within 4 seconds", exten)
  316. return
  317. }
  318. time.AfterFunc(4*time.Second, func() {
  319. suppressedExts.Delete(key)
  320. lfshook.NewLogger().Logger.Debugf("Suppression released for key: %s", key)
  321. })
  322. }
  323. switch handler {
  324. case 0x01: //answer(ICP+Alarm+PACU)
  325. //NotifyPaiu(exten, "answer")
  326. priority.ICPAnswer = 1
  327. if priority.PADStart == 0 {
  328. alstatus.PaStatus("", "PAD", "start")
  329. priority.PADStart = 1
  330. }
  331. lfshook.NewLogger().Logger.Infof("================ ICP Answer PAD ================:%s ", exten)
  332. if active.ActivedCab == "1" {
  333. action.Dial("0402", "0511", "pad-rule-pacus", "ani1", exten, "1") // PACUs dial ICP1
  334. //goto ami event ConfbridgeJoin, ICP answer PAD
  335. } else if active.ActivedCab == "8" {
  336. action.Dial("0402", "0511", "pad-rule-pacus", "ani8", exten, "8") // PACUs dial ICP8
  337. //goto ami event ConfbridgeJoin, ICP answer PAD
  338. } else if active.ActivedCab == "" { // No cab occupied
  339. action.Dial("0402", "0511", "pad-rule-pacus", "ani1", exten, "1") // PACUs dial ICP1
  340. }
  341. case 0x02: //hold 重新放回队列里面
  342. active.NotifyPaiu(exten, "hold")
  343. err := action.RedirectInQueue(exten, "0300", "queues-icp-redirect", "1")
  344. if err != nil {
  345. lfshook.NewLogger().Info(err)
  346. }
  347. action.InterruptRunningTask("")
  348. //action.HangupICP()
  349. case 0x03: //hangup
  350. //NotifyPaiu(exten, "hangup")
  351. lfshook.NewLogger().Logger.Infof("============ Hangup PAD-ICP =============== ")
  352. action.Hangup(exten) //Pad
  353. //action.HangupICP()
  354. action.HangupTask("PAD-ICP")
  355. }
  356. }
  357. // TMS操作乘客报警(根据激活信息判断转到1车还是8车================)
  358. func AlarmHandleTMS(data []byte) {
  359. handler := data[8]
  360. //extlen := data[9]
  361. carr := data[12]
  362. pos := data[13]
  363. exten := fmt.Sprintf("24%c%c", carr, pos)
  364. PacuNum := fmt.Sprintf("21%c%c", carr, pos)
  365. key := suppressKey(exten, handler)
  366. //Drop other handler in 2 sec
  367. // 只对 handler == 0x01 做 2 秒去重
  368. if handler == 0x01 {
  369. if _, loaded := suppressedExts.LoadOrStore(key, struct{}{}); loaded {
  370. lfshook.NewLogger().Logger.Infof("Suppressed duplicate ICP Alarm (handler=0x01) for exten: %s within 4 seconds", exten)
  371. return // 已存在,说明在2秒窗口期内,直接丢弃
  372. }
  373. // 设置4秒后删除该 key,允许下次通过
  374. time.AfterFunc(4*time.Second, func() {
  375. suppressedExts.Delete(key)
  376. lfshook.NewLogger().Logger.Debugf("Suppression released for key: %s", key)
  377. })
  378. }
  379. switch handler {
  380. case 0x01: //answer(ICP+Alarm+PACU)
  381. //PACU---call---->ICP1
  382. //PAD---->Chanspy(WEq)-->ICP1;PAD--->Call---->ICP2
  383. if priority.PADStart == 0 {
  384. alstatus.PaStatus("", "PAD", "start")
  385. priority.PADStart = 1
  386. }
  387. priority.ICPAnswer = 1
  388. lfshook.NewLogger().Logger.Infof("==============TMS Answer PAD Exten:%s PACU:%s==========", exten, PacuNum)
  389. if action.ExtenStatus(PacuNum) == "Idle" {
  390. if active.ActivedCab == "1" {
  391. action.Dial("0403", PacuNum, "default", PacuNum, exten, "1") // PACU dial ICP1
  392. //goto ami event BridgeEnter, ICP8 whisper ICP1
  393. } else if active.ActivedCab == "8" {
  394. action.Dial("0403", PacuNum, "default", PacuNum, exten, "8") // PACU dial ICP8
  395. //goto ami event BridgeEnter, ICP1 whisper ICP8
  396. }
  397. } else {
  398. action.RedirectInQueue(exten, "0405", "default", exten) // PAD dial ICPs
  399. }
  400. case 0x02: //hold 重新放回队列里面
  401. active.NotifyPaiu(exten, "hold")
  402. err := action.RedirectInQueue(exten, "0300", "queues-icp-redirect", "1")
  403. if err != nil {
  404. lfshook.NewLogger().Info(err)
  405. }
  406. action.HangupAllLocalChan()
  407. case 0x03: //hangup
  408. //NotifyPaiu(exten, "hangup")
  409. action.Hangup(exten) //Pad
  410. action.HangupTask("PAD-ICP")
  411. }
  412. }
  413. // 挂断所有报警器
  414. func AlarmHoldResetAll(handler byte) {
  415. //hangup all actived PAD
  416. action.HangupAllPAD()
  417. //hangup running task
  418. action.InterruptRunningTask("AlarmHoldResetAll") //Reset PAD ALL
  419. }