stc-broadcast.go 14 KB

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