Bläddra i källkod

fix:日志文件权限问题解决

zzf 1 år sedan
förälder
incheckning
44d1672811
9 ändrade filer med 138 tillägg och 14 borttagningar
  1. 2 2
      api/gateway/gateway.go
  2. 124 2
      api/gateway/sse.go
  3. 1 1
      config/application.yaml
  4. 1 1
      docs/docs.go
  5. 1 1
      docs/swagger.json
  6. 1 1
      docs/swagger.yaml
  7. 1 1
      go.mod
  8. 5 3
      initialize/router.go
  9. 2 2
      service/device/device.go

+ 2 - 2
api/gateway/gateway.go

@@ -27,7 +27,7 @@ import (
 // @Accept json
 // @Produce json
 // @Success 200 {string} string "ok"
-// @Router /v1/device/scan [get]
+// @Router /v1/device/scan [post]
 func ScanDevice(c *gin.Context) {
 	var param gateway.DeviceScanParam
 	err := c.ShouldBindJSON(&param)
@@ -75,7 +75,7 @@ func ScanDevice(c *gin.Context) {
 	}
 	paramMap["active"] = "1"
 	paramMap["event"] = "1"
-	SseScanDevice(paramMap, param.FilterType)
+	SseScanDevice(paramMap, param.FilterType, c.Request)
 	//http.GetReq(global.Config.Gateway.BaseUrl + global.Config.Gateway.OpenNotify)
 	response.Success("扫描完成", "", c)
 	return

+ 124 - 2
api/gateway/sse.go

@@ -5,16 +5,19 @@ import (
 	errors "confrontation-training/err"
 	"confrontation-training/global"
 	"confrontation-training/models/gateway"
+	"confrontation-training/response"
 	"encoding/json"
 	"fmt"
+	"github.com/gin-gonic/gin"
 	"github.com/gorilla/websocket"
 	"github.com/r3labs/sse/v2"
+	"net/http"
 	"strings"
 	"time"
 )
 
 // SseScanDevice 扫描设备
-func SseScanDevice(paramMap map[string]string, filterType string) {
+func SseScanDevice(paramMap map[string]string, filterType string, r *http.Request) {
 	var scanUrl = global.Config.Gateway.BaseUrl + global.Config.Gateway.ScanUrl
 
 	deviceMap := make(map[string]gateway.DeviceScanned)
@@ -59,12 +62,15 @@ func SseScanDevice(paramMap map[string]string, filterType string) {
 			fmt.Println(err.Error())
 			return
 		}
+		<-r.Context().Done()
+		return
 	}()
 	ticket := time.NewTicker(time.Duration(global.Config.Gateway.ScanSecond) * time.Millisecond)
 	for range ticket.C {
 		fmt.Println("当前时间:" + time.Now().Format("2006-01-02 15:04:05"))
+		ws, _, err := websocket.DefaultDialer.Dial(global.Config.Websocket.WSUrl, nil)
 		if len(deviceMap) > 0 {
-			ws, _, err := websocket.DefaultDialer.Dial(global.Config.Websocket.WSUrl, nil)
+
 			if err != nil {
 				fmt.Println("Websocket client init error" + err.Error())
 				return
@@ -87,8 +93,124 @@ func SseScanDevice(paramMap map[string]string, filterType string) {
 				fmt.Println("消息发送异常:" + err.Error())
 				return
 			}
+		} else {
+			err := ws.WriteMessage(websocket.TextMessage, []byte("{}"))
+			if err != nil {
+				fmt.Println("消息发送异常:" + err.Error())
+				return
+			}
+		}
+		client = nil
+		ws = nil
+	}
+}
+
+func SseScanDevice2(c *gin.Context) {
+	var scanUrl = global.Config.Gateway.BaseUrl + global.Config.Gateway.ScanUrl
+	var param gateway.DeviceScanParam
+	err := c.ShouldBindJSON(&param)
+	if err != nil {
+		fmt.Printf("参数格式化异常:%s", err.Error())
+		response.Failed(errors.ParamInvalid, c)
+		return
+	}
+	paramMap := make(map[string]string)
+	if param.Chip != "" {
+		paramMap["chip"] = param.Chip
+	}
+	if param.FilterName != "" {
+		//查询设备mac过滤信息
+		filterMac := ""
+		deviceInfos, count := GetDeviceService().DeviceService.FindDeviceByType(param.FilterName)
+		if count > 0 {
+			for i := range deviceInfos {
+				filterMac += deviceInfos[i].Mac + ","
+			}
+		}
+		if len(filterMac) > 0 {
+			if strings.HasSuffix(filterMac, ",") {
+				filterMac = filterMac[0 : len(filterMac)-1]
+			}
+			paramMap["filter_mac"] = filterMac
+		}
+
+		if param.FilterName == "0" {
+			paramMap["filter_name"] = constant.FilterNameEEG
+		} else if param.FilterName == "1" {
+			paramMap["filter_name"] = constant.FilterNameECG
+		} else {
+			response.Failed(errors.ParamInvalid+":过滤类型-"+param.FilterName+"无效", c)
+			return
+		}
+	} else {
+		paramMap["filter_name"] = constant.FilterNameALL
+	}
+	if param.FilterRssi != "" {
+		paramMap["filter_rssi"] = param.FilterRssi
+	}
+	if param.FilterMac != "" {
+		paramMap["filter_mac"] = param.FilterMac
+	}
+	paramMap["active"] = "1"
+	paramMap["event"] = "1"
+	deviceMap := make(map[string]gateway.DeviceScanned)
+	if len(paramMap) > 0 {
+		for key, value := range paramMap {
+			scanUrl += "&" + key + "=" + value
 		}
 	}
+	//events := make(chan *sse.Event)
+	client := sse.NewClient(scanUrl)
+	fmt.Println("开始SSE")
+	flusher := c.Writer.(http.Flusher)
+	err = client.SubscribeRaw(func(msg *sse.Event) {
+		//fmt.Println(string(msg.Data))
+		var data gateway.DeviceScannedFromGateway
+		err := json.Unmarshal(msg.Data, &data)
+		if err != nil {
+			fmt.Printf("SSE数据转换异常:%s", err.Error())
+			return
+		}
+		deviceScanned := gateway.DeviceScanned{}
+		deviceScanned.MAC = data.Bdaddrs[0].Bdaddr
+		//if param.FilterType == "1" {
+		//	deviceService := GetDeviceService()
+		//	_, i := deviceService.FindDeviceByMac(deviceScanned.MAC)
+		//	if i > 0 {
+		//		deviceScanned.Name = data.Name
+		//		deviceScanned.Rssi = data.Rssi
+		//		deviceScanned.BdadrType = data.Bdaddrs[0].BdaddrType
+		//		deviceScanned.Chip = data.ChipId
+		//		deviceMap[deviceScanned.MAC] = deviceScanned
+		//		fmt.Println(deviceScanned)
+		//	}
+		//}
+		deviceScanned.Name = data.Name
+		deviceScanned.Rssi = data.Rssi
+		deviceScanned.BdadrType = data.Bdaddrs[0].BdaddrType
+		deviceScanned.Chip = data.ChipId
+		deviceMap[deviceScanned.MAC] = deviceScanned
+		fmt.Println(deviceScanned)
+		if len(deviceMap) > 0 {
+			marshal, _ := json.Marshal(deviceMap)
+			c.Writer.Write(marshal)
+			//fmt.Fprintf(c.Writer, string(marshal))
+			flusher.Flush()
+		}
+
+		go func() {
+			<-c.Request.Context().Done()
+			client = nil
+			return
+
+		}()
+	})
+	if err != nil {
+		fmt.Println(err.Error())
+		return
+	}
+	return
+
 }
 
 // SseOpenNotify 开启通知

+ 1 - 1
config/application.yaml

@@ -30,7 +30,7 @@ gateway:
   writeDataUrl: /gatt/nodes/MAC/handle/32/value/DATA
   openChannel: /gatt/nodes/MAC/handle/36/value/0100
   disconnectUrl: /gap/nodes/MAC/connection
-  scanSecond: 1000 #蓝牙数据推送时间间隔
+  scanSecond: 20000 #蓝牙数据推送时间间隔
 #日志系统
 log2file:
   filePath: ./logs/

+ 1 - 1
docs/docs.go

@@ -355,7 +355,7 @@ const docTemplate = `{
             }
         },
         "/v1/device/scan": {
-            "get": {
+            "post": {
                 "description": "扫描设备",
                 "consumes": [
                     "application/json"

+ 1 - 1
docs/swagger.json

@@ -346,7 +346,7 @@
             }
         },
         "/v1/device/scan": {
-            "get": {
+            "post": {
                 "description": "扫描设备",
                 "consumes": [
                     "application/json"

+ 1 - 1
docs/swagger.yaml

@@ -224,7 +224,7 @@ paths:
       tags:
       - 设备管理
   /v1/device/scan:
-    get:
+    post:
       consumes:
       - application/json
       description: 扫描设备

+ 1 - 1
go.mod

@@ -3,6 +3,7 @@ module confrontation-training
 go 1.18
 
 require (
+	github.com/forgoer/openssl v1.6.0
 	github.com/gin-gonic/gin v1.9.1
 	github.com/golang-jwt/jwt v3.2.2+incompatible
 	github.com/google/uuid v1.1.2
@@ -24,7 +25,6 @@ require (
 	github.com/bytedance/sonic v1.10.0 // indirect
 	github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect
 	github.com/chenzhuoyu/iasm v0.9.0 // indirect
-	github.com/forgoer/openssl v1.6.0 // indirect
 	github.com/fsnotify/fsnotify v1.6.0 // indirect
 	github.com/gabriel-vasile/mimetype v1.4.2 // indirect
 	github.com/gin-contrib/sse v0.1.0 // indirect

+ 5 - 3
initialize/router.go

@@ -25,7 +25,8 @@ func Router() {
 		fmt.Printf("初始化表格异常:%s", initTableErr.Error())
 		return
 	}
-	gin.SetMode(gin.ReleaseMode)
+	//gin.SetMode(gin.ReleaseMode)
+	gin.SetMode(gin.DebugMode)
 	engine := gin.Default()
 	//解决跨域
 	engine.Use(middleware.Cors())
@@ -52,8 +53,9 @@ func Router() {
 	user.POST("/reset", gateway.GetUser().ResetPassword)
 	user.GET("/find", gateway.GetUser().UserList)
 	user.POST("/change/password", gateway.GetUser().ModePass)
-	device := v1.Group("/device/")
-	device.GET("/scan", gateway.ScanDevice)
+	device := v1.Group("/device")
+	device.POST("/scan", gateway.ScanDevice)
+	device.POST("/scan2", gateway.SseScanDevice2)
 	device.GET("/connection", gateway.ConnectDevice)
 	device.POST("/write/data/", gateway.WriteData)
 	device.GET("/open/notify/", gateway.OpenNotify)

+ 2 - 2
service/device/device.go

@@ -28,9 +28,9 @@ func (d *DeviceService) CreateDevice(param deviceModel.DeviceAddParam) *gorm.DB
 }
 
 func (d *DeviceService) RemoveDevice(mac string) int64 {
-	_, count := d.FindDeviceByMac(mac)
+	deviceInfo, count := d.FindDeviceByMac(mac)
 	if count > 0 {
-		count = global.Db.Delete(" mac = ?", mac).RowsAffected
+		count = global.Db.Delete(&deviceModel.DeviceInfo{}, deviceInfo.ID).RowsAffected
 	}
 	return count
 }