stc-broadcast.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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. AlarmHandleICP(packet) //for test
  107. }
  108. case 0x0b:
  109. AlarmHoldResetAll(packet[8])
  110. case 0x0c:
  111. RecordStorageConf(packet[8:])
  112. case 0x0d:
  113. if priority.CheckPriority("PAD-ICP") {
  114. action.HangupAll()
  115. AlarmHandleICP(packet)
  116. }
  117. default:
  118. fmt.Printf("Unknown command: %x\n", packet[5])
  119. }
  120. }
  121. // STN , 自动报站广播
  122. func StationAnn(data []byte) (err error) {
  123. specialVoice := int(data[8])
  124. delay := data[9]
  125. cycleCount := data[10]
  126. datalen := int(data[11])
  127. filename := msgdata.SubstrByRune(string(data[12:]), 0, datalen-4)
  128. //set spc voice tag
  129. priority.SpecialVoice = specialVoice
  130. //Pa status report
  131. priority.RunningType, _ = strconv.Atoi(priority.Priority.STN)
  132. alstatus.PaStatus("", "STN", "start")
  133. action.PlaybackPacu(filename, int(cycleCount), int(delay), "STN")
  134. return nil
  135. }
  136. // 激活信号
  137. func Active(data [1]byte) {
  138. //var info model.Sysinfo
  139. active.Actived = true
  140. //Num := int(data[0])
  141. //lfshook.NewLogger().Logger.Infof("Active data : %x", Num)
  142. /*
  143. switch Num { // 设置全局的激活信号,并通过协议(待定)通知终端注册到对应的激活主机上
  144. case 0:
  145. lfshook.NewLogger().Logger.Infof("=================Inactive==================")
  146. info.Name = "cab_active"
  147. info.Value = "0"
  148. active.Actived = false
  149. _, er := mysql.DBOrmInstance.Where("name = ?", "cab_active").Update(&info)
  150. if er != nil {
  151. lfshook.NewLogger().Logger.Infof("update sysinfo err : %+v", er.Error())
  152. return
  153. }
  154. case 1:
  155. lfshook.NewLogger().Logger.Infof("=================active===MC1===============")
  156. if active.CabNum == "1" { // local cab is MC1
  157. info.Name = "cab_active"
  158. info.Value = "1"
  159. active.Actived = true
  160. } else {
  161. info.Name = "cab_active"
  162. info.Value = "0"
  163. active.Actived = false
  164. }
  165. _, er := mysql.DBOrmInstance.Where("name = ?", "cab_active").Update(&info)
  166. if er != nil {
  167. lfshook.NewLogger().Logger.Infof("update sysinfo err : %+v", er.Error())
  168. return
  169. }
  170. case 8:
  171. lfshook.NewLogger().Logger.Infof("=================active===MC8===============")
  172. if active.CabNum == "8" { //Local cab is MC8
  173. info.Name = "cab_active"
  174. info.Value = "1"
  175. active.Actived = true
  176. } else {
  177. info.Name = "cab_active"
  178. info.Value = "0"
  179. active.Actived = false
  180. }
  181. _, er := mysql.DBOrmInstance.Where("name = ?", "cab_active").Update(&info)
  182. if er != nil {
  183. lfshook.NewLogger().Logger.Infof("update sysinfo err : %+v", er.Error())
  184. return
  185. }
  186. }
  187. */
  188. }
  189. // SPC ,特殊服务消息广播
  190. func SpecialAnn(data []byte) {
  191. delay := data[8]
  192. cycleCount := data[9]
  193. datalen := int(data[10])
  194. filename := msgdata.SubstrByRune(string(data[11:]), 0, datalen-4)
  195. //Pa status report
  196. priority.RunningType, _ = strconv.Atoi(priority.Priority.SPCTMS)
  197. alstatus.PaStatus("", "SPC", "start")
  198. if int(cycleCount) == 255 {
  199. action.PlaybackPacu(filename, 9999999, int(delay), "SPC")
  200. } else {
  201. action.PlaybackPacu(filename, int(cycleCount), int(delay), "SPC")
  202. }
  203. }
  204. // EMG ,紧急服务消息广播
  205. func EmgMsg(data []byte) {
  206. delay := data[8]
  207. cycleCount := data[9]
  208. datalen := int(data[10])
  209. filename := msgdata.SubstrByRune(string(data[11:]), 0, datalen-4)
  210. //Pa status report
  211. priority.RunningType, _ = strconv.Atoi(priority.Priority.EMGTMS)
  212. alstatus.PaStatus("", "EMG", "start")
  213. if int(cycleCount) == 255 {
  214. action.PlaybackPacu(filename, 9999999, int(delay), "EMG")
  215. } else {
  216. action.PlaybackPacu(filename, int(cycleCount), int(delay), "EMG")
  217. }
  218. }
  219. // 停止指定类型广播
  220. func AnnStop(data [4]byte) {
  221. PaType := ""
  222. switch data[0] {
  223. case 0x03:
  224. PaType = "DCS"
  225. case 0x04:
  226. PaType = "EMG"
  227. case 0x07:
  228. PaType = "SPC"
  229. case 0x08:
  230. PaType = "STN"
  231. case 0x09:
  232. PaType = "CHK"
  233. }
  234. priority.RunningType = 0
  235. alstatus.PaStatus("", PaType, "end")
  236. action.HangupAll()
  237. }
  238. // DCS 语音
  239. func DcsAnn(data []byte) {
  240. delay := data[8]
  241. cycleCount := data[9]
  242. datalen := int(data[10])
  243. filename := msgdata.SubstrByRune(string(data[11:]), 0, datalen-4)
  244. //Pa status report
  245. priority.RunningType, _ = strconv.Atoi(priority.Priority.DCS)
  246. alstatus.PaStatus("", "DCS", "start")
  247. if int(cycleCount) == 255 {
  248. action.PlaybackPacu(filename, 9999999, int(delay), "DCS")
  249. } else {
  250. action.PlaybackPacu(filename, int(cycleCount), int(delay), "DCS")
  251. }
  252. }
  253. // 调音广播
  254. func VolumeAdjust(data []byte) {
  255. check := data[8]
  256. delay := data[9]
  257. cycleCount := data[10]
  258. datalen := int(data[11])
  259. filename := msgdata.SubstrByRune(string(data[12:]), 0, datalen-4)
  260. switch check {
  261. case 0x01: //start
  262. //Pa status report
  263. priority.RunningType, _ = strconv.Atoi(priority.Priority.CHK)
  264. alstatus.PaStatus("", "VOL", "start")
  265. action.PlaybackPacu(filename, int(cycleCount), int(delay), "VOL")
  266. case 0x02: //stop
  267. alstatus.PaStatus("", "VOL", "end")
  268. action.HangupAll()
  269. }
  270. }
  271. // 自检广播
  272. func SelfCheck(data []byte) {
  273. check := data[8]
  274. delay := data[9]
  275. cycleCount := data[10]
  276. datalen := int(data[11])
  277. filename := msgdata.SubstrByRune(string(data[12:]), 0, datalen-4)
  278. switch check {
  279. case 0x01: //start
  280. //Pa status report
  281. priority.RunningType, _ = strconv.Atoi(priority.Priority.CHK)
  282. alstatus.PaStatus("", "CHK", "start")
  283. action.PlaybackPacu(filename, int(cycleCount), int(delay), "CHK")
  284. case 0x02: //stop
  285. //Pa status report
  286. priority.RunningType = 0
  287. alstatus.PaStatus("", "CHK", "end")
  288. action.HangupAll()
  289. }
  290. }
  291. // 全局变量:记录正在抑制的 exten
  292. var (
  293. suppressedExts = sync.Map{} // map[string]struct{},值存在即表示被抑制
  294. //suppressionMu sync.Mutex // 保护初始化和清理操作(可选)
  295. )
  296. // suppressKey 生成用于抑制的 key(可以根据需求扩展)
  297. func suppressKey(exten string, handler byte) string {
  298. return fmt.Sprintf("%s_h%x", exten, handler)
  299. }
  300. // ICP操作乘客报警(根据激活信息判断转到1车还是8车================)
  301. func AlarmHandleICP(data []byte) {
  302. handler := data[8]
  303. carr := data[12]
  304. pos := data[13]
  305. exten := fmt.Sprintf("24%c%c", carr, pos)
  306. key := suppressKey(exten, handler)
  307. //Drop other handler in 2 sec
  308. //PACUs---call---->ICP1
  309. //PAD---->Chanspy(WEq)-->ICP1
  310. //ICP2--->Chanspy(Eq)---->PAD
  311. if handler == 0x01 {
  312. if _, loaded := suppressedExts.LoadOrStore(key, struct{}{}); loaded {
  313. lfshook.NewLogger().Logger.Infof("Suppressed duplicate ICP Alarm (handler=0x01) for exten: %s within 4 seconds", exten)
  314. return
  315. }
  316. time.AfterFunc(4*time.Second, func() {
  317. suppressedExts.Delete(key)
  318. lfshook.NewLogger().Logger.Debugf("Suppression released for key: %s", key)
  319. })
  320. }
  321. switch handler {
  322. case 0x01: //answer(ICP+Alarm+PACU)
  323. //NotifyPaiu(exten, "answer")
  324. priority.ICPAnswer = 1
  325. lfshook.NewLogger().Logger.Infof("================ICP Answer PAD================:%s ", exten)
  326. if active.CabNum == "1" && active.Actived {
  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.CabNum == "8" && active.Actived {
  330. action.Dial("0402", "0511", "pad-rule-pacus", "ani8", exten, "8") // PACUs dial ICP8
  331. //goto ami event ConfbridgeJoin, ICP answer PAD
  332. }
  333. case 0x02: //hold 重新放回队列里面
  334. NotifyPaiu(exten, "hold")
  335. err := action.RedirectInQueue(exten, "0300", "default", "1")
  336. if err != nil {
  337. lfshook.NewLogger().Info(err)
  338. }
  339. action.Hangup("2311") //1 车接听
  340. action.Hangup("2381") //8 车接听
  341. case 0x03: //hangup
  342. //NotifyPaiu(exten, "hangup")
  343. /* action.Hangup(exten) //Pad
  344. action.Hangup("2311") //1 车接听
  345. action.Hangup("2381") //8 车接听
  346. */
  347. action.HangupAll()
  348. }
  349. }
  350. // TMS操作乘客报警(根据激活信息判断转到1车还是8车================)
  351. func AlarmHandleTMS(data []byte) {
  352. handler := data[8]
  353. //extlen := data[9]
  354. carr := data[12]
  355. pos := data[13]
  356. exten := fmt.Sprintf("24%c%c", carr, pos)
  357. PacuNum := fmt.Sprintf("21%c%c", carr, pos)
  358. key := suppressKey(exten, handler)
  359. //Drop other handler in 2 sec
  360. // 只对 handler == 0x01 做 2 秒去重
  361. if handler == 0x01 {
  362. if _, loaded := suppressedExts.LoadOrStore(key, struct{}{}); loaded {
  363. lfshook.NewLogger().Logger.Infof("Suppressed duplicate ICP Alarm (handler=0x01) for exten: %s within 4 seconds", exten)
  364. return // 已存在,说明在2秒窗口期内,直接丢弃
  365. }
  366. // 设置4秒后删除该 key,允许下次通过
  367. time.AfterFunc(4*time.Second, func() {
  368. suppressedExts.Delete(key)
  369. lfshook.NewLogger().Logger.Debugf("Suppression released for key: %s", key)
  370. })
  371. }
  372. switch handler {
  373. case 0x01: //answer(ICP+Alarm+PACU)
  374. //PACU---call---->ICP1
  375. //PAD---->Chanspy(WEq)-->ICP1
  376. //ICP2--->spy(Eq)---->PAD
  377. priority.ICPAnswer = 1
  378. lfshook.NewLogger().Logger.Infof("================TMS Answer PAD:%s===PACU:%s==========", exten, PacuNum)
  379. if action.ExtenStatus(PacuNum) == "Idle" {
  380. if active.CabNum == "1" && active.Actived {
  381. action.Dial("0403", PacuNum, "default", PacuNum, exten, "1") // PACU dial ICP1
  382. //goto ami event BridgeEnter, ICP8 whisper ICP1
  383. } else if active.CabNum == "8" && active.Actived {
  384. action.Dial("0403", PacuNum, "default", PacuNum, exten, "8") // PACU dial ICP8
  385. //goto ami event BridgeEnter, ICP1 whisper ICP8
  386. }
  387. } else {
  388. action.RedirectInQueue(exten, "0405", "default", exten) // PAD dial ICPs
  389. }
  390. case 0x02: //hold 重新放回队列里面
  391. NotifyPaiu(exten, "hold")
  392. err := action.RedirectInQueue(exten, "0300", "default", "1")
  393. if err != nil {
  394. lfshook.NewLogger().Info(err)
  395. }
  396. action.Hangup("2311") //1 车接听
  397. action.Hangup("2381") //8 车接听
  398. case 0x03: //hangup
  399. //NotifyPaiu(exten, "hangup")
  400. /*action.Hangup(exten) //PAD
  401. action.Hangup("2311") //1 车接听
  402. action.Hangup("2381") //8 车接听
  403. */
  404. action.HangupAll()
  405. }
  406. }
  407. // 挂断所有报警器
  408. func NotifyPaiu(Exten, Action string) {
  409. url := ""
  410. switch Action {
  411. case "answer":
  412. url = fmt.Sprintf("http://10.0.24.%s/api/sipphone?action=answer", Exten[2:])
  413. case "hold":
  414. url = fmt.Sprintf("http://10.0.24.%s/api/sipphone?action=hold", Exten[2:])
  415. case "hangup":
  416. url = fmt.Sprintf("http://10.0.24.%s/api/sipphone?action=hangup", Exten[2:])
  417. }
  418. lfshook.NewLogger().Logger.Infof("======Notify PAIU Alarm====:%+v ", url)
  419. resp, err := http.Get(url)
  420. if err != nil {
  421. lfshook.NewLogger().Logger.Infof("======Notify PAIU Alarm====:%+v ", err)
  422. return
  423. }
  424. defer resp.Body.Close()
  425. /*
  426. body, err := io.ReadAll(resp.Body)
  427. if err != nil {
  428. // 读取数据错误
  429. lfshook.NewLogger().Warn("ioutil ReadAll failed :", err.Error())
  430. return
  431. }
  432. fmt.Printf("状态码: %d\n", resp.StatusCode)
  433. fmt.Printf("响应内容: %s\n", body)
  434. */
  435. }
  436. // 挂断所有报警器
  437. func AlarmHoldResetAll(data byte) {
  438. var AlarmExts []model.Extension
  439. er := mysql.DBOrmInstance.Where("dev_type = ? and status != ?", "PAIU", "Idle").Find(&AlarmExts)
  440. if er != nil {
  441. lfshook.NewLogger().Logger.Infof("update special voice to exten err : %+v", er.Error())
  442. }
  443. //all hold
  444. if data == 1 {
  445. for _, ext := range AlarmExts {
  446. err := action.RedirectInQueue(ext.Extension, "0300", "default", "1")
  447. if err != nil {
  448. lfshook.NewLogger().Info(err)
  449. }
  450. }
  451. if active.CabNum == "1" && active.Actived {
  452. action.Hangup("2311") //1 车接听
  453. alstatus.AlarmStatus("0000", "allhold") //send all hold status
  454. } else if active.CabNum == "8" && active.Actived {
  455. action.Hangup("2381") //8 车接听
  456. alstatus.AlarmStatus("0000", "allhold") // send all hold status
  457. }
  458. } else if data == 2 { //all reset
  459. for _, ext := range AlarmExts {
  460. action.Hangup(ext.Extension)
  461. }
  462. if active.CabNum == "1" && active.Actived {
  463. action.Hangup("2311") //1 车接听
  464. alstatus.AlarmStatus("0000", "allreset") //send all reset status
  465. } else if active.CabNum == "8" && active.Actived {
  466. action.Hangup("2381") //8 车接听
  467. alstatus.AlarmStatus("0000", "allreset") // send all reset status
  468. }
  469. }
  470. }
  471. func RecordStorageConf(data []byte) {
  472. var info model.RcdConf
  473. info.PadRcdEnable = int(data[0])
  474. info.PadRcdStorageDays = int(data[1])
  475. info.PaRcdStorageDays = int(data[2])
  476. info.CpaRcdStorageDays = int(data[3])
  477. info.PadRcdDelDays = int(data[4])
  478. info.PaRcdDelDays = int(data[5])
  479. info.CpaRcdDelDays = int(data[6])
  480. //info.OpaRcdStorageDays = int(data[7])
  481. //info.OpaRcdDelDays = int(data[8])
  482. //lfshook.NewLogger().Infof("=============Set record Conf : %+v", info)
  483. //update record config
  484. _, er := mysql.DBOrmInstance.AllCols().Update(&info)
  485. if er != nil {
  486. lfshook.NewLogger().Logger.Infof("update special voice to exten err : %+v", er.Error())
  487. }
  488. }