stc-broadcast.go 14 KB

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