eventServer.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. package eventServer
  2. import (
  3. "encoding/xml"
  4. "fmt"
  5. "github.com/sirupsen/logrus"
  6. mail "github.com/xhit/go-simple-mail/v2"
  7. "io"
  8. "io/ioutil"
  9. "lc-fangdaosha/model/app"
  10. "lc-fangdaosha/service"
  11. "log"
  12. "mime/multipart"
  13. "net/http"
  14. "strings"
  15. "time"
  16. )
  17. // MQDEvent (MQTT Data Event) 用于mqtt传输事件
  18. type MQDEvent struct {
  19. EventCode string `json:"eventCode"`
  20. EId int `json:"eId"`
  21. Ip string `json:"ip"`
  22. Type string `json:"type"`
  23. StartTime string `json:"startTime"`
  24. Name string `json:"name"`
  25. Data []byte `json:"data"`
  26. }
  27. func StartEventServer() {
  28. http.HandleFunc("/event", handler)
  29. logrus.Fatal("事件监听服务启动失败", http.ListenAndServe(":8850", nil))
  30. }
  31. func handler(w http.ResponseWriter, r *http.Request) {
  32. go func() {
  33. //监听主机应答固定,直接先应答
  34. w.WriteHeader(200)
  35. w.Header().Add("Date", time.Now().String())
  36. w.Header().Add("Connection", "close")
  37. }()
  38. logRequest(r)
  39. contentType := r.Header.Get("Content-Type")
  40. if strings.Contains(contentType, "application/xml") {
  41. bytes, err := ioutil.ReadAll(r.Body)
  42. if err != nil {
  43. logrus.Error("事件处理-读取错误:", err)
  44. return
  45. }
  46. var event EventNotificationAlert
  47. err = xml.Unmarshal(bytes, &event)
  48. if err != nil {
  49. logrus.Error("事件处理-解析错误:", err)
  50. return
  51. }
  52. //处理事件 todo 邮箱
  53. handleEvent_(event)
  54. } else if strings.Contains(contentType, "multipart/form-data") {
  55. handleMultipart(r)
  56. } else {
  57. logrus.WithField("Content-Type", contentType).Error("该Content-Type没有写处理逻辑")
  58. return
  59. }
  60. }
  61. //TODO 限制事件重复触发,一段时间内不重复发送邮件,但保持报警状态
  62. var eventService = service.ServiceGroupApp.AppServiceGroup.EventService
  63. var carInfoService = service.ServiceGroupApp.AppServiceGroup.CarInfoService
  64. // 处理多文件事件
  65. func handleMultipart(r *http.Request) {
  66. // todo 远程联动
  67. multipartReader := multipart.NewReader(r.Body, "boundary")
  68. var msg string //邮件消息
  69. // 循环读取每个 part
  70. var eventAlert EventNotificationAlert
  71. for {
  72. part, err := multipartReader.NextPart()
  73. if err == io.EOF {
  74. break
  75. }
  76. if err != nil {
  77. log.Println("Failed to read part:", err)
  78. continue
  79. }
  80. // 检查 part 的 Content-Disposition
  81. formName := part.FormName()
  82. //if formName != "intrusionImage" {
  83. if !strings.Contains(formName, "Image") {
  84. //不含图片的xml部分数据
  85. xmlData, err := ioutil.ReadAll(part)
  86. if err != nil {
  87. return
  88. }
  89. xml.Unmarshal(xmlData, &eventAlert)
  90. msg = handleEvent_(eventAlert)
  91. continue
  92. }
  93. //处理图片部分数据
  94. contentType := part.Header.Get("Content-Type")
  95. eventCode := part.Header.Get("Content-ID")
  96. picName := timeFmt(eventAlert.DateTime) + ".jpeg"
  97. data, _ := ioutil.ReadAll(part)
  98. if strings.Contains(eventAlert.ChannelName, "PlateNumber") {
  99. //todo 识别车牌,记录次数
  100. number, err := CallLicensePlateRecognitionAPI(data)
  101. if err != nil {
  102. fmt.Println("车牌识别失败:", err)
  103. //time.Sleep(1000)
  104. }
  105. //todo 处理车牌号
  106. carInfoService.ProcessPlateNumber(number)
  107. return
  108. }
  109. f := &mail.File{
  110. Name: picName,
  111. MimeType: contentType,
  112. Data: data,
  113. Inline: true,
  114. }
  115. picture := &app.Picture{
  116. Name: picName,
  117. Time: time.Now(),
  118. Mime: contentType,
  119. Size: len(data),
  120. }
  121. pictureData := &app.PictureData{
  122. Data: data,
  123. }
  124. event := &app.Event{
  125. EventCode: eventCode,
  126. MacAddress: eventAlert.MacAddress,
  127. EventType: eventAlert.EventType,
  128. }
  129. //保存图片
  130. go eventService.Save(event, picture, pictureData)
  131. //邮件通知
  132. SendAlarmEmail(eventAlert.MacAddress, msg, f)
  133. }
  134. }
  135. func handleEvent_(event EventNotificationAlert) string {
  136. var eType string
  137. if event.EventType == "duration" {
  138. eType = event.DurationList.Duration[0].RelationEvent
  139. } else {
  140. eType = event.EventType
  141. }
  142. return fmt.Sprintf("事件类型:%s,时间:%s", sMap[eType], timeFmt(event.DateTime))
  143. }
  144. func timeFmt(str string) string {
  145. s := strings.Split(str, "T")
  146. t := s[0]
  147. s1 := strings.Split(s[1], ".")
  148. s2 := strings.Split(s1[0], "+")
  149. return t + " " + s2[0]
  150. }
  151. func logRequest(req *http.Request) {
  152. // 打印请求行
  153. fmt.Printf("%s %s %s\n", req.Method, req.URL.Path, req.Proto)
  154. // 打印请求头
  155. for name, headers := range req.Header {
  156. for _, h := range headers {
  157. fmt.Printf("%v: %v\n", name, h)
  158. }
  159. }
  160. // 打印请求体
  161. body, _ := ioutil.ReadAll(req.Body)
  162. fmt.Printf("%s\n", body)
  163. }