stc-broadcast.go 11 KB

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