stc-broadcast.go 9.8 KB

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