stc-broadcast.go 9.8 KB

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