stc-broadcast.go 16 KB

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