Quellcode durchsuchen

add:新网关,双人对抗

zzf vor 10 Monaten
Ursprung
Commit
439d02239c
9 geänderte Dateien mit 76 neuen und 43 gelöschten Zeilen
  1. 16 10
      api/gateway/device.go
  2. 5 4
      api/gateway/gateway.go
  3. 2 0
      docs/docs.go
  4. 10 9
      global/global.go
  5. 1 0
      go.mod
  6. 7 8
      initialize/emq.go
  7. 33 11
      initialize/findGateway.go
  8. 1 1
      initialize/run.go
  9. 1 0
      models/gateway/device.go

+ 16 - 10
api/gateway/device.go

@@ -4,6 +4,7 @@ import (
 	errors "confrontation-training/err"
 	"confrontation-training/global"
 	deviceModel "confrontation-training/models/gateway"
+	gatewaym "confrontation-training/models/gateway"
 	"confrontation-training/response"
 	deviceService "confrontation-training/service/device"
 	"fmt"
@@ -45,16 +46,14 @@ func (d *DeviceService) DeviceAdd(c *gin.Context) {
 		return
 	}
 	if result := d.CreateDevice(param); result.Error == nil {
-		deviceInfo := deviceModel.DeviceInfo{
-			Type: param.Type,
-			Mac:  param.Mac,
-		}
-		if param.Type == "0" {
-			deviceInfo.Name = "MIND" + strings.ReplaceAll(param.Mac[len(param.Mac)-5:], ":", "")
-		} else {
-			deviceInfo.Name = "BW-ECG-01"
+		service := GetDeviceService()
+		d, i := service.FindDeviceByType("")
+		global.DeviceMap = make(map[string]gatewaym.DeviceInfo)
+		if i > 0 {
+			for j := 0; j < len(d); j++ {
+				global.DeviceMap[d[j].Mac] = d[j]
+			}
 		}
-		global.DeviceMap[param.Mac] = deviceInfo
 		response.Success(errors.DeviceAddSuccess, result.RowsAffected, c)
 		return
 	} else {
@@ -81,7 +80,14 @@ func (d *DeviceService) DeviceRemove(c *gin.Context) {
 	} else {
 		response.Success(errors.DeviceRemoveSuccess, count, c)
 	}
-	delete(global.DeviceMap, mac)
+	service := GetDeviceService()
+	device, i := service.FindDeviceByType("")
+	global.DeviceMap = make(map[string]gatewaym.DeviceInfo)
+	if i > 0 {
+		for j := 0; j < len(device); j++ {
+			global.DeviceMap[device[j].Mac] = device[j]
+		}
+	}
 	return
 }
 

+ 5 - 4
api/gateway/gateway.go

@@ -490,6 +490,7 @@ func ConnectList(c *gin.Context) {
 		ConnectedListEmq(global.EmqClient, topic, strconv.Itoa(i))
 		time.Sleep(time.Millisecond * 500)
 	}
+
 	response.Success("查询连接列表完成", "", c)
 	return
 }
@@ -572,13 +573,13 @@ func WriteDataEmq(c *gin.Context) {
 	global.Log4J.Info(startCollectCmd)
 	//发送指令
 	//绑定用户
-	WNP(global.EmqClient, topic, param.Mac, "FFF1", bindUserCmd)
+	WNP(global.EmqClient, topic, strings.ReplaceAll(param.Mac, ":", ""), "FFF1", bindUserCmd)
 	//授时
-	WNP(global.EmqClient, topic, param.Mac, "FFF1", setTimeCmd)
+	WNP(global.EmqClient, topic, strings.ReplaceAll(param.Mac, ":", ""), "FFF1", setTimeCmd)
 	//开始收集
-	WNP(global.EmqClient, topic, param.Mac, "FFF1", startCollectCmd)
+	WNP(global.EmqClient, topic, strings.ReplaceAll(param.Mac, ":", ""), "FFF1", startCollectCmd)
 	//开始传输指令
-	WNP(global.EmqClient, topic, param.Mac, "FFF1", constant.StartTransCmd)
+	WNP(global.EmqClient, topic, strings.ReplaceAll(param.Mac, ":", ""), "FFF1", constant.StartTransCmd)
 	response.Success(errors.WriteDataSuccess, nil, c)
 	return
 }

+ 2 - 0
docs/docs.go

@@ -879,6 +879,8 @@ var SwaggerInfo = &swag.Spec{
 	Description:      "对抗训练",
 	InfoInstanceName: "swagger",
 	SwaggerTemplate:  docTemplate,
+	LeftDelim:        "{{",
+	RightDelim:       "}}",
 }
 
 func init() {

+ 10 - 9
global/global.go

@@ -10,13 +10,14 @@ import (
 )
 
 var (
-	Config          config.Config
-	Db              *gorm.DB
-	SseClientDevice *sse.Client
-	SseClientData   *sse.Client
-	DeviceMap       map[string]gateway.DeviceInfo
-	EmqClient       mqtt.Client
-	EmqConfig       config.EmqConfig
-	Log4J           log4go.Logger
-	GatewayList     map[string]gateway.GatewayInfo
+	Config             config.Config
+	Db                 *gorm.DB
+	SseClientDevice    *sse.Client
+	SseClientData      *sse.Client
+	DeviceMap          map[string]gateway.DeviceInfo
+	EmqClient          mqtt.Client
+	EmqConfig          config.EmqConfig
+	Log4J              log4go.Logger
+	GatewayList        map[string]gateway.GatewayInfo
+	ConnectedDeviceMap map[string]gateway.ConnectedDevice
 )

+ 1 - 0
go.mod

@@ -13,6 +13,7 @@ require (
 	github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible
 	github.com/r3labs/sse/v2 v2.10.0
 	github.com/rifflock/lfshook v0.0.0-20180920164130-b9218ef580f5
+	github.com/robfig/cron v1.2.0
 	github.com/rosshemsley/kalman v0.0.0-20190615074247-f4b900823fd1
 	github.com/sirupsen/logrus v1.9.3
 	github.com/spf13/viper v1.16.0

+ 7 - 8
initialize/emq.go

@@ -193,8 +193,6 @@ func SubScribe(client mqtt.Client) {
 						payload.M = realMac
 						marshal, _ := json.Marshal(payload)
 						content = string(marshal)
-
-						//连接成功或连接失败,发送已连接设备列表
 					}
 					for i := 0; i < 6; i++ {
 						topic := "/" + global.Config.EmqConfig.GatewayMac + constant.TopicConnectSub
@@ -203,15 +201,15 @@ func SubScribe(client mqtt.Client) {
 				case constant.PayloadDisConnect:
 					messageMap["msgType"] = constant.MessageTypeDisConnect
 					//content = "断开设备连接"
-					if payload.State == "SUCCESS" && payload.ReasonCode == "62" {
-						messageMap["msgType"] = constant.MessageTypeConnect
-					}
 					realMac := transMac(payload.M)
 					deviceInfo := global.DeviceMap[realMac]
 					payload.T = deviceInfo.Type
 					payload.M = realMac
 					marshal, _ := json.Marshal(payload)
 					content = string(marshal)
+					if payload.State == "SUCCESS" && payload.ReasonCode == "62" {
+						messageMap["msgType"] = constant.MessageTypeConnect
+					}
 					//断开连接成功或连接失败,发送已连接设备列表
 					for i := 0; i < 6; i++ {
 						topic := "/" + global.Config.EmqConfig.GatewayMac + constant.TopicConnectSub
@@ -264,6 +262,7 @@ func SubScribe(client mqtt.Client) {
 					var receiveData gateway.DeviceDataReceived
 					receiveData.Mac = realMac
 					receiveData.Value = payload.D
+
 					if deviceInfo.Type == "0" { //脑电
 						messageMap["msgType"] = constant.MessageTypeEEGData
 						marshal, _ := json.Marshal(receiveData)
@@ -318,10 +317,10 @@ func SubScribe(client mqtt.Client) {
 					return
 				}
 				if sendFlag && content != "成功" && content != "失败" {
-					if messageMap["msgType"] == constant.MessageTypeECGData {
+					if messageMap["msgType"] == constant.MessageTypeConnectList {
 
-						fmt.Printf("发送心电数据===" + common.NowTime("2006-01-02 15:04:05") + "=====" + string(bytes))
-						_ = global.Log4J.Info("发送心电数据===" + common.NowTime("2006-01-02 15:04:05") + "=====" + string(bytes))
+						fmt.Printf("已连接列表===" + common.NowTime("2006-01-02 15:04:05") + "=====" + string(bytes))
+						_ = global.Log4J.Info("已连接列表===" + common.NowTime("2006-01-02 15:04:05") + "=====" + string(bytes))
 					}
 					for k := range messageMap {
 						delete(messageMap, k)

+ 33 - 11
initialize/findGateway.go

@@ -3,7 +3,9 @@ package initialize
 import (
 	"confrontation-training/global"
 	"confrontation-training/models/gateway"
+	"github.com/robfig/cron"
 	"strings"
+	"time"
 	"tinygo.org/x/bluetooth"
 )
 
@@ -15,20 +17,40 @@ func FindGateway() {
 	global.GatewayList = make(map[string]gateway.GatewayInfo)
 	// Start scanning.
 	println("scanning...")
-	err := adapter.Scan(func(adapter *bluetooth.Adapter, device bluetooth.ScanResult) {
+	global.Log4J.Info("开启网关扫描---")
+	cron := cron.New()
+	isScanning := false
+	cron.AddFunc("0 */1 * * * *", func() {
+		if !isScanning {
+			isScanning = true
+			err := adapter.Scan(func(adapter *bluetooth.Adapter, device bluetooth.ScanResult) {
 
-		println("found device:", device.Address.String(), device.RSSI, device.LocalName())
-		mac := strings.ReplaceAll(device.Address.String(), ":", "")
-		name := device.LocalName()
-		if strings.HasSuffix(name, mac) {
-			global.Log4J.Info("发现可能是网关的设备:mac="+mac, "	name="+name)
-			var gatewayInfo gateway.GatewayInfo
-			gatewayInfo.Mac = mac
-			gatewayInfo.Name = name
-			global.GatewayList[mac] = gatewayInfo
+				println("found device:", device.Address.String(), device.RSSI, device.LocalName())
+				mac := strings.ReplaceAll(device.Address.String(), ":", "")
+				name := device.LocalName()
+				if strings.HasSuffix(name, mac) {
+					global.Log4J.Info("发现可能是网关的设备:mac="+mac, "	name="+name)
+					var gatewayInfo gateway.GatewayInfo
+					gatewayInfo.Mac = mac
+					gatewayInfo.Name = name
+					global.GatewayList[mac] = gatewayInfo
+				}
+				time.Sleep(time.Millisecond * 100)
+			})
+			must("start scan", err)
+		} else {
+			isScanning = false
+			adapter.StopScan()
 		}
+		global.Log4J.Info("关闭网关扫描---")
+		adapter.StopScan()
+		time.Sleep(time.Millisecond * 10000)
+		global.Log4J.Info("开启网关扫描---")
+
 	})
-	must("start scan", err)
+	cron.Start()
+	select {}
+
 }
 func must(action string, err error) {
 	if err != nil {

+ 1 - 1
initialize/run.go

@@ -9,6 +9,6 @@ func Run() {
 	//go StartDataSSeClient()
 	//go StartScanSseClient()
 	go CreateEmqClient()
-	go FindGateway()
+	//go FindGateway()
 	Router()
 }

+ 1 - 0
models/gateway/device.go

@@ -61,6 +61,7 @@ type ConnectedDevice struct {
 	MAC        string
 	Name       string
 	DeviceType string
+	State      string
 }
 
 type ConnectDevice struct {