stc-broadcast.go 9.6 KB

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