stc-broadcast.go 11 KB

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