package service import ( "fmt" "net" "regexp" "smartIntersection_edge/util/config" "smartIntersection_edge/util/logger" "strconv" "strings" "time" ) var ( Devices = make(map[string]*Device) ) type Device struct { Info *config.Screens Conn net.Conn IsLogin bool LastTime time.Time SumHighSpeed int SumLowSpeed int } // 实例所有设备 func InitDevices() { //// 将数据库中的设备全部离线 //screens, _ := dao.QueryAllScreens() //for _, screen := range screens { // Devices[screen.Sn] = &Device{Info: screen} //} } func (s *Device) Start(conn net.Conn) { s.Conn = conn go s.Process() } func (s *Device) Process() { // 函数执行完之后关闭连接 defer s.Conn.Close() for { buf := make([]byte, 256) // 将tcp连接读取到的数据读取到byte数组中, 返回读取到的byte的数目 n, err := s.Conn.Read(buf) if err != nil { // 从客户端读取数据的过程中发生错误 这里如果没读到可以视为设备离线了 logger.Logger.Errorf("read err,dev offLine") break } data := string(buf[:n]) fmt.Println("读取", string(buf[:n]), time.Now()) if data[2:7] == "login" { s.Conn.Write([]byte("login:successful")) } if data[2:11] == "heartbeat" { //默认一分钟发一次心跳 s.LastTime = time.Now() if !s.IsLogin { s.Conn.Write([]byte("{'trans':'on'}")) //开启上传状态 screens := FindScreenBySN(data[20:44]) s.Info = screens s.IsLogin = true Devices[data[20:44]] = s topic := MqttService.GetTopic(s.Info.Sn, TopicChanStatus) err := MqttService.Publish(topic, 1) if err != nil { continue } } Devices[data[20:44]].Conn = s.Conn logger.Logger.Infof("%v 设备心跳", s.Info.ScreensName) } //判断超速 if strings.Contains(data, `"status":"highspeed"`) { s.SumLowSpeed = 0 re := regexp.MustCompile(`"speed1":"(\d+)"`) match := re.FindStringSubmatch(data) if len(match) > 1 { speed1, _ := strconv.Atoi(match[1]) if speed1 > 50 { //大于50认为超速 s.SumHighSpeed++ if s.SumHighSpeed >= 3 { //连续三次认为超速 topic := MqttService.GetTopic(s.Info.Sn, TopicHighSpeed) MqttService.Publish(topic, time.Now()) //上报当前超速时间 } } else { s.SumHighSpeed = 0 } } else { fmt.Println("Speed1 not found") continue } } //判断低速 if strings.Contains(data, `"status":"normalspeed"`) { s.SumHighSpeed = 0 re := regexp.MustCompile(`"speed1":"(\d+)"`) match := re.FindStringSubmatch(data) if len(match) > 1 { speed1, _ := strconv.Atoi(match[1]) if speed1 < 10 { //小于10认为低速 s.SumLowSpeed++ if s.SumLowSpeed >= 6 { //连续8次认为低速 topic := MqttService.GetTopic(s.Info.Sn, TopicLowSpeed) MqttService.Publish(topic, time.Now()) //上报当前低俗时间 } } else { s.SumLowSpeed = 0 } } else { fmt.Println("Speed1 not found") continue } } //if strings.Contains(data, `"status":"none"`) { // s.SumHighSpeed = 0 // s.SumLowSpeed = 0 //} } } func FindScreenBySN(sn string) *config.Screens { for _, screen := range config.DevConfig.Screens { if screen != nil && screen.Sn == sn { return screen } } return nil }