stc-broadcast.go 14 KB

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