stc-broadcast.go 14 KB

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