stc-broadcast.go 12 KB

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