Browse Source

优化代码3.1

chengqian 4 months ago
parent
commit
111ee0d634

+ 21 - 18
server/api/v1/devices/dev_screens.go

@@ -118,26 +118,29 @@ func (s *ScreensApi) UpdateScreens(c *gin.Context) {
 	}
 
 	screens := devices.Screens{
-		ID:            sc.ID,
-		ScreensName:   sc.ScreensName,
-		ScreensCode:   sc.ScreensCode,
-		Sn:            sc.Sn,
-		Network:       sc.Network,
-		ScreensBrand:  sc.ScreensBrand,
-		ScreensModel:  sc.ScreensModel,
-		IPAddress:     sc.IpAddress,
-		GatewayId:     sc.GatewayID,
-		ResolutionId:  sc.ResolutionId,
-		ScreensSizeId: sc.ScreensSizeId,
-		Shunt:         sc.Shunt,
-		ShuntDescribe: sc.ShuntDescribe,
-		InstallTime:   sc.InstallTime,
-		SwitchSn:      sc.SwitchSn,
-	}
-	err = ScreensService.UpdateScreens(screens)
+		ID:              sc.ID,
+		ScreensName:     sc.ScreensName,
+		ScreensCode:     sc.ScreensCode,
+		Sn:              sc.Sn,
+		Network:         sc.Network,
+		ScreensBrand:    sc.ScreensBrand,
+		ScreensModel:    sc.ScreensModel,
+		IPAddress:       sc.IpAddress,
+		GatewayId:       sc.GatewayID,
+		ResolutionId:    sc.ResolutionId,
+		ScreensSizeId:   sc.ScreensSizeId,
+		Shunt:           sc.Shunt,
+		ShuntDescribe:   sc.ShuntDescribe,
+		InstallTime:     sc.InstallTime,
+		SwitchSn:        sc.SwitchSn,
+		Status:          sc.Status,
+		LastOnlineTime:  sc.LastOnlineTime,
+		LastOfflineTime: sc.LastOfflineTime,
+	}
+	err = ScreensService.UpdateScreens(screens, sc.OldSn)
 	if err != nil {
 		global.GVA_LOG.Error("设置失败!", zap.Error(err))
-		response.FailWithMessage("设置失败", c)
+		response.FailWithMessage(err.Error(), c)
 		return
 	}
 	response.OkWithMessage("设置成功", c)

BIN
server/build/smart_intersection


+ 25 - 22
server/dao/devices/dev_screens.go

@@ -25,8 +25,8 @@ type Screens struct {
 	Status          int            `gorm:"type:int;default:0" json:"status"`                  //在线状态 0=离线,1=在线
 	DayBright       int            `gorm:"type:int;default:100" json:"dayBright"`             //白天亮度
 	NightBright     int            `gorm:"type:int;default:10" json:"nightBright"`            //晚上亮度
-	LastOnlineTime  time.Time      `gorm:"type:datetime;default:NULL" json:"lastOnlineTime"`  //最近在线时间
-	LastOfflineTime time.Time      `gorm:"type:datetime;default:NULL" json:"lastOfflineTime"` //最近离线时间
+	LastOnlineTime  *time.Time     `gorm:"type:datetime;default:NULL" json:"lastOnlineTime"`  //最近在线时间
+	LastOfflineTime *time.Time     `gorm:"type:datetime;default:NULL" json:"lastOfflineTime"` //最近离线时间
 	IsLogin         int            `gorm:"type:int;default:0" json:"isLogin"`                 //是否登录 0=未登录,1=登录
 	SwitchSn        string         `gorm:"type:varchar(25)" json:"switchSn"`                  //时控开关sn
 	AudioOn         string         `gorm:"type:varchar(10);default:'00:00'" json:"audioOn"`   //声音开时间
@@ -58,23 +58,26 @@ func (s Screens) AddScreens() error {
 
 func (s Screens) UpdateScreens() error {
 	err := global.GVA_DB.Model(&s).
-		Select("screens_name", "screens_code", "sn", "network", "gateway_id", "screens_brand", "screens_model", "ip_address", "install_time", "shunt", "shunt_describe", "resolution_id", "screens_size_id", "switch_sn").
+		Select("screens_name", "screens_code", "sn", "network", "gateway_id", "screens_brand", "screens_model", "ip_address", "install_time", "shunt", "shunt_describe", "resolution_id", "screens_size_id", "switch_sn", "status", "last_online_time", "Last_offline_time").
 		Where("id=?", s.ID).
 		Updates(map[string]interface{}{
-			"screens_name":    s.ScreensName,
-			"screens_code":    s.ScreensCode,
-			"sn":              s.Sn,
-			"network":         s.Network,
-			"gateway_id":      s.GatewayId,
-			"screens_brand":   s.ScreensBrand,
-			"screens_model":   s.ScreensModel,
-			"ip_address":      s.IPAddress,
-			"install_time":    s.InstallTime,
-			"shunt":           s.Shunt,
-			"shunt_describe":  s.ShuntDescribe,
-			"resolution_id":   s.ResolutionId,
-			"screens_size_id": s.ScreensSizeId,
-			"switch_sn":       s.SwitchSn,
+			"screens_name":      s.ScreensName,
+			"screens_code":      s.ScreensCode,
+			"sn":                s.Sn,
+			"network":           s.Network,
+			"gateway_id":        s.GatewayId,
+			"screens_brand":     s.ScreensBrand,
+			"screens_model":     s.ScreensModel,
+			"ip_address":        s.IPAddress,
+			"install_time":      s.InstallTime,
+			"shunt":             s.Shunt,
+			"shunt_describe":    s.ShuntDescribe,
+			"resolution_id":     s.ResolutionId,
+			"screens_size_id":   s.ScreensSizeId,
+			"switch_sn":         s.SwitchSn,
+			"status":            s.Status,
+			"last_online_time":  s.LastOnlineTime,
+			"Last_offline_time": s.LastOfflineTime,
 		}).Error
 	return err
 }
@@ -115,20 +118,20 @@ func QueryScreensToDetail(id int) (screensList []Screens, err error) {
 //	return err
 //}
 
-func UpdateScreensStatusAndOnline(code string, sta int) error {
+func UpdateScreensStatusAndOnline(sn string, sta int) error {
 	var screens Screens
 	return global.GVA_DB.Model(&screens).Select("status", "last_online_time", "is_login").
-		Where("screens_code = ?", code).Updates(map[string]interface{}{
+		Where("sn = ?", sn).Updates(map[string]interface{}{
 		"status":           sta,
 		"last_online_time": time.Now(),
 		"is_login":         999,
 	}).Error
 }
 
-func UpdateScreensStatusAndOffline(code string, sta int) error {
+func UpdateScreensStatusAndOffline(sn string, sta int) error {
 	var screens Screens
 	return global.GVA_DB.Model(&screens).Select("status", "last_offline_time", "is_login").
-		Where("screens_code = ?", code).Updates(map[string]interface{}{
+		Where("sn = ?", sn).Updates(map[string]interface{}{
 		"status":            sta,
 		"last_offline_time": time.Now(),
 		"is_login":          999,
@@ -175,6 +178,6 @@ func (s Screens) QueryOnlineScreens() (screensList []Screens, err error) {
 }
 
 func QueryAllScreens() (screensList []Screens, err error) {
-	err = global.GVA_DB.Model(&Screens{}).Debug().Find(&screensList).Error
+	err = global.GVA_DB.Model(&Screens{}).Find(&screensList).Error
 	return
 }

+ 5 - 0
server/model/devices/dev_screens.go

@@ -27,6 +27,11 @@ type ReqScreens struct {
 	ShuntDescribe string    `json:"shuntDescribe"` //分路描述
 	InstallTime   time.Time `json:"installTime"`   //安装时间
 	SwitchSn      string    `json:"switchSn"`      //时控开关sn
+
+	OldSn           string     `json:"oldSn"`  //老sn 用于删除内存中原有的资源
+	Status          int        `json:"status"` //在线状态 0=离线,1=在线
+	LastOnlineTime  *time.Time `json:"lastOnlineTime"`
+	LastOfflineTime *time.Time `json:"lastOfflineTime"`
 }
 
 type ReqInCode struct {

+ 31 - 2
server/service/devices/dev_screens.go

@@ -69,9 +69,38 @@ func (screensService *ScreensService) AddScreens(screens devices.Screens) error
 	return err
 }
 
-func (screensService *ScreensService) UpdateScreens(screens devices.Screens) error {
+func (screensService *ScreensService) UpdateScreens(screens devices.Screens, oldSn string) error {
+	for s, _ := range tcp.Devices {
+		if s == screens.Sn && oldSn != screens.Sn { //判断修改的新的sn是否已存在,存在这不让修改,
+			return errors.New("设备Sn重复")
+		}
+	}
+
+	//如果改了其它参数,没改sn,则只更新内存中的设备基础信息,且数据库中的原有status、LastOnlineTime、LastOfflineTime不做修改
+	if oldSn == screens.Sn {
+		tcp.Devices[screens.Sn].Info = screens
+		err := screens.UpdateScreens()
+		if err != nil {
+			return errors.New("修改失败")
+		}
+		return nil
+	}
+	//如果改了sn 则要修改内存和数据库中的status、LastOnlineTime、LastOfflineTime信息
+	screens.Status = 0
+	var empty *time.Time
+	screens.LastOnlineTime = empty
+	screens.LastOfflineTime = empty
 	err := screens.UpdateScreens()
-	return err
+	if err != nil {
+		return errors.New("修改失败")
+	}
+	//从内存中删除原有的资源,并添加新的
+	delete(tcp.Devices, oldSn)
+	screens.Status = 0
+	screens.LastOnlineTime = empty
+	screens.LastOfflineTime = empty
+	tcp.Devices[screens.Sn] = &tcp.Device{Info: screens}
+	return nil
 }
 
 /**

+ 11 - 10
server/service/tcp/deviceMgr.go

@@ -33,7 +33,8 @@ func InitDevices() {
 	for _, screen := range devs {
 		if screen.Status != 0 {
 			screen.Status = 0
-			screen.LastOfflineTime = time.Now()
+			now := time.Now()
+			screen.LastOfflineTime = &now
 		}
 		Devices[screen.Sn] = &Device{Info: screen}
 	}
@@ -63,30 +64,29 @@ func (s *Device) Process() {
 		switch data[16:18] {
 		case "61":
 			// fe5c4b89 2a000000 62 00000000 17000000 31 23 32303233(年) 3035(月) 3135(日) 3031(星期) 3038(时) 3334(分) 3135(秒) 23 303630(心跳包时间) 23 ffff
+			//目前登录只做查找设备的操作 (假登录)
 			buffer := protocol.AuthDataPack{}.AuthLogin()
 			// 通过sn 查设备是否存在 不存在return 存在就保存con 和 info
-			screens, err := deviceDao.QueryScreenBySn(data[34:50])
+			_, err := deviceDao.QueryScreenBySn(data[34:50])
 			if errors.Is(err, gorm.ErrRecordNotFound) {
 				logger.Logger.Errorf("Process[case '61'] SN not found \n")
 				break
 			}
-			s.Info = screens
-			Devices[s.Info.Sn] = s
 			s.Conn.Write(buffer.Bytes())
-			logger.Logger.Debugf("设备 [%v] 登录", s.Info.ScreensName)
 		case "91":
 			dev := Devices[data[34:50]]
 			if dev.Info.Status == 0 {
 				state := 1
 				//上线 则修改数据库上线时间
-				err := Dev.UpdateScreensStatusAndOnline(dev.Info.ScreensCode, state)
+				err := Dev.UpdateScreensStatusAndOnline(dev.Info.Sn, state)
 				if err != nil {
 					logger.Logger.Error("Process[case '91'] UpdateScreensStatusAndOnline err", zap.Error(err))
 					continue
 				}
 				dev.Info.Status = 1
-				dev.Info.LastOnlineTime = time.Now()
-				logger.Logger.Debugf("设备 [%v] 上线", dev.Info.ScreensName)
+				now := time.Now()
+				dev.Info.LastOnlineTime = &now
+				logger.Logger.Debugf("设备 [%v] 上线", dev.Info.ScreensName) // 登录
 			}
 			dev.Conn = s.Conn
 			dev.LastTime = time.Now()
@@ -108,13 +108,14 @@ func IsOnline() {
 					//修改数据库和内存
 					//离线
 					state := 0
-					err := Dev.UpdateScreensStatusAndOffline(device.Info.ScreensCode, state)
+					err := Dev.UpdateScreensStatusAndOffline(device.Info.Sn, state)
 					if err != nil {
 						logger.Logger.Error("[Handle] UpdateScreensStatus err", zap.Error(err))
 						continue
 					}
 					device.Info.Status = 0
-					device.Info.LastOfflineTime = time.Now()
+					now := time.Now()
+					device.Info.LastOfflineTime = &now
 					logger.Logger.Debugf("设备 [%v] 离线了...", device.Info.ScreensName)
 				}
 			}

+ 5 - 2
web/src/view/devicesAdmin/screens/screens.vue

@@ -599,6 +599,7 @@ const voiceBroadDialog = ref(false)
 const setBrightDialog = ref(false)
 const onlineSum = ref('0')
 const offlineSum = ref('0')
+const oldSn = ref('')
 
 const rules = ref({
   screensName: [
@@ -700,13 +701,13 @@ const view = (row)=>{
     offlineSum.value = TimeConversion(new Date()-new Date(screensInfo.value.lastOfflineTime))
   }
 
-  if (screensInfo.value.lastOnlineTime === '0001-01-01T00:00:00Z' ){
+  if (screensInfo.value.lastOnlineTime === '0001-01-01T00:00:00Z' || screensInfo.value.lastOnlineTime === null ){
     screensInfo.value.lastOnlineTime = '——'
     onlineSum.value = "无"
   }else {
     screensInfo.value.lastOnlineTime = dayjs(screensInfo.value.lastOnlineTime).format('YYYY-MM-DD HH:mm:ss')
   }
-  if (screensInfo.value.lastOfflineTime === '0001-01-01T00:00:00Z' ){
+  if (screensInfo.value.lastOfflineTime === '0001-01-01T00:00:00Z' || screensInfo.value.lastOfflineTime === null ){
     screensInfo.value.lastOfflineTime = '——'
     offlineSum.value = "无"
   }else {
@@ -765,6 +766,7 @@ const enterAddScreensDialog = async() => {
         }
       }
       if (dialogFlag.value === 'edit') {
+        req.oldSn = oldSn.value
         const res = await setScreensInfo(req)
         if (res.code === 0) {
           ElMessage({ type: 'success', message: '编辑成功' })
@@ -778,6 +780,7 @@ const enterAddScreensDialog = async() => {
 
 const editScreens = (row) => {
   dialogFlag.value = 'edit'
+  oldSn.value = row.sn
   screensInfo.value = JSON.parse(JSON.stringify(row))
   addScreensDialog.value = true
 }