Procházet zdrojové kódy

add:已连接设备列表
fix:
断开设备连接
心电脑电数据处理

zzf před 1 rokem
rodič
revize
ab49135c82

+ 47 - 0
api/gateway/device.go

@@ -2,11 +2,13 @@ package gateway
 
 import (
 	errors "confrontation-training/err"
+	"confrontation-training/global"
 	deviceModel "confrontation-training/models/gateway"
 	"confrontation-training/response"
 	deviceService "confrontation-training/service/device"
 	"fmt"
 	"github.com/gin-gonic/gin"
+	"strings"
 )
 
 type DeviceService struct {
@@ -84,3 +86,48 @@ func (d *DeviceService) DeviceList(c *gin.Context) {
 	deviceInfos, _ := d.FindDeviceByType(c.Param("type"))
 	response.Success(errors.FindSuccess, deviceInfos, c)
 }
+
+// DeviceConnected 连接列表
+// PingExample confrontation-training
+// @Summary 连接列表
+// @Schemes
+// @Description 连接列表
+// @Tags 设备管理
+// @Accept json
+// @Produce json
+// @Success 200 {string} string "ok"
+// @Router /v1/device/connected [get]
+func (d *DeviceService) DeviceConnected(c *gin.Context) {
+
+	url := global.Config.Gateway.BaseUrl + global.Config.Gateway.ConnectedUrl
+	list, err := d.DeviceConnectedList(url)
+	if err != nil {
+		response.Failed("查询失败", c)
+	}
+	response.Success(errors.FindSuccess, list, c)
+	return
+}
+
+// Disconnect
+// PingExample confrontation-training
+// @Summary 断开连接
+// @Schemes
+// @Description 断开连接
+// @Tags 设备管理
+// @Accept json
+// @Produce json
+// @Success 200 {string} string "ok"
+// @Router /v1/device/:mac/disconnect [get]
+func (d *DeviceService) Disconnect(c *gin.Context) {
+	mac := c.Param("mac")
+	disconnectUrl := global.Config.Gateway.BaseUrl + global.Config.Gateway.DisconnectUrl
+	disconnectUrl = strings.Replace(disconnectUrl, "MAC", mac, -1)
+	resp := d.DisconnectDevice(disconnectUrl)
+	if resp.StatusCode != 200 {
+		fmt.Println("断开连接失败")
+		response.Failed("断开连接失败", c)
+	} else {
+		response.Success("断开连接", mac, c)
+	}
+	return
+}

+ 1 - 19
api/gateway/gateway.go

@@ -75,7 +75,7 @@ func ScanDevice(c *gin.Context) {
 	}
 	paramMap["active"] = "1"
 	paramMap["event"] = "1"
-	SseScanDevice(paramMap, param.FilterType, c)
+	SseScanDevice(paramMap, param.FilterType)
 	response.Success("扫描完成", "", c)
 	return
 }
@@ -306,21 +306,3 @@ func StopCollect(c *gin.Context) {
 	response.Success("停止采集", "", c)
 	return
 }
-
-// Disconnect
-// PingExample confrontation-training
-// @Summary 断开连接
-// @Schemes
-// @Description 断开连接
-// @Tags 设备管理
-// @Accept json
-// @Produce json
-// @Success 200 {string} string "ok"
-// @Router /v1/device/:mac/disconnect [get]
-func Disconnect(c *gin.Context) {
-	mac := c.Param("mac")
-	disconnectUrl := global.Config.Gateway.BaseUrl + global.Config.Gateway.DisconnectUrl
-	disconnectUrl = strings.Replace(disconnectUrl, "MAC", mac, -1)
-	response.Success("断开连接", mac, c)
-	return
-}

+ 51 - 34
api/gateway/sse.go

@@ -7,15 +7,15 @@ import (
 	"confrontation-training/models/gateway"
 	"encoding/json"
 	"fmt"
-	"github.com/gin-gonic/gin"
 	"github.com/gorilla/websocket"
 	"github.com/r3labs/sse/v2"
+	"strconv"
 	"strings"
 	"time"
 )
 
 // SseScanDevice 扫描设备
-func SseScanDevice(paramMap map[string]string, filterType string, c *gin.Context) {
+func SseScanDevice(paramMap map[string]string, filterType string) {
 	var scanUrl = global.Config.Gateway.BaseUrl + global.Config.Gateway.ScanUrl
 
 	deviceMap := make(map[string]gateway.DeviceScanned)
@@ -118,42 +118,59 @@ func SseOpenNotify() {
 	client.URL = notifyUrl
 	err = client.SubscribeRaw(func(msg *sse.Event) {
 		bytes := msg.Data
-		s := string(bytes)
+		//s := string(bytes)
 		//fmt.Println("notify receive data :" + s)
-
-		flag := strings.HasPrefix(s, "E840") || strings.HasPrefix(s, "E841") || strings.HasPrefix(s, "E823")
-		//非心电数据
-		if !flag {
-			//websocket 通知数据
-			//msgMap := make(map[string]string)
-			//msgMap[]
-			var receiveData gateway.DeviceDataReceived
-			errJson := json.Unmarshal(msg.Data, &receiveData)
-			if errJson != nil {
-				fmt.Println("receive data parse error:" + errJson.Error())
-				//panic(err)
-				return
-			}
-			messageMap := make(map[string]string)
-			messageMap["msgType"] = constant.MessageTypeData
-			messageMap["content"] = string(msg.Data)
-			messageMap["Sender"] = "server"
-			messageMap["Recipient"] = "client"
-			bytes, err := json.Marshal(messageMap)
-			err = ws.WriteMessage(websocket.TextMessage, bytes)
-			if err != nil {
-				fmt.Println(errors.SendMessageError + err.Error())
-				return
+		//脑电数据
+		var receiveData gateway.DeviceDataReceived
+		errJson := json.Unmarshal(msg.Data, &receiveData)
+		if errJson != nil {
+			fmt.Println("receive data parse error:" + errJson.Error())
+			return
+		}
+		messageMap := make(map[string]string)
+		if strings.Contains(receiveData.Value, "AAAA") {
+			messageMap["msgType"] = constant.MessageTypeEEGData
+			marshal, _ := json.Marshal(receiveData)
+			messageMap["content"] = string(marshal)
+		} else { //心电数据
+			flag := strings.HasPrefix(receiveData.Value, "E840") || strings.HasPrefix(receiveData.Value, "E841") || strings.HasPrefix(receiveData.Value, "E823")
+			if !flag {
+				//var ecgData []int
+				ecgData := [12]int{}
+				fmt.Println("收到的心电数据:" + string(msg.Data))
+				data := []byte(receiveData.Value[4:])
+				fmt.Println(len(data))
+				if len(data) == 36 {
+					for i := 0; i < 36; i += 3 {
+						ecgData[i/3] = int(16<<data[i]&0xFF | 8<<data[i+1]&0xFF | data[i+2]&0xFF)
+					}
+				} else {
+					for i := len(data); i < 36; i++ {
+						data = append(data, data[i])
+					}
+					for i := 0; i < 36; i += 3 {
+						ecgData[i/3] = int(16<<data[i]&0xFF | 8<<data[i+1]&0xFF | data[i+2]&0xFF)
+					}
+				}
+				messageMap["msgType"] = constant.MessageTypeECGData
+				var dataStr []string
+				for _, i := range ecgData {
+					dataStr = append(dataStr, strconv.Itoa(i))
+				}
+				receiveData.Value = strings.Join(dataStr, ",")
+				marshal, _ := json.Marshal(receiveData)
+				messageMap["content"] = string(marshal)
 			}
-			//心电数据
-		} else {
-			if len(bytes) == 18 {
+		}
 
-			}
+		messageMap["Sender"] = "server"
+		messageMap["Recipient"] = "client"
+		bytes, err := json.Marshal(messageMap)
+		err = ws.WriteMessage(websocket.TextMessage, bytes)
+		if err != nil {
+			fmt.Println(errors.SendMessageError + err.Error())
+			return
 		}
-		//time.Sleep(100)
-		//time.Sleep(100 * time.Millisecond)
-		//time.Sleep(10 * time.Millisecond)
 	})
 	if err != nil {
 		return

+ 1 - 0
config/application.yaml

@@ -31,6 +31,7 @@ gateway:
   openChannel: /gatt/nodes/MAC/handle/36/value/0100
   disconnectUrl: /gap/nodes/MAC/connection
   scanSecond: 20000 #蓝牙数据推送时间间隔
+  connectedList: /gap/nodes?connection_state=connected
 #日志系统
 log2file:
   filePath: ./logs/

+ 3 - 2
config/config.go

@@ -1,7 +1,7 @@
 package config
 
 type Gateway struct {
-	BaseUrl         string `mpstructure:"baseUrl"`
+	BaseUrl         string `mapstructure:"baseUrl"`
 	ScanUrl         string `mapstructure:"scanUrl"`
 	ScanSecond      int64  `mapstructure:"scanSecond"`
 	ConnUrl         string `mapstructure:"connUrl"`
@@ -10,6 +10,7 @@ type Gateway struct {
 	StartCollectUrl string `mapstructure:"startCollectUrl"`
 	OpenChannel     string `mapstructure:"openChannel"`
 	DisconnectUrl   string `mapstructure:"disconnectUrl"`
+	ConnectedUrl    string `mapstructure:"connectedList"`
 }
 
 type Param struct {
@@ -44,7 +45,7 @@ type Jwt struct {
 
 // Upload 文件上传相关路径配置
 type Upload struct {
-	SavePath  string `mapstructer:"savePath"`
+	SavePath  string `mapstructure:"savePath"`
 	AccessUrl string `mapstructure:"accessUrl"`
 }
 

+ 2 - 1
constant/constant.go

@@ -22,7 +22,8 @@ const (
 
 	// MessageTypeDeviceScanned websocket 消息类型 扫描到设备
 	MessageTypeDeviceScanned = "device"
-	MessageTypeData          = "data"
+	MessageTypeEEGData       = "eegData"
+	MessageTypeECGData       = "ecgData"
 	// DefaultKey 3des
 	DefaultKey = "240262447423713749922240"
 	DefaultIv  = "12345678"

+ 23 - 0
docs/docs.go

@@ -274,6 +274,29 @@ const docTemplate = `{
                 }
             }
         },
+        "/v1/device/connected": {
+            "get": {
+                "description": "连接列表",
+                "consumes": [
+                    "application/json"
+                ],
+                "produces": [
+                    "application/json"
+                ],
+                "tags": [
+                    "设备管理"
+                ],
+                "summary": "连接列表",
+                "responses": {
+                    "200": {
+                        "description": "ok",
+                        "schema": {
+                            "type": "string"
+                        }
+                    }
+                }
+            }
+        },
         "/v1/device/connection": {
             "post": {
                 "description": "连接设备",

+ 23 - 0
docs/swagger.json

@@ -265,6 +265,29 @@
                 }
             }
         },
+        "/v1/device/connected": {
+            "get": {
+                "description": "连接列表",
+                "consumes": [
+                    "application/json"
+                ],
+                "produces": [
+                    "application/json"
+                ],
+                "tags": [
+                    "设备管理"
+                ],
+                "summary": "连接列表",
+                "responses": {
+                    "200": {
+                        "description": "ok",
+                        "schema": {
+                            "type": "string"
+                        }
+                    }
+                }
+            }
+        },
         "/v1/device/connection": {
             "post": {
                 "description": "连接设备",

+ 15 - 0
docs/swagger.yaml

@@ -171,6 +171,21 @@ paths:
       summary: 新增设备
       tags:
       - 设备管理
+  /v1/device/connected:
+    get:
+      consumes:
+      - application/json
+      description: 连接列表
+      produces:
+      - application/json
+      responses:
+        "200":
+          description: ok
+          schema:
+            type: string
+      summary: 连接列表
+      tags:
+      - 设备管理
   /v1/device/connection:
     post:
       consumes:

+ 1 - 0
global/global.go

@@ -11,4 +11,5 @@ var (
 	Db              *gorm.DB
 	SseClientDevice *sse.Client
 	SseClientData   *sse.Client
+	//EcgDataMap      map[string][]byte
 )

+ 21 - 6
http/http.go

@@ -21,12 +21,12 @@ func GetReq(url string) *http.Response {
 	if err != nil {
 		panic(err)
 	}
-	defer func(Body io.ReadCloser) {
-		err := Body.Close()
-		if err != nil {
-			fmt.Print("Body close err" + err.Error())
-		}
-	}(resp.Body)
+	//defer func(Body io.ReadCloser) {
+	//	err := Body.Close()
+	//	if err != nil {
+	//		fmt.Print("Body close err" + err.Error())
+	//	}
+	//}(resp.Body)
 	return resp
 
 }
@@ -102,3 +102,18 @@ func (jp *JsonPost) postReqJson2() {
 	fmt.Println(*str)
 
 }
+
+// DeleteReq 发送delete请求
+func DeleteReq(url string) *http.Response {
+	client := &http.Client{}
+
+	req, err := http.NewRequest("DELETE", url, nil)
+	if err != nil {
+		panic(err)
+	}
+	resp, err := client.Do(req)
+	if err != nil {
+		panic(err)
+	}
+	return resp
+}

+ 3 - 1
initialize/router.go

@@ -60,14 +60,16 @@ func Router() {
 	device.GET("/open/notify/", gateway.OpenNotify)
 	device.GET("/:mac/stop/trans/", gateway.StopTrans)
 	device.GET("/:mac/stop/collect/", gateway.StopCollect)
-	device.GET("/:mac/disconnect/", gateway.Disconnect)
+	device.GET("/:mac/disconnect", gateway.GetDeviceService().Disconnect)
 	device.POST("/add/", gateway.GetDeviceService().DeviceAdd)
 	device.DELETE("/:mac/remove/", gateway.GetDeviceService().DeviceRemove)
 	device.GET("/list/:type", gateway.GetDeviceService().DeviceList)
+	device.GET("connected", gateway.GetDeviceService().DeviceConnected)
 	chats := v1.Group("/chat")
 	chats.GET("/get/chat/", chat.GetQuestionService().GetQuestion)
 	chats.POST("/create/chat/", chat.GetQuestionService().CreateQuestion)
 	chats.GET("/get/answer/", chat.GetAnswerService().GetAnswer)
+
 	//
 	//record := v1.Group("/record")
 	//record.POST("/create", api.GetRecord().SaveRecord)

+ 27 - 0
service/device/device.go

@@ -1,9 +1,15 @@
 package device
 
 import (
+	errors "confrontation-training/err"
 	"confrontation-training/global"
+	"confrontation-training/http"
 	deviceModel "confrontation-training/models/gateway"
+	"encoding/json"
+	"fmt"
 	"gorm.io/gorm"
+	"io/ioutil"
+	netHttp "net/http"
 )
 
 type DeviceService struct {
@@ -34,3 +40,24 @@ func (d *DeviceService) RemoveDevice(mac string) int64 {
 	}
 	return count
 }
+
+func (d *DeviceService) DeviceConnectedList(url string) (map[string]interface{}, error) {
+	httpResponse := http.GetReq(url)
+	var result map[string]interface{}
+	if httpResponse.StatusCode != 200 {
+		fmt.Printf("%s:%s", errors.StartTransFailed, httpResponse.Body)
+		return result, nil
+	} else {
+		body, err := ioutil.ReadAll(httpResponse.Body)
+		if err == nil {
+			err = json.Unmarshal(body, &result)
+			return result, err
+		}
+		return result, err
+	}
+
+}
+
+func (d *DeviceService) DisconnectDevice(url string) *netHttp.Response {
+	return http.DeleteReq(url)
+}