stc-broadcast.go 13 KB

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