stc-broadcast.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. package broadcast
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "io"
  7. "net"
  8. "net/http"
  9. "pbx-api-gin/internal/app/ami/action"
  10. "pbx-api-gin/internal/app/ami/model"
  11. "pbx-api-gin/internal/app/mysql"
  12. "pbx-api-gin/internal/app/stc/active"
  13. msgdata "pbx-api-gin/internal/app/stc/data"
  14. "pbx-api-gin/internal/app/stc/priority"
  15. alstatus "pbx-api-gin/internal/app/stc/sendstatus"
  16. "pbx-api-gin/pkg/lfshook"
  17. "strconv"
  18. "sync"
  19. "time"
  20. )
  21. var Pacus = []string{"2111", "2121", "2131", "2141", "2151", "2161", "2171", "2181"}
  22. func HandleStcCmd(ctx context.Context, conn net.Conn) {
  23. for {
  24. select {
  25. case <-ctx.Done():
  26. return
  27. default:
  28. var buf bytes.Buffer
  29. tmp := make([]byte, 1024)
  30. if conn != nil {
  31. n, err := conn.Read(tmp)
  32. if err != nil {
  33. if err != io.EOF {
  34. conn.Close()
  35. }
  36. return
  37. }
  38. buf.Write(tmp[:n])
  39. }
  40. for {
  41. packet, err := msgdata.ExtractPacket(&buf)
  42. if err != nil {
  43. break
  44. }
  45. go processPacket(packet)
  46. }
  47. }
  48. }
  49. }
  50. // 处理单个数据包(原 switch 逻辑迁移过来)
  51. func processPacket(packet []byte) {
  52. if len(packet) < 6 {
  53. fmt.Println("Invalid packet length")
  54. return
  55. }
  56. //for recv data log debug
  57. if packet[5] != 0x03 && packet[5] != 0x0c && packet[5] != 0x01 {
  58. lfshook.NewLogger().Logger.Infof("Get data from STC ===============:%x", packet)
  59. }
  60. //check if the cmd type is avtive
  61. if packet[5] == 0x03 { // ACTIVE
  62. Active([1]byte{packet[8]})
  63. return
  64. }
  65. //check if actived
  66. if !active.Actived {
  67. lfshook.NewLogger().Logger.Infof("===========Inactived retrun==============")
  68. return
  69. }
  70. switch packet[5] {
  71. case 0x01:
  72. break
  73. case 0x02: // STN
  74. if priority.CheckPriority("STN") {
  75. action.HangupAll()
  76. StationAnn(packet)
  77. }
  78. case 0x05: // SPC
  79. if priority.CheckPriority("SPC-TMS") {
  80. action.HangupAll()
  81. SpecialAnn(packet)
  82. }
  83. case 0x06: // EMG
  84. EmgMsg(packet)
  85. case 0x07: // STOP
  86. AnnStop([4]byte{packet[8], packet[9], packet[10], packet[11]})
  87. case 0x08: // DCS
  88. if priority.CheckPriority("DCS") {
  89. action.HangupAll()
  90. DcsAnn(packet)
  91. }
  92. case 0x09: // SELF CHECK
  93. if priority.CheckPriority("CHK") {
  94. action.HangupAll()
  95. SelfCheck(packet)
  96. }
  97. case 0x10: // SELF CHECK
  98. if priority.CheckPriority("CHK") {
  99. action.HangupAll()
  100. VolumeAdjust(packet)
  101. }
  102. case 0x0a:
  103. if priority.CheckPriority("PAD-TMS") {
  104. action.HangupAll()
  105. AlarmHandleTMS(packet)
  106. }
  107. case 0x0b:
  108. AlarmHoldResetAll(packet[8])
  109. case 0x0c:
  110. RecordStorageConf(packet[8:])
  111. case 0x0d:
  112. if priority.CheckPriority("PAD-ICP") {
  113. action.HangupAll()
  114. AlarmHandleICP(packet)
  115. }
  116. default:
  117. fmt.Printf("Unknown command: %x\n", packet[5])
  118. }
  119. }
  120. // STN , 自动报站广播
  121. func StationAnn(data []byte) (err error) {
  122. specialVoice := int(data[8])
  123. delay := data[9]
  124. cycleCount := data[10]
  125. datalen := int(data[11])
  126. filename := msgdata.SubstrByRune(string(data[12:]), 0, datalen-4)
  127. //set spc voice tag
  128. priority.SpecialVoice = specialVoice
  129. //Pa status report
  130. priority.RunningType, _ = strconv.Atoi(priority.Priority.STN)
  131. alstatus.PaStatus("", "STN", "start")
  132. action.PlaybackPacu(filename, int(cycleCount), int(delay), "STN")
  133. return nil
  134. }
  135. // 激活信号
  136. func Active(data [1]byte) {
  137. //var info model.Sysinfo
  138. active.Actived = true
  139. //Num := int(data[0])
  140. //lfshook.NewLogger().Logger.Infof("Active data : %x", Num)
  141. /*
  142. switch Num { // 设置全局的激活信号,并通过协议(待定)通知终端注册到对应的激活主机上
  143. case 0:
  144. lfshook.NewLogger().Logger.Infof("=================Inactive==================")
  145. info.Name = "cab_active"
  146. info.Value = "0"
  147. active.Actived = false
  148. _, er := mysql.DBOrmInstance.Where("name = ?", "cab_active").Update(&info)
  149. if er != nil {
  150. lfshook.NewLogger().Logger.Infof("update sysinfo err : %+v", er.Error())
  151. return
  152. }
  153. case 1:
  154. lfshook.NewLogger().Logger.Infof("=================active===MC1===============")
  155. if active.CabNum == "1" { // local cab is MC1
  156. info.Name = "cab_active"
  157. info.Value = "1"
  158. active.Actived = true
  159. } else {
  160. info.Name = "cab_active"
  161. info.Value = "0"
  162. active.Actived = false
  163. }
  164. _, er := mysql.DBOrmInstance.Where("name = ?", "cab_active").Update(&info)
  165. if er != nil {
  166. lfshook.NewLogger().Logger.Infof("update sysinfo err : %+v", er.Error())
  167. return
  168. }
  169. case 8:
  170. lfshook.NewLogger().Logger.Infof("=================active===MC8===============")
  171. if active.CabNum == "8" { //Local cab is MC8
  172. info.Name = "cab_active"
  173. info.Value = "1"
  174. active.Actived = true
  175. } else {
  176. info.Name = "cab_active"
  177. info.Value = "0"
  178. active.Actived = false
  179. }
  180. _, er := mysql.DBOrmInstance.Where("name = ?", "cab_active").Update(&info)
  181. if er != nil {
  182. lfshook.NewLogger().Logger.Infof("update sysinfo err : %+v", er.Error())
  183. return
  184. }
  185. }
  186. */
  187. }
  188. // SPC ,特殊服务消息广播
  189. func SpecialAnn(data []byte) {
  190. delay := data[8]
  191. cycleCount := data[9]
  192. datalen := int(data[10])
  193. filename := msgdata.SubstrByRune(string(data[11:]), 0, datalen-4)
  194. //Pa status report
  195. priority.RunningType, _ = strconv.Atoi(priority.Priority.SPCTMS)
  196. alstatus.PaStatus("", "SPC", "start")
  197. if int(cycleCount) == 255 {
  198. action.PlaybackPacu(filename, 9999999, int(delay), "SPC")
  199. } else {
  200. action.PlaybackPacu(filename, int(cycleCount), int(delay), "SPC")
  201. }
  202. }
  203. // EMG ,紧急服务消息广播
  204. func EmgMsg(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. //Pa status report
  210. priority.RunningType, _ = strconv.Atoi(priority.Priority.EMGTMS)
  211. alstatus.PaStatus("", "EMG", "start")
  212. if int(cycleCount) == 255 {
  213. action.PlaybackPacu(filename, 9999999, int(delay), "EMG")
  214. } else {
  215. action.PlaybackPacu(filename, int(cycleCount), int(delay), "EMG")
  216. }
  217. }
  218. // 停止指定类型广播
  219. func AnnStop(data [4]byte) {
  220. PaType := ""
  221. switch data[0] {
  222. case 0x03:
  223. PaType = "DCS"
  224. case 0x04:
  225. PaType = "EMG"
  226. case 0x07:
  227. PaType = "SPC"
  228. case 0x08:
  229. PaType = "STN"
  230. case 0x09:
  231. PaType = "CHK"
  232. }
  233. priority.RunningType = 0
  234. alstatus.PaStatus("", PaType, "end")
  235. /*
  236. for _, ext := range Pacus {
  237. action.Hangup(ext)
  238. }
  239. //update pa type
  240. _, er := mysql.DBOrmInstance.Cols("patype").Where("pa_type = ?", RunningType).Update(&model.Extension{PaType: ""})
  241. if er != nil {
  242. lfshook.NewLogger().Logger.Infof("update special voice to exten err : %+v", er.Error())
  243. }
  244. */
  245. action.HangupAll()
  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. //Pa status report
  254. priority.RunningType, _ = strconv.Atoi(priority.Priority.DCS)
  255. alstatus.PaStatus("", "DCS", "start")
  256. if int(cycleCount) == 255 {
  257. action.PlaybackPacu(filename, 9999999, int(delay), "DCS")
  258. } else {
  259. action.PlaybackPacu(filename, int(cycleCount), int(delay), "DCS")
  260. }
  261. }
  262. // 调音广播
  263. func VolumeAdjust(data []byte) {
  264. check := data[8]
  265. delay := data[9]
  266. cycleCount := data[10]
  267. datalen := int(data[11])
  268. filename := msgdata.SubstrByRune(string(data[12:]), 0, datalen-4)
  269. switch check {
  270. case 0x01: //start
  271. //Pa status report
  272. priority.RunningType, _ = strconv.Atoi(priority.Priority.CHK)
  273. alstatus.PaStatus("", "VOL", "start")
  274. action.PlaybackPacu(filename, int(cycleCount), int(delay), "VOL")
  275. case 0x02: //stop
  276. /* //Pa status report
  277. priority.RunningType = 0
  278. alstatus.PaStatus("", "VOL", "end")
  279. for _, ext := range Pacus {
  280. asterisk.Hangup(ext)
  281. }
  282. asterisk.Hangup("2311")
  283. asterisk.Hangup("2381")
  284. */
  285. action.HangupAll()
  286. }
  287. }
  288. // 自检广播
  289. func SelfCheck(data []byte) {
  290. check := data[8]
  291. delay := data[9]
  292. cycleCount := data[10]
  293. datalen := int(data[11])
  294. filename := msgdata.SubstrByRune(string(data[12:]), 0, datalen-4)
  295. switch check {
  296. case 0x01: //start
  297. //Pa status report
  298. priority.RunningType, _ = strconv.Atoi(priority.Priority.CHK)
  299. alstatus.PaStatus("", "CHK", "start")
  300. action.PlaybackPacu(filename, int(cycleCount), int(delay), "CHK")
  301. case 0x02: //stop
  302. //Pa status report
  303. priority.RunningType = 0
  304. alstatus.PaStatus("", "CHK", "end")
  305. /*
  306. for _, ext := range Pacus {
  307. asterisk.Hangup(ext)
  308. }
  309. asterisk.Hangup("2311")
  310. asterisk.Hangup("2381")
  311. */
  312. action.HangupAll()
  313. }
  314. }
  315. // 全局变量:记录正在抑制的 exten
  316. var (
  317. suppressedExts = sync.Map{} // map[string]struct{},值存在即表示被抑制
  318. //suppressionMu sync.Mutex // 保护初始化和清理操作(可选)
  319. )
  320. // suppressKey 生成用于抑制的 key(可以根据需求扩展)
  321. func suppressKey(exten string, handler byte) string {
  322. return fmt.Sprintf("%s_h%x", exten, handler)
  323. }
  324. // ICP操作乘客报警(根据激活信息判断转到1车还是8车================)
  325. func AlarmHandleICP(data []byte) {
  326. handler := data[8]
  327. carr := data[12]
  328. pos := data[13]
  329. exten := fmt.Sprintf("24%c%c", carr, pos)
  330. key := suppressKey(exten, handler)
  331. //Drop other handler in 2 sec
  332. if handler == 0x01 {
  333. if _, loaded := suppressedExts.LoadOrStore(key, struct{}{}); loaded {
  334. lfshook.NewLogger().Logger.Infof("Suppressed duplicate ICP Alarm (handler=0x01) for exten: %s within 4 seconds", exten)
  335. return
  336. }
  337. time.AfterFunc(4*time.Second, func() {
  338. suppressedExts.Delete(key)
  339. lfshook.NewLogger().Logger.Debugf("Suppression released for key: %s", key)
  340. })
  341. }
  342. switch handler {
  343. case 0x01: //answer(ICP+Alarm+PACU)
  344. //NotifyPaiu(exten, "answer")
  345. priority.ICPAnswer = 1
  346. lfshook.NewLogger().Logger.Infof("================ICP Answer PAD================:%s ", exten)
  347. if active.CabNum == "1" && active.Actived {
  348. action.Dial("0402", "0511", "pad-rule-pacus", "ani1", exten, "1") // PACUs dial ICP1
  349. //goto ami event ConfbridgeJoin, ICP answer PAD
  350. } else if active.CabNum == "8" && active.Actived {
  351. action.Dial("0402", "0511", "pad-rule-pacus", "ani8", exten, "8") // PACUs dial ICP8
  352. //goto ami event ConfbridgeJoin, ICP answer PAD
  353. }
  354. case 0x02: //hold 重新放回队列里面
  355. NotifyPaiu(exten, "hold")
  356. err := action.RedirectInQueue(exten, "0300", "default", "1")
  357. if err != nil {
  358. lfshook.NewLogger().Info(err)
  359. }
  360. action.Hangup("2311") //1 车接听
  361. action.Hangup("2381") //8 车接听
  362. case 0x03: //hangup
  363. //NotifyPaiu(exten, "hangup")
  364. /* action.Hangup(exten) //Pad
  365. action.Hangup("2311") //1 车接听
  366. action.Hangup("2381") //8 车接听
  367. */
  368. action.HangupAll()
  369. }
  370. }
  371. // TMS操作乘客报警(根据激活信息判断转到1车还是8车================)
  372. func AlarmHandleTMS(data []byte) {
  373. handler := data[8]
  374. //extlen := data[9]
  375. carr := data[12]
  376. pos := data[13]
  377. exten := fmt.Sprintf("24%c%c", carr, pos)
  378. PacuNum := fmt.Sprintf("21%c%c", carr, pos)
  379. key := suppressKey(exten, handler)
  380. //Drop other handler in 2 sec
  381. // 只对 handler == 0x01 做 2 秒去重
  382. if handler == 0x01 {
  383. if _, loaded := suppressedExts.LoadOrStore(key, struct{}{}); loaded {
  384. lfshook.NewLogger().Logger.Infof("Suppressed duplicate ICP Alarm (handler=0x01) for exten: %s within 4 seconds", exten)
  385. return // 已存在,说明在2秒窗口期内,直接丢弃
  386. }
  387. // 设置4秒后删除该 key,允许下次通过
  388. time.AfterFunc(4*time.Second, func() {
  389. suppressedExts.Delete(key)
  390. lfshook.NewLogger().Logger.Debugf("Suppression released for key: %s", key)
  391. })
  392. }
  393. switch handler {
  394. case 0x01: //answer(ICP+Alarm+PACU)
  395. //PACU---call---->ICP1
  396. //PAD---->Chanspy(WEq)-->ICP1
  397. //ICP2--->spy(Eq)---->PAD
  398. priority.ICPAnswer = 1
  399. lfshook.NewLogger().Logger.Infof("================TMS Answer PAD:%s===PACU:%s==========", exten, PacuNum)
  400. if action.ExtenStatus(PacuNum) == "Idle" {
  401. if active.CabNum == "1" && active.Actived {
  402. action.Dial("0403", PacuNum, "default", PacuNum, exten, "1") // PACU dial ICP1
  403. //goto ami event BridgeEnter, ICP8 whisper ICP1
  404. } else if active.CabNum == "8" && active.Actived {
  405. action.Dial("0403", PacuNum, "default", PacuNum, exten, "8") // PACU dial ICP8
  406. //goto ami event BridgeEnter, ICP1 whisper ICP8
  407. }
  408. } else {
  409. action.RedirectInQueue(exten, "0405", "default", "PAD") // PAD dial ICPs
  410. }
  411. case 0x02: //hold 重新放回队列里面
  412. NotifyPaiu(exten, "hold")
  413. err := action.RedirectInQueue(exten, "0300", "default", "1")
  414. if err != nil {
  415. lfshook.NewLogger().Info(err)
  416. }
  417. action.Hangup("2311") //1 车接听
  418. action.Hangup("2381") //8 车接听
  419. case 0x03: //hangup
  420. //NotifyPaiu(exten, "hangup")
  421. /*action.Hangup(exten) //PAD
  422. action.Hangup("2311") //1 车接听
  423. action.Hangup("2381") //8 车接听
  424. */
  425. action.HangupAll()
  426. }
  427. }
  428. // 挂断所有报警器
  429. func NotifyPaiu(Exten, Action string) {
  430. url := ""
  431. switch Action {
  432. case "answer":
  433. url = fmt.Sprintf("http://10.0.24.%s/api/sipphone?action=answer", Exten[2:])
  434. case "hold":
  435. url = fmt.Sprintf("http://10.0.24.%s/api/sipphone?action=hold", Exten[2:])
  436. case "hangup":
  437. url = fmt.Sprintf("http://10.0.24.%s/api/sipphone?action=hangup", Exten[2:])
  438. }
  439. lfshook.NewLogger().Logger.Infof("======Notify PAIU Alarm====:%+v ", url)
  440. resp, err := http.Get(url)
  441. if err != nil {
  442. lfshook.NewLogger().Logger.Infof("======Notify PAIU Alarm====:%+v ", err)
  443. return
  444. }
  445. defer resp.Body.Close()
  446. /*
  447. body, err := io.ReadAll(resp.Body)
  448. if err != nil {
  449. // 读取数据错误
  450. lfshook.NewLogger().Warn("ioutil ReadAll failed :", err.Error())
  451. return
  452. }
  453. fmt.Printf("状态码: %d\n", resp.StatusCode)
  454. fmt.Printf("响应内容: %s\n", body)
  455. */
  456. }
  457. // 挂断所有报警器
  458. func AlarmHoldResetAll(data byte) {
  459. var AlarmExts []model.Extension
  460. er := mysql.DBOrmInstance.Where("dev_type = ? and status != ?", "PAIU", "Idle").Find(&AlarmExts)
  461. if er != nil {
  462. lfshook.NewLogger().Logger.Infof("update special voice to exten err : %+v", er.Error())
  463. }
  464. //all hold
  465. if data == 1 {
  466. for _, ext := range AlarmExts {
  467. err := action.RedirectInQueue(ext.Extension, "0300", "default", "1")
  468. if err != nil {
  469. lfshook.NewLogger().Info(err)
  470. }
  471. }
  472. if active.CabNum == "1" && active.Actived {
  473. action.Hangup("2311") //1 车接听
  474. alstatus.AlarmStatus("0000", "allhold") //send all hold status
  475. } else if active.CabNum == "8" && active.Actived {
  476. action.Hangup("2381") //8 车接听
  477. alstatus.AlarmStatus("0000", "allhold") // send all hold status
  478. }
  479. } else if data == 2 { //all reset
  480. for _, ext := range AlarmExts {
  481. action.Hangup(ext.Extension)
  482. }
  483. if active.CabNum == "1" && active.Actived {
  484. action.Hangup("2311") //1 车接听
  485. alstatus.AlarmStatus("0000", "allreset") //send all reset status
  486. } else if active.CabNum == "8" && active.Actived {
  487. action.Hangup("2381") //8 车接听
  488. alstatus.AlarmStatus("0000", "allreset") // send all reset status
  489. }
  490. }
  491. }
  492. func RecordStorageConf(data []byte) {
  493. var info model.RcdConf
  494. info.PadRcdEnable = int(data[0])
  495. info.PadRcdStorageDays = int(data[1])
  496. info.PaRcdStorageDays = int(data[2])
  497. info.CpaRcdStorageDays = int(data[3])
  498. info.PadRcdDelDays = int(data[4])
  499. info.PaRcdDelDays = int(data[5])
  500. info.CpaRcdDelDays = int(data[6])
  501. //info.OpaRcdStorageDays = int(data[7])
  502. //info.OpaRcdDelDays = int(data[8])
  503. //lfshook.NewLogger().Infof("=============Set record Conf : %+v", info)
  504. //update record config
  505. _, er := mysql.DBOrmInstance.AllCols().Update(&info)
  506. if er != nil {
  507. lfshook.NewLogger().Logger.Infof("update special voice to exten err : %+v", er.Error())
  508. }
  509. }