stc-broadcast.go 15 KB

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