Browse Source

add:新网关,双人对抗

zzf 11 months ago
parent
commit
4f8da186d1

+ 7 - 0
.idea/dataSources.xml

@@ -8,5 +8,12 @@
       <jdbc-url>jdbc:sqlite:$PROJECT_DIR$/db/confrontation-training.db</jdbc-url>
       <working-dir>$ProjectFileDir$</working-dir>
     </data-source>
+    <data-source source="LOCAL" name="confrontation-training.db [2]" uuid="9f38f1c5-77b0-47d9-b55f-464646182511">
+      <driver-ref>sqlite.xerial</driver-ref>
+      <synchronize>true</synchronize>
+      <jdbc-driver>org.sqlite.JDBC</jdbc-driver>
+      <jdbc-url>jdbc:sqlite:C:/Program Files/gy/resources/exe/ct1/db/confrontation-training.db</jdbc-url>
+      <working-dir>$ProjectFileDir$</working-dir>
+    </data-source>
   </component>
 </project>

+ 4 - 2
api/chat/answer.go

@@ -2,11 +2,12 @@ package chat
 
 import (
 	errors "confrontation-training/err"
+	"confrontation-training/global"
 	"confrontation-training/models/chat"
 	"confrontation-training/response"
 	serviceChat "confrontation-training/service/chat"
-	"fmt"
 	"github.com/gin-gonic/gin"
+	log "github.com/sirupsen/logrus"
 )
 
 type AnswerService struct {
@@ -61,7 +62,8 @@ func (a *AnswerService) GetAnswer(c *gin.Context) {
 	err := c.ShouldBind(&id)
 	questions, count := a.FindAnswerByQuestionId(id)
 	if err != nil {
-		fmt.Println("查询答案信息出错:" + err.Error())
+		log.Infoln("查询答案信息出错:" + err.Error())
+		global.Log4J.Info("查询答案信息出错:" + err.Error())
 		panic(err)
 	}
 	if count <= 0 {

+ 3 - 0
api/chat/question.go

@@ -7,6 +7,7 @@ import (
 	serviceChat "confrontation-training/service/chat"
 	"fmt"
 	"github.com/gin-gonic/gin"
+	log "github.com/sirupsen/logrus"
 )
 
 type QuestionService struct {
@@ -31,6 +32,7 @@ func GetQuestionService() *QuestionService {
 func (q *QuestionService) GetQuestion(c *gin.Context) {
 	var id uint8
 	if err := c.ShouldBind(&id); err != nil {
+		log.Infof("参数绑定异常:%s", err.Error())
 		fmt.Printf("参数绑定异常:%s", err.Error())
 		response.Failed(errors.ParamInvalid, c)
 		return
@@ -61,6 +63,7 @@ func (q *QuestionService) GetQuestion(c *gin.Context) {
 func (q *QuestionService) CreateQuestion(c *gin.Context) {
 	var param modelsChat.CreateQuestion
 	if err := c.ShouldBindJSON(&param); err != nil {
+		log.Infof("参数绑定异常:%s", err.Error())
 		fmt.Printf("参数绑定异常:%s", err.Error())
 		response.Failed(errors.ParamInvalid, c)
 		return

+ 3 - 0
api/gateway/device.go

@@ -36,6 +36,7 @@ func (d *DeviceService) DeviceAdd(c *gin.Context) {
 	err := c.ShouldBindJSON(&param)
 	if err != nil {
 		fmt.Printf("参数格式化异常:%s", err.Error())
+		global.Log4J.Info("参数格式化异常:" + err.Error())
 		response.Failed(errors.ParamInvalid, c)
 		return
 	}
@@ -116,6 +117,7 @@ func (d *DeviceService) DeviceConnected(c *gin.Context) {
 	listResult, err := d.DeviceConnectedList(url)
 	if err != nil {
 		response.Failed("查询失败", c)
+		return
 	}
 	a := make(map[string]interface{})
 	a = listResult
@@ -170,6 +172,7 @@ func (d *DeviceService) Disconnect(c *gin.Context) {
 	resp := d.DisconnectDevice(disconnectUrl)
 	if resp.StatusCode != 200 {
 		fmt.Println("断开连接失败")
+		global.Log4J.Info("断开连接失败")
 		response.Failed("断开连接失败", c)
 	} else {
 		response.Success("断开连接", mac, c)

+ 71 - 8
api/gateway/gateway.go

@@ -13,7 +13,9 @@ import (
 	"encoding/json"
 	"fmt"
 	"github.com/gin-gonic/gin"
+	log "github.com/sirupsen/logrus"
 	"io/ioutil"
+	"strconv"
 	"strings"
 	"time"
 )
@@ -34,6 +36,7 @@ func ScanDevice(c *gin.Context) {
 	err := c.ShouldBindJSON(&param)
 	if err != nil {
 		fmt.Printf("参数格式化异常:%s", err.Error())
+		global.Log4J.Info("参数格式化异常:", err.Error())
 		response.Failed(errors.ParamInvalid, c)
 		return
 	}
@@ -98,12 +101,14 @@ func ConnectDevice(c *gin.Context) {
 	err := c.ShouldBindJSON(&param)
 	if err != nil {
 		fmt.Printf("参数格式化异常:%s", err.Error())
+		log.Infof("参数格式化异常:%s", err.Error())
 		response.Failed(errors.ParamInvalid, c)
 		return
 	}
 	jsonParam, err := json.Marshal(param)
 	if err != nil {
 		fmt.Printf("参数转换异常:%s", err.Error())
+		log.Infof("参数转换异常:%s", err.Error())
 		response.Failed("参数转换异常:%s"+err.Error(), c)
 		return
 	}
@@ -127,6 +132,7 @@ func ConnectDevice(c *gin.Context) {
 		httpResponse = http.GetReq(openChannelUrl)
 		if httpResponse.StatusCode != 200 {
 			fmt.Printf("%s:%s", errors.OpenChannelError, httpResponse.Body)
+			log.Infof("%s:%s", errors.OpenChannelError, httpResponse.Body)
 			response.Failed(errors.OpenChannelError, c)
 			return
 		}
@@ -152,6 +158,7 @@ func WriteData(c *gin.Context) {
 	err := c.ShouldBindJSON(&param)
 	if err != nil {
 		fmt.Printf("参数格式化异常:%s", err.Error())
+		log.Infof("参数格式化异常:%s", err.Error())
 		response.Failed(errors.ParamInvalid, c)
 		return
 	}
@@ -197,6 +204,7 @@ func WriteData(c *gin.Context) {
 	bindUserCmd := string(bindUserCmdByte)
 
 	fmt.Println(bindUserCmd)
+	log.Infoln(bindUserCmd)
 
 	//2.授时指令
 	//timeCmd := common.GetTimeCmd()
@@ -204,18 +212,22 @@ func WriteData(c *gin.Context) {
 	//timeCmd = fmt.Sprintf("%s%s", "0x", timeCmd)
 	setTimeCmd := fmt.Sprintf("%s%s", constant.SetTimeCmdPrefix, timeCmd)
 	fmt.Println(setTimeCmd)
+	log.Infoln(setTimeCmd)
 	//3.开始收集指令
 	startCollectCmd := fmt.Sprintf("%s%s", constant.StartCollectCmdPrefix, timeCmd)
 	fmt.Println(startCollectCmd)
+	log.Infoln(startCollectCmd)
 	//发送指令
 	//绑定用户
 	bindUserUrl := fmt.Sprintf("%s%s", global.Config.Gateway.BaseUrl, global.Config.Gateway.WriteDataUrl)
 	bindUserUrl = strings.Replace(bindUserUrl, "MAC", param.Mac, -1)
 	bindUserUrl = strings.Replace(bindUserUrl, "DATA", bindUserCmd, -1)
 	fmt.Println("bindUserUrl====" + bindUserUrl)
+	log.Infoln("bindUserUrl====" + bindUserUrl)
 	httpResponse := http.GetReq(bindUserUrl)
 	if httpResponse.StatusCode != 200 {
 		fmt.Printf("%s:%s", errors.BindUserFailed, httpResponse.Body)
+		log.Infof("%s:%s", errors.BindUserFailed, httpResponse.Body)
 		response.Failed(errors.BindUserFailed, c)
 		return
 	}
@@ -226,18 +238,22 @@ func WriteData(c *gin.Context) {
 	httpResponse = http.GetReq(setTimeUrl)
 	if httpResponse.StatusCode != 200 {
 		fmt.Printf("%s:%s", errors.BindUserFailed, httpResponse.Body)
+		log.Infof("%s:%s", errors.BindUserFailed, httpResponse.Body)
 		response.Failed(errors.BindUserFailed, c)
 		return
 	}
 	fmt.Println("setTimeUrl=====" + setTimeUrl)
+	log.Infoln("setTimeUrl=====" + setTimeUrl)
 	//开始收集
 	startCollectUrl := fmt.Sprintf("%s%s", global.Config.Gateway.BaseUrl, global.Config.Gateway.WriteDataUrl)
 	startCollectUrl = strings.Replace(startCollectUrl, "MAC", param.Mac, -1)
 	startCollectUrl = strings.Replace(startCollectUrl, "DATA", startCollectCmd, -1)
 	fmt.Println("startCollectUrl=====" + startCollectUrl)
+	log.Infoln("startCollectUrl=====" + startCollectUrl)
 	httpResponse = http.GetReq(startCollectUrl)
 	if httpResponse.StatusCode != 200 {
 		fmt.Printf("%s:%s", errors.StartCollocateFailed, httpResponse.Body)
+		log.Infof("%s:%s", errors.StartCollocateFailed, httpResponse.Body)
 		response.Failed(errors.StartCollocateFailed, c)
 		return
 	}
@@ -246,9 +262,11 @@ func WriteData(c *gin.Context) {
 	startTransUrl = strings.Replace(startTransUrl, "MAC", param.Mac, -1)
 	startTransUrl = strings.Replace(startTransUrl, "DATA", constant.StartTransCmd, -1)
 	fmt.Println("startTransUrl====" + startTransUrl)
+	log.Infoln("startTransUrl====" + startTransUrl)
 	httpResponse = http.GetReq(startTransUrl)
 	if httpResponse.StatusCode != 200 {
 		fmt.Printf("%s:%s", errors.StartTransFailed, httpResponse.Body)
+		log.Infof("%s:%s", errors.StartTransFailed, httpResponse.Body)
 		response.Failed(errors.StartTransFailed, c)
 		return
 	}
@@ -323,8 +341,11 @@ func StopCollect(c *gin.Context) {
 func ScanDeviceEmq(c *gin.Context) {
 	topic := "/" + global.Config.EmqConfig.GatewayMac + constant.TopicConnectSub
 	client := global.EmqClient
+
 	//停止扫描
 	fmt.Println("停止扫描")
+	log.Infoln("停止扫描")
+	global.Log4J.Info("停止扫描")
 	fmt.Println(constant.CmdStopScan)
 	Publish(client, topic, constant.CmdStopScan)
 
@@ -373,14 +394,27 @@ func StopScanDeviceEmq(c *gin.Context) {
 // @Router /v2/device/conn [post]
 func ConnectDevice2(c *gin.Context) {
 	var param gateway.ConnectDevice
+
 	err := c.ShouldBindJSON(&param)
 	if err != nil {
 		fmt.Printf("参数格式化异常:%s", err.Error())
+		global.Log4J.Info("参数格式化异常:", err.Error())
 		response.Failed(errors.ParamInvalid, c)
 		return
 	}
+	global.Log4J.Info("连接Mac:" + param.Mac)
+	info := global.DeviceMap[param.Mac]
+	for s, deviceInfo := range global.DeviceMap {
+		global.Log4J.Info("mac"+s, "deviceInfo:", deviceInfo)
+	}
+	global.Log4J.Info("设备信息:", info)
+	if info.Type == "" {
+		response.Failed("设备未入库,请先添加设备", c)
+		return
+	}
 	topic := "/" + global.Config.EmqConfig.GatewayMac + constant.TopicConnectSub
-	ConnectDeviceEmq(global.EmqClient, topic, param.Mac, "0", param.Ai, param.At)
+	mac := strings.ReplaceAll(param.Mac, ":", "")
+	ConnectDeviceEmq(global.EmqClient, topic, mac, "0", param.Ai, param.At)
 	response.Success("连接设备完成", "", c)
 	return
 }
@@ -401,15 +435,39 @@ func DisConnect(c *gin.Context) {
 	err := c.ShouldBindJSON(&param)
 	if err != nil {
 		fmt.Printf("参数格式化异常:%s", err.Error())
+		global.Log4J.Info("参数格式化异常:", err.Error())
 		response.Failed(errors.ParamInvalid, c)
 		return
 	}
 	topic := "/" + global.Config.EmqConfig.GatewayMac + constant.TopicConnectSub
-	DisConnectDeviceEmq(global.EmqClient, topic, param.Mac)
+	mac := strings.ReplaceAll(param.Mac, ":", "")
+	DisConnectDeviceEmq(global.EmqClient, topic, mac)
 	response.Success("断开设备连接成功", "", c)
 	return
 }
 
+// DisConnectAll
+// PingExample confrontation-training
+// @Summary 断开所有已连接设备
+// @Schemes
+// @Description 断开所有已连接设备
+// @Tags 设备管理
+// @Accept json
+// @Produce json
+// @Success 200 {string} string "ok"
+// @Router /v2/device/dis/connAll [get]
+func DisConnectAll(c *gin.Context) {
+	topic := "/" + global.Config.EmqConfig.GatewayMac + constant.TopicConnectSub
+	//断开所有的连接
+	for s := range global.DeviceMap {
+		if len(s) == 18 {
+			DisConnectDeviceEmq(global.EmqClient, topic, s)
+		}
+	}
+	response.Success("断开所有已连接设备成功", "", c)
+	return
+}
+
 // ConnectList
 // PingExample confrontation-training
 // @Summary 已连接列表 已连接列表中不再做任何处理,在连接或断开连接 成功或失败时系统自动调用
@@ -421,12 +479,13 @@ func DisConnect(c *gin.Context) {
 // @Success 200 {string} string "ok"
 // @Router /v2/device/connected/list [get]
 func ConnectList(c *gin.Context) {
-	//topic := "/" + global.Config.EmqConfig.GatewayMac + constant.TopicConnectSub
-	////ConnectedListEmq(global.EmqClient, topic)
-	////ConnectedNumber(global.EmqClient, topic)
-	//for i := 0; i < 6; i++ {
-	//	ConnectedListEmq(global.EmqClient, topic, strconv.Itoa(i))
-	//}
+	topic := "/" + global.Config.EmqConfig.GatewayMac + constant.TopicConnectSub
+	//ConnectedListEmq(global.EmqClient, topic)
+	//ConnectedNumber(global.EmqClient, topic)
+	for i := 0; i < 6; i++ {
+		ConnectedListEmq(global.EmqClient, topic, strconv.Itoa(i))
+		time.Sleep(time.Millisecond * 500)
+	}
 	response.Success("查询连接列表完成", "", c)
 	return
 }
@@ -447,6 +506,7 @@ func WriteDataEmq(c *gin.Context) {
 	err := c.ShouldBindJSON(&param)
 	if err != nil {
 		fmt.Printf("参数格式化异常:%s", err.Error())
+		global.Log4J.Info("参数格式化异常:", err.Error())
 		response.Failed(errors.ParamInvalid, c)
 		return
 	}
@@ -493,6 +553,7 @@ func WriteDataEmq(c *gin.Context) {
 	bindUserCmd := string(bindUserCmdByte)
 
 	fmt.Println(bindUserCmd)
+	global.Log4J.Info(bindUserCmd)
 
 	//2.授时指令
 	//timeCmd := common.GetTimeCmd()
@@ -500,9 +561,11 @@ func WriteDataEmq(c *gin.Context) {
 	//timeCmd = fmt.Sprintf("%s%s", "0x", timeCmd)
 	setTimeCmd := fmt.Sprintf("%s%s", constant.SetTimeCmdPrefix, timeCmd)
 	fmt.Println(setTimeCmd)
+	global.Log4J.Info(setTimeCmd)
 	//3.开始收集指令
 	startCollectCmd := fmt.Sprintf("%s%s", constant.StartCollectCmdPrefix, timeCmd)
 	fmt.Println(startCollectCmd)
+	global.Log4J.Info(startCollectCmd)
 	//发送指令
 	//绑定用户
 	WNP(global.EmqClient, topic, param.Mac, "FFF1", bindUserCmd)

+ 20 - 0
api/gateway/gatewayEmp.go

@@ -12,8 +12,10 @@ func Publish(client mqtt.Client, topic string, message string) {
 
 	if token := client.Publish(topic, byte(global.EmqConfig.Qos), false, message); token.Wait() && token.Error() != nil {
 		fmt.Printf("publish failed, topic: %s, payload: %s\n", topic, message)
+		global.Log4J.Info("publish failed, topic: "+topic+", payload: ", message)
 	} else {
 		fmt.Printf("publish success, topic: %s, payload: %s\n", topic, message)
+		global.Log4J.Info("publish success, topic: "+topic+", payload: ", message)
 	}
 	//time.Sleep(time.Second * 1)
 	time.Sleep(time.Millisecond * 100)
@@ -23,8 +25,10 @@ func SendUUID(client mqtt.Client, topic string) {
 
 	if token := client.Publish(topic, byte(global.EmqConfig.Qos), false, constant.CmdSetUUID); token.Wait() && token.Error() != nil {
 		fmt.Printf("publish failed, topic: %s, payload: %s\n", topic, constant.CmdSetUUID)
+		global.Log4J.Info("publish failed, topic: "+topic+", payload: ", constant.CmdSetUUID)
 	} else {
 		fmt.Printf("publish success, topic: %s, payload: %s\n", topic, constant.CmdSetUUID)
+		global.Log4J.Info("publish success, topic: "+topic+", payload: ", constant.CmdSetUUID)
 	}
 	//time.Sleep(time.Second * 1)
 	time.Sleep(time.Millisecond * 100)
@@ -34,8 +38,10 @@ func ReadUUID(client mqtt.Client, topic string) {
 	message := "[{\"cmd\":\"AT+SUUID=\",\"param\":\"?\",\"i\":\"0\"}]"
 	if token := client.Publish(topic, byte(global.EmqConfig.Qos), false, message); token.Wait() && token.Error() != nil {
 		fmt.Printf("publish failed, topic: %s, payload: %s\n", topic, message)
+		global.Log4J.Info("publish failed, topic: "+topic+", payload: ", message)
 	} else {
 		fmt.Printf("publish success, topic: %s, payload: %s\n", topic, message)
+		global.Log4J.Info("publish success, topic: "+topic+", payload: ", message)
 	}
 	//time.Sleep(time.Second * 1)
 	time.Sleep(time.Millisecond * 100)
@@ -45,8 +51,10 @@ func ConnectDeviceEmq(client mqtt.Client, topic string, mac string, index string
 	message := "[{\"cmd\":\"AT+CNN=\",\"m\":\"" + mac + "\",\"i\":\"" + index + "\",\"ai\":\"" + ai + "\",\"at\":\"" + at + "\",\"l\":\"1\",\"x\":\"251\",\"relink\":\"0\",\"timeout\":\"12000\"}]"
 	if token := client.Publish(topic, byte(global.EmqConfig.Qos), false, message); token.Wait() && token.Error() != nil {
 		fmt.Printf("publish failed, topic: %s, payload: %s\n", topic, message)
+		global.Log4J.Info("publish failed, topic: "+topic+", payload: ", message)
 	} else {
 		fmt.Printf("publish success, topic: %s, payload: %s\n", topic, message)
+		global.Log4J.Info("publish success, topic: "+topic+", payload: ", message)
 	}
 	//time.Sleep(time.Second * 1)
 	time.Sleep(time.Millisecond * 100)
@@ -55,8 +63,10 @@ func DisConnectDeviceEmq(client mqtt.Client, topic string, mac string) {
 	message := "[{\"cmd\":\"AT+DISCNN=\",\"m\":\"" + mac + "\"}]"
 	if token := client.Publish(topic, byte(global.EmqConfig.Qos), false, message); token.Wait() && token.Error() != nil {
 		fmt.Printf("publish failed, topic: %s, payload: %s\n", topic, message)
+		global.Log4J.Info("publish failed, topic: "+topic+", payload: ", message)
 	} else {
 		fmt.Printf("publish success, topic: %s, payload: %s\n", topic, message)
+		global.Log4J.Info("publish success, topic: "+topic+", payload: ", message)
 	}
 	//time.Sleep(time.Second * 1)
 	time.Sleep(time.Millisecond * 100)
@@ -65,8 +75,10 @@ func ConnectedNumber(client mqtt.Client, topic string) {
 	message := "{\"cmd\":\"AT+CNB=\",\"param\":\"?\"}"
 	if token := client.Publish(topic, byte(global.EmqConfig.Qos), false, message); token.Wait() && token.Error() != nil {
 		fmt.Printf("publish failed, topic: %s, payload: %s\n", topic, message)
+		global.Log4J.Info("publish failed, topic: "+topic+", payload: ", message)
 	} else {
 		fmt.Printf("publish success, topic: %s, payload: %s\n", topic, message)
+		global.Log4J.Info("publish success, topic: "+topic+", payload: ", message)
 	}
 	//time.Sleep(time.Second * 1)
 	time.Sleep(time.Millisecond * 100)
@@ -76,8 +88,10 @@ func ConnectedListEmq(client mqtt.Client, topic string, index string) {
 	message := "{\"cmd\":\"AT+QUE=\",\"param\":\"?\",\"h\":\"" + index + "\"}"
 	if token := client.Publish(topic, byte(global.EmqConfig.Qos), false, message); token.Wait() && token.Error() != nil {
 		fmt.Printf("publish failed, topic: %s, payload: %s\n", topic, message)
+		global.Log4J.Info("publish failed, topic: "+topic+", payload: ", message)
 	} else {
 		fmt.Printf("publish success, topic: %s, payload: %s\n", topic, message)
+		global.Log4J.Info("publish success, topic: "+topic+", payload: ", message)
 	}
 	//time.Sleep(time.Second * 1)
 	time.Sleep(time.Millisecond * 100)
@@ -88,8 +102,10 @@ func WNP(client mqtt.Client, topic string, mac string, uuid string, data string)
 	message := "[{\"cmd\":\"AT+WNP=\",\"m\":\"" + mac + "\",\"s\":\"FFF0\",\"u\":\"" + uuid + "\",\"d\":\"" + data + "\"}]"
 	if token := client.Publish(topic, byte(global.EmqConfig.Qos), false, message); token.Wait() && token.Error() != nil {
 		fmt.Printf("publish failed, topic: %s, payload: %s\n", topic, message)
+		global.Log4J.Info("publish failed, topic: "+topic+", payload: ", message)
 	} else {
 		fmt.Printf("publish success, topic: %s, payload: %s\n", topic, message)
+		global.Log4J.Info("publish success, topic: "+topic+", payload: ", message)
 	}
 	//time.Sleep(time.Second * 1)
 	time.Sleep(time.Millisecond * 100)
@@ -101,8 +117,10 @@ func W(client mqtt.Client, topic string, mac string, uuid string, data string) {
 	//messagee = "[{\"cmd\":\"AT+W=\",\"m\":\"" + mac + "\",\"s\":\"FFF1\",\"u\":\"" + uuid + "\",\"d\":\"" + data + "\"}]"
 	if token := client.Publish(topic, byte(global.EmqConfig.Qos), false, message); token.Wait() && token.Error() != nil {
 		fmt.Printf("publish failed, topic: %s, payload: %s\n", topic, message)
+		global.Log4J.Info("publish failed, topic: "+topic+", payload: ", message)
 	} else {
 		fmt.Printf("publish success, topic: %s, payload: %s\n", topic, message)
+		global.Log4J.Info("publish success, topic: "+topic+", payload: ", message)
 	}
 	//time.Sleep(time.Second * 1)
 	time.Sleep(time.Millisecond * 100)
@@ -112,8 +130,10 @@ func Read(client mqtt.Client, topic string, mac string, uuid string) {
 	message := "[{\"cmd\":\"AT+W=\",\"m\":\"" + mac + "\",\"s\":\"FFF0\",\"u\":\"" + uuid + "\"]"
 	if token := client.Publish(topic, byte(global.EmqConfig.Qos), false, message); token.Wait() && token.Error() != nil {
 		fmt.Printf("publish failed, topic: %s, payload: %s\n", topic, message)
+		global.Log4J.Info("publish failed, topic: "+topic+", payload: ", message)
 	} else {
 		fmt.Printf("publish success, topic: %s, payload: %s\n", topic, message)
+		global.Log4J.Info("publish success, topic: "+topic+", payload: ", message)
 	}
 	//time.Sleep(time.Second * 1)
 	time.Sleep(time.Millisecond * 100)

+ 7 - 0
api/gateway/user.go

@@ -9,6 +9,7 @@ import (
 	"confrontation-training/service"
 	"fmt"
 	"github.com/gin-gonic/gin"
+	log "github.com/sirupsen/logrus"
 )
 
 type UserService struct {
@@ -35,6 +36,7 @@ func (u *UserService) UseRegister(c *gin.Context) {
 	err := c.ShouldBindJSON(&param)
 	if err != nil {
 		fmt.Printf("参数格式化异常:%s", err.Error())
+		log.Infof("参数格式化异常:%s", err.Error())
 		response.Failed(errors.ParamInvalid, c)
 		return
 	}
@@ -69,6 +71,7 @@ func (u *UserService) UserLogin(c *gin.Context) {
 
 	if err != nil {
 		fmt.Printf("参数格式化异常:%s", err.Error())
+		log.Infof("参数格式化异常:%s", err.Error())
 		response.Failed(errors.ParamInvalid, c)
 		return
 	}
@@ -101,16 +104,19 @@ func (u *UserService) ResetPassword(c *gin.Context) {
 	err := c.ShouldBindJSON(&param)
 	if err != nil {
 		fmt.Printf("参数格式化异常:%s", err.Error())
+		log.Infof("参数格式化异常:%s", err.Error())
 		response.Failed(errors.ParamInvalid, c)
 		return
 	}
 	if admin := u.FindUserByPhoneAndRole(param.Phone, constant.RoleAdmin); admin == nil {
 		fmt.Printf("管理员"+errors.UserNotExists+"%s", param.Phone)
+		log.Infof("管理员"+errors.UserNotExists+"%s", param.Phone)
 		response.Failed("管理员"+errors.UserNotExists+param.Phone, c)
 		return
 	}
 	if normalUser := u.FindUserByPhoneAndRole(param.PhoneInit, constant.RoleNormal); normalUser == nil {
 		fmt.Printf(errors.UserNotExists+"%s", param.PhoneInit)
+		log.Infof(errors.UserNotExists+"%s", param.PhoneInit)
 		response.Failed(errors.UserNotExists+param.PhoneInit, c)
 		return
 	}
@@ -145,6 +151,7 @@ func (u *UserService) UserList(c *gin.Context) {
 	err := c.ShouldBindJSON(&param)
 	if err != nil {
 		fmt.Printf(errors.ParamInvalid+"%s", err.Error())
+		log.Infof(errors.ParamInvalid+"%s", err.Error())
 		response.Failed(errors.ParamInvalid, c)
 		return
 	}

BIN
db/confrontation-training.db


+ 2 - 0
global/global.go

@@ -4,6 +4,7 @@ import (
 	"confrontation-training/config"
 	"confrontation-training/models/gateway"
 	mqtt "github.com/eclipse/paho.mqtt.golang"
+	"github.com/gohutool/log4go"
 	"github.com/r3labs/sse/v2"
 	"gorm.io/gorm"
 )
@@ -16,4 +17,5 @@ var (
 	DeviceMap       map[string]gateway.DeviceInfo
 	EmqClient       mqtt.Client
 	EmqConfig       config.EmqConfig
+	Log4J           log4go.Logger
 )

+ 1 - 0
go.mod

@@ -6,6 +6,7 @@ require (
 	github.com/eclipse/paho.mqtt.golang v1.4.3
 	github.com/forgoer/openssl v1.6.0
 	github.com/gin-gonic/gin v1.9.1
+	github.com/gohutool/log4go v1.0.2
 	github.com/golang-jwt/jwt v3.2.2+incompatible
 	github.com/google/uuid v1.1.2
 	github.com/gorilla/websocket v1.5.0

+ 2 - 0
go.sum

@@ -112,6 +112,8 @@ github.com/go-playground/validator/v10 v10.15.1 h1:BSe8uhN+xQ4r5guV/ywQI4gO59C2r
 github.com/go-playground/validator/v10 v10.15.1/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
 github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
 github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
+github.com/gohutool/log4go v1.0.2 h1:iV8TkROQG+Cqvegg1zC5PPane1PAMwJ5vLFof9/1k8w=
+github.com/gohutool/log4go v1.0.2/go.mod h1:NNSgiNWEro9XhO3antf1DxcjnICKEPdOux7kMGn8dGA=
 github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
 github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
 github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k=

+ 36 - 10
initialize/emq.go

@@ -12,7 +12,7 @@ import (
 	"fmt"
 	mqtt "github.com/eclipse/paho.mqtt.golang"
 	"github.com/gorilla/websocket"
-	"log"
+	log "github.com/sirupsen/logrus"
 	"strconv"
 	"strings"
 	"time"
@@ -35,6 +35,7 @@ func CreateEmqClient() {
 	emqConfig := global.EmqConfig
 	connectAddress := fmt.Sprintf("%s://%s:%d", emqConfig.Protocol, emqConfig.Broker, emqConfig.Port)
 	fmt.Println("connect address:", connectAddress)
+	global.Log4J.Info("connect address:", connectAddress)
 	opts := mqtt.NewClientOptions()
 	opts.AddBroker(connectAddress)
 	opts.SetUsername(emqConfig.UserName)
@@ -45,7 +46,7 @@ func CreateEmqClient() {
 	client := global.EmqClient
 	token := client.Connect()
 	if token.WaitTimeout(time.Second*3) && token.Error() != nil {
-		log.Fatal(token.Error())
+		global.Log4J.Error(token.Error())
 	}
 	SubScribe(client)
 	topic := "/" + global.Config.EmqConfig.GatewayMac + constant.TopicConnectSub
@@ -53,12 +54,14 @@ func CreateEmqClient() {
 
 	//添加过滤
 	fmt.Println("添加设备过滤:")
+	global.Log4J.Info("添加设备过滤:")
 	filterCmd := "[{\"cmd\":\"AT+FLT=\",\"total\":\"2\"}"
 	for _, filter := range global.EmqConfig.Filter {
 		filterCmd = filterCmd + ",{\"t\":\"0\",\"d\":\"" + filter + "\"}"
 	}
 	filterCmd = filterCmd + "]"
 	fmt.Println(filterCmd)
+	global.Log4J.Info(filterCmd)
 	//filterCmd = "[{\"cmd\":\"AT+FLT=\",\"total\":\"2\"},{\"t\":\"0\",\"d\":\"MIND\"},{\"t\":\"0\",\"d\":\"BW-ECG\"}]"
 	Publish(client, topic, filterCmd)
 	//SendUUID(client, "/EE3870DA24C4/connect_packet/connect1_subscribe")
@@ -77,8 +80,10 @@ func Publish(client mqtt.Client, topic string, message string) {
 
 	if token := client.Publish(topic, byte(global.EmqConfig.Qos), false, message); token.Wait() && token.Error() != nil {
 		fmt.Printf("publish failed, topic: %s, payload: %s\n", topic, message)
+		global.Log4J.Info("publish failed, topic: ", topic, "payload: ", message)
 	} else {
 		fmt.Printf("publish success, topic: %s, payload: %s\n", topic, message)
+		global.Log4J.Info("publish failed, topic: ", topic, "payload: ", message)
 	}
 	//time.Sleep(time.Second * 1)
 	time.Sleep(time.Millisecond * 100)
@@ -87,8 +92,11 @@ func SendUUID(client mqtt.Client, topic string) {
 
 	if token := client.Publish(topic, byte(global.EmqConfig.Qos), false, constant.CmdSetUUID); token.Wait() && token.Error() != nil {
 		fmt.Printf("publish failed, topic: %s, payload: %s\n", topic, constant.CmdSetUUID)
+		global.Log4J.Info("publish failed, topic: ", topic, "payload: ", constant.CmdSetUUID)
+
 	} else {
 		fmt.Printf("publish success, topic: %s, payload: %s\n", topic, constant.CmdSetUUID)
+		global.Log4J.Info("publish success, topic: ", topic, "payload: ", constant.CmdSetUUID)
 	}
 	//time.Sleep(time.Second * 1)
 	time.Sleep(time.Millisecond * 100)
@@ -97,8 +105,11 @@ func ConnectDevice(client mqtt.Client, topic string, mac string, index string, a
 	message := "[{\"cmd\":\"AT+CNN=\",\"m\":\"" + mac + "\",\"i\":\"" + index + "\",\"ai\":\"" + ai + "\",\"at\":\"" + at + "\",\"l\":\"1\",\"x\":\"251\",\"relink\":\"0\",\"timeout\":\"12000\"}]"
 	if token := client.Publish(topic, byte(global.EmqConfig.Qos), false, message); token.Wait() && token.Error() != nil {
 		fmt.Printf("publish failed, topic: %s, payload: %s\n", topic, message)
+		global.Log4J.Info("publish failed, topic: ", topic, "payload: ", message)
+
 	} else {
 		fmt.Printf("publish success, topic: %s, payload: %s\n", topic, message)
+		global.Log4J.Info("publish success, topic: ", topic, "payload: ", message)
 	}
 	//time.Sleep(time.Second * 1)
 	time.Sleep(time.Millisecond * 100)
@@ -108,6 +119,7 @@ func SubScribe(client mqtt.Client) {
 	ws, _, err := websocket.DefaultDialer.Dial(global.Config.Websocket.WSUrl, nil)
 	if err != nil {
 		fmt.Println("socket通道初始化失败")
+		global.Log4J.Error("socket通道初始化失败")
 		panic(err)
 		return
 	}
@@ -122,6 +134,7 @@ func SubScribe(client mqtt.Client) {
 	for _, topic := range emqConfig.Topic {
 		topic = "/" + global.EmqConfig.GatewayMac + topic
 		client.Subscribe(topic, byte(emqConfig.Qos), func(client mqtt.Client, message mqtt.Message) {
+			global.Log4J.Info("`%s` Received `%s` from `%s` topic\n", common.NowTime("2006-01-02 15:04:05"), message.Payload(), message.Topic())
 			fmt.Printf("`%s` Received `%s` from `%s` topic\n", common.NowTime("2006-01-02 15:04:05"), message.Payload(), message.Topic())
 			messageMap := make(map[string]string)
 			var payloads []emq.Payload
@@ -151,6 +164,7 @@ func SubScribe(client mqtt.Client) {
 							} else if strings.HasPrefix(payload.N, "BW-ECG") {
 								payload.T = "1"
 							}
+							payload.M = transMac(payload.M)
 							messageMap["msgType"] = constant.MessageTypeDeviceScanned
 							marshal, _ := json.Marshal(payload)
 							content = string(marshal)
@@ -171,12 +185,14 @@ func SubScribe(client mqtt.Client) {
 				case constant.PayloadConnect:
 					messageMap["msgType"] = constant.MessageTypeConnect
 					//content = "设备连接"
-					realMac := transMac(payload.M)
-					deviceInfo := global.DeviceMap[realMac]
-					payload.T = deviceInfo.Type
-					marshal, _ := json.Marshal(payload)
-					content = string(marshal)
-					//连接成功或连接失败,发送已连接设备列表
+					if payload.State == "SUCCESS" {
+						realMac := transMac(payload.M)
+						deviceInfo := global.DeviceMap[realMac]
+						payload.T = deviceInfo.Type
+						marshal, _ := json.Marshal(payload)
+						content = string(marshal)
+						//连接成功或连接失败,发送已连接设备列表
+					}
 					for i := 0; i < 6; i++ {
 						topic := "/" + global.Config.EmqConfig.GatewayMac + constant.TopicConnectSub
 						gateway2.ConnectedListEmq(global.EmqClient, topic, strconv.Itoa(i))
@@ -190,6 +206,7 @@ func SubScribe(client mqtt.Client) {
 					realMac := transMac(payload.M)
 					deviceInfo := global.DeviceMap[realMac]
 					payload.T = deviceInfo.Type
+					payload.M = realMac
 					marshal, _ := json.Marshal(payload)
 					content = string(marshal)
 					//断开连接成功或连接失败,发送已连接设备列表
@@ -210,6 +227,7 @@ func SubScribe(client mqtt.Client) {
 						} else {
 							payload.T = deviceInfo.Type
 							payload.N = deviceInfo.Name
+							payload.M = transMac(payload.M)
 							marshal, _ := json.Marshal(payload)
 							content = string(marshal)
 						}
@@ -227,8 +245,13 @@ func SubScribe(client mqtt.Client) {
 					deviceInfo := global.DeviceMap[realMac]
 					payload.T = deviceInfo.Type
 					payload.N = deviceInfo.Name
+					payload.M = transMac(payload.M)
 					marshal, _ := json.Marshal(payload)
 					content = string(marshal)
+					for i := 0; i < 6; i++ {
+						topic := "/" + global.Config.EmqConfig.GatewayMac + constant.TopicConnectSub
+						gateway2.ConnectedListEmq(global.EmqClient, topic, strconv.Itoa(i))
+					}
 				case constant.PayloadNotify: //接收到蓝牙通知数据
 					//1.判断是脑电数据还是心电数据
 					//1.1脑电数据直接转发
@@ -236,7 +259,7 @@ func SubScribe(client mqtt.Client) {
 					realMac := transMac(payload.M)
 					deviceInfo := global.DeviceMap[realMac]
 					var receiveData gateway.DeviceDataReceived
-					receiveData.Mac = payload.M
+					receiveData.Mac = realMac
 					receiveData.Value = payload.D
 					if deviceInfo.Type == "0" { //脑电
 						messageMap["msgType"] = constant.MessageTypeEEGData
@@ -295,13 +318,16 @@ func SubScribe(client mqtt.Client) {
 					if messageMap["msgType"] == constant.MessageTypeECGData {
 
 						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)
 					}
+					global.Log4J.Info("发送消息===" + common.NowTime("2006-01-02 15:04:05") + "=====" + string(bytes))
 					err = ws.WriteMessage(websocket.TextMessage, bytes)
 					if err != nil {
-						fmt.Println("消息发送异常:" + err.Error())
+						log.Infoln("消息发送异常:" + err.Error())
+						global.Log4J.Error("消息发送异常:" + err.Error())
 					}
 				}
 				time.Sleep(time.Millisecond * 5)

+ 3 - 0
initialize/gorm.go

@@ -3,6 +3,7 @@ package initialize
 import (
 	"confrontation-training/global"
 	"fmt"
+	log "github.com/sirupsen/logrus"
 	"gorm.io/driver/sqlite"
 	"gorm.io/gorm"
 	"gorm.io/gorm/schema"
@@ -20,11 +21,13 @@ func SQLite() {
 	})
 	if err != nil {
 		fmt.Printf("mysql error :%s", err.Error())
+		log.Infof("mysql error :%s", err.Error())
 		return
 	}
 	sqlDb, err := db.DB()
 	if err != nil {
 		fmt.Printf("mysql error :%s", err.Error())
+		log.Infof("mysql error :%s", err.Error())
 	}
 	sqlDb.SetMaxIdleConns(10)
 	sqlDb.SetMaxOpenConns(100)

+ 4 - 0
initialize/load.go

@@ -3,6 +3,7 @@ package initialize
 import (
 	"confrontation-training/global"
 	"fmt"
+	"github.com/gohutool/log4go"
 	"github.com/spf13/viper"
 )
 
@@ -16,4 +17,7 @@ func LoadConfig() {
 	if err := viper.Unmarshal(&global.Config); err != nil {
 		fmt.Printf("Unable to decode into structure Config %s \n", err.Error())
 	}
+	global.Log4J = log4go.LoggerManager.GetLogger("ct")
+	log4go.LoggerManager.InitWithXML("./config/log4j.xml")
+
 }

+ 4 - 0
initialize/router.go

@@ -12,6 +12,7 @@ import (
 	modelsDevice "confrontation-training/models/gateway"
 	"fmt"
 	"github.com/gin-gonic/gin"
+	log "github.com/sirupsen/logrus"
 	swaggerFiles "github.com/swaggo/files"
 	ginSwagger "github.com/swaggo/gin-swagger"
 	"net/http"
@@ -23,6 +24,7 @@ func Router() {
 	initTableErr := global.Db.AutoMigrate(&models.User{}, &modelsChat.Question{}, &modelsChat.Answer{}, &modelsDevice.DeviceInfo{})
 	if initTableErr != nil {
 		fmt.Printf("初始化表格异常:%s", initTableErr.Error())
+		log.Infof("初始化表格异常:%s", initTableErr.Error())
 		return
 	}
 	gin.SetMode(gin.ReleaseMode)
@@ -76,6 +78,7 @@ func Router() {
 	device2.GET("/stop/scan", gateway.StopScanDeviceEmq)
 	device2.POST("/conn", gateway.ConnectDevice2)
 	device2.POST("/dis/conn", gateway.DisConnect)
+	device2.POST("/dis/connAll", gateway.DisConnectAll)
 	device2.GET("/connected/list", gateway.ConnectList)
 	device2.POST("/write/data", gateway.WriteDataEmq)
 	//初始化SSE
@@ -88,6 +91,7 @@ func Router() {
 	err := engine.Run(fmt.Sprintf(":%s", global.Config.Server.Port))
 	if err != nil {
 		fmt.Printf("%s", err.Error())
+		log.Infof("%s", err.Error())
 		return
 	}
 }

+ 8 - 7
initialize/ws.go

@@ -1,10 +1,11 @@
 package initialize
 
 import (
+	"confrontation-training/global"
 	"encoding/json"
 	"github.com/gin-gonic/gin"
 	"github.com/gorilla/websocket"
-	"log"
+	log "github.com/sirupsen/logrus"
 	"net/http"
 )
 
@@ -41,15 +42,16 @@ var Manager = ClientManager{
 // Start is  项目运行前, 协程开启start -> go Manager.Start()
 func (manager *ClientManager) Start() {
 	for {
-		log.Println("<---管道通信--->")
+		log.Infoln("<---管道通信--->")
+
 		select {
 		case conn := <-Manager.Register:
-			log.Printf("新用户加入:%v", conn.ID)
+			log.Infof("新用户加入:%v", conn.ID)
 			Manager.Clients[conn.ID] = conn
 			jsonMessage, _ := json.Marshal(&Message{Content: "Successful connection to socket service"})
 			conn.Send <- jsonMessage
 		case conn := <-Manager.Unregister:
-			log.Printf("用户离开:%v", conn.ID)
+			log.Infof("用户离开:%v", conn.ID)
 			if _, ok := Manager.Clients[conn.ID]; ok {
 				jsonMessage, _ := json.Marshal(&Message{Content: "A socket has disconnected"})
 				conn.Send <- jsonMessage
@@ -96,7 +98,7 @@ func (c *Client) Read() {
 			c.Socket.Close()
 			break
 		}
-		//log.Printf("读取到客户端的信息:%s", string(message))
+		//log.Infof("读取到客户端的信息:%s", string(message))
 		Manager.Broadcast <- message
 	}
 }
@@ -113,8 +115,7 @@ func (c *Client) Write() {
 				c.Socket.WriteMessage(websocket.CloseMessage, []byte{})
 				return
 			}
-			//log.Printf("发送到到客户端的信息:%s", string(message))
-
+			global.Log4J.Info("发送到到客户端的信息:", string(message))
 			c.Socket.WriteMessage(websocket.TextMessage, message)
 		}
 	}

+ 4 - 0
middleware/log_2_file.go

@@ -99,6 +99,9 @@ func LoggerToFile() gin.HandlerFunc {
 		//clientIP := c.ClientIP()
 		clientIP := c.RemoteIP()
 
+		//请求参数
+		requestParam := c.Params
+
 		// 日志格式
 		logger.WithFields(logrus.Fields{
 			"status_code":  statusCode,
@@ -106,6 +109,7 @@ func LoggerToFile() gin.HandlerFunc {
 			"client_ip":    clientIP,
 			"req_method":   reqMethod,
 			"req_uri":      reqUri,
+			"req_param":    requestParam,
 		}).Info()
 	}
 }