eventServer.go 7.1 KB

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