eventServer.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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/global"
  10. "lc-fangdaosha/model/app"
  11. "lc-fangdaosha/service"
  12. "log"
  13. "math"
  14. "mime/multipart"
  15. "net/http"
  16. "strconv"
  17. "strings"
  18. "time"
  19. )
  20. // MQDEvent (MQTT Data Event) 用于mqtt传输事件
  21. type MQDEvent struct {
  22. EventCode string `json:"eventCode"`
  23. EId int `json:"eId"`
  24. Ip string `json:"ip"`
  25. Type string `json:"type"`
  26. StartTime string `json:"startTime"`
  27. Name string `json:"name"`
  28. Data []byte `json:"data"`
  29. }
  30. func StartEventServer() {
  31. //记录长宽高
  32. go func() {
  33. for {
  34. l, w, h := CalcCap()
  35. time.Sleep(500 * time.Millisecond)
  36. //todo 根据长宽高估计车厢体积
  37. fmt.Println("长", l, "宽", w, "高", h)
  38. }
  39. }()
  40. http.HandleFunc("/event", handler)
  41. logrus.Fatal("事件监听服务启动失败", http.ListenAndServe(":8850", nil))
  42. }
  43. func handler(w http.ResponseWriter, r *http.Request) {
  44. go func() {
  45. //监听主机应答固定,直接先应答
  46. w.WriteHeader(200)
  47. w.Header().Add("Date", time.Now().String())
  48. w.Header().Add("Connection", "close")
  49. }()
  50. logRequest(r)
  51. contentType := r.Header.Get("Content-Type")
  52. if strings.Contains(contentType, "application/xml") {
  53. bytes, err := ioutil.ReadAll(r.Body)
  54. if err != nil {
  55. logrus.Error("事件处理-读取错误:", err)
  56. return
  57. }
  58. var event EventNotificationAlert
  59. err = xml.Unmarshal(bytes, &event)
  60. if err != nil {
  61. logrus.Error("事件处理-解析错误:", err)
  62. return
  63. }
  64. //处理事件 todo 邮箱
  65. handleEvent_(event)
  66. } else if strings.Contains(contentType, "multipart/form-data") {
  67. handleMultipart(r)
  68. } else {
  69. logrus.WithField("Content-Type", contentType).Error("该Content-Type没有写处理逻辑")
  70. return
  71. }
  72. }
  73. //TODO 限制事件重复触发,一段时间内不重复发送邮件,但保持报警状态
  74. var eventService = service.ServiceGroupApp.AppServiceGroup.EventService
  75. var carInfoService = service.ServiceGroupApp.AppServiceGroup.CarInfoService
  76. // 保留小数
  77. func round(num float64, places int) float64 {
  78. shift := math.Pow(10, float64(places))
  79. return math.Round(num*shift) / shift
  80. }
  81. var bulk = make(map[string][]float64)
  82. // 处理多文件事件
  83. func handleMultipart(r *http.Request) {
  84. // todo 远程联动
  85. multipartReader := multipart.NewReader(r.Body, "boundary")
  86. var msg string //邮件消息
  87. // 循环读取每个 part
  88. var eventAlert EventNotificationAlert
  89. for {
  90. part, err := multipartReader.NextPart()
  91. if err == io.EOF {
  92. break
  93. }
  94. if err != nil {
  95. log.Println("Failed to read part:", err)
  96. continue
  97. }
  98. // 检查 part 的 Content-Disposition
  99. formName := part.FormName()
  100. //if formName != "intrusionImage" {
  101. if !strings.Contains(formName, "Image") {
  102. //不含图片的xml部分数据
  103. xmlData, err := ioutil.ReadAll(part)
  104. if err != nil {
  105. return
  106. }
  107. xml.Unmarshal(xmlData, &eventAlert)
  108. msg = handleEvent_(eventAlert)
  109. continue
  110. }
  111. //处理图片部分数据
  112. contentType := part.Header.Get("Content-Type")
  113. eventCode := part.Header.Get("Content-ID")
  114. picName := timeFmt(eventAlert.DateTime) + ".jpeg"
  115. data, _ := ioutil.ReadAll(part)
  116. if strings.Contains(eventAlert.ChannelName, "plateNumber") {
  117. // 识别车牌,记录次数
  118. number, err := CallLicensePlateRecognitionAPI(data)
  119. if err != nil {
  120. fmt.Println("车牌识别失败:", err)
  121. //time.Sleep(1000)
  122. }
  123. //todo 处理车牌号
  124. carInfoService.ProcessPlateNumber(number)
  125. return
  126. }
  127. if strings.Contains(eventAlert.ChannelName, "metering1") {
  128. //测量车的长度和高度
  129. targetRect := eventAlert.DetectionRegionList.DetectionRegionEntry[0].TargetRect
  130. //x, _ := strconv.ParseFloat(targetRect.X, 64)
  131. y, _ := strconv.ParseFloat(targetRect.Y, 64)
  132. h, _ := strconv.ParseFloat(targetRect.Height, 64)
  133. w, _ := strconv.ParseFloat(targetRect.Width, 64)
  134. n := int(round(y+h, 1) * 10)
  135. b := float64(global.Config.Metering.Camera1.B[n])
  136. a := float64(global.Config.Metering.Camera1.A[n])
  137. rh := h / (y + h) * b
  138. rl := w * a
  139. //dateTime := eventAlert.DateTime
  140. //bulk[dateTime] = append(bulk[dateTime], rh, rl)
  141. LhChan <- [2]float64{rl, rh}
  142. return
  143. }
  144. if strings.Contains(eventAlert.ChannelName, "metering2") {
  145. //todo 测量车的宽度
  146. targetRect := eventAlert.DetectionRegionList.DetectionRegionEntry[0].TargetRect
  147. //x, _ := strconv.ParseFloat(targetRect.X, 64)
  148. y, _ := strconv.ParseFloat(targetRect.Y, 64)
  149. h, _ := strconv.ParseFloat(targetRect.Height, 64)
  150. w, _ := strconv.ParseFloat(targetRect.Width, 64)
  151. n := int(round(y+h, 1) * 10)
  152. a := float64(global.Config.Metering.Camera2.A[n])
  153. rw := w * a
  154. WChan <- rw
  155. //dateTime := eventAlert.DateTime
  156. //bulk[dateTime] = append(bulk[dateTime], rw)
  157. //// 识别车牌,记录次数
  158. //number, err := CallLicensePlateRecognitionAPI(data)
  159. //if err != nil {
  160. // fmt.Println("车牌识别失败:", err)
  161. // //time.Sleep(1000)
  162. //}
  163. //// 处理车牌号
  164. //carInfoService.ProcessPlateNumber(number)
  165. return
  166. }
  167. f := &mail.File{
  168. Name: picName,
  169. MimeType: contentType,
  170. Data: data,
  171. Inline: true,
  172. }
  173. picture := &app.Picture{
  174. Name: picName,
  175. Time: time.Now(),
  176. Mime: contentType,
  177. Size: len(data),
  178. }
  179. pictureData := &app.PictureData{
  180. Data: data,
  181. }
  182. event := &app.Event{
  183. EventCode: eventCode,
  184. MacAddress: eventAlert.MacAddress,
  185. EventType: eventAlert.EventType,
  186. }
  187. //保存图片
  188. go eventService.Save(event, picture, pictureData)
  189. //邮件通知
  190. SendAlarmEmail(eventAlert.MacAddress, msg, f)
  191. }
  192. }
  193. func handleEvent_(event EventNotificationAlert) string {
  194. var eType string
  195. if event.EventType == "duration" {
  196. eType = event.DurationList.Duration[0].RelationEvent
  197. } else {
  198. eType = event.EventType
  199. }
  200. return fmt.Sprintf("事件类型:%s,时间:%s", sMap[eType], timeFmt(event.DateTime))
  201. }
  202. func timeFmt(str string) string {
  203. s := strings.Split(str, "T")
  204. t := s[0]
  205. s1 := strings.Split(s[1], ".")
  206. s2 := strings.Split(s1[0], "+")
  207. return t + " " + s2[0]
  208. }
  209. func logRequest(req *http.Request) {
  210. // 打印请求行
  211. fmt.Printf("%s %s %s\n", req.Method, req.URL.Path, req.Proto)
  212. // 打印请求头
  213. for name, headers := range req.Header {
  214. for _, h := range headers {
  215. fmt.Printf("%v: %v\n", name, h)
  216. }
  217. }
  218. // 打印请求体
  219. body, _ := ioutil.ReadAll(req.Body)
  220. fmt.Printf("%s\n", body)
  221. }