stc-broadcast.go 15 KB

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