stc-broadcast.go 16 KB

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