stc-broadcast.go 15 KB

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