stc-broadcast.go 15 KB

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