stc-broadcast.go 10 KB

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