siked 1 year ago
parent
commit
60798f7134

+ 3 - 3
.idea/deployment.xml

@@ -1,11 +1,11 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <project version="4">
-  <component name="PublishConfigData" autoUpload="Always" serverName="Alot" remoteFilesAllowedToDisappearOnAutoupload="false">
+  <component name="PublishConfigData" autoUpload="On explicit save action" serverName="Alot" remoteFilesAllowedToDisappearOnAutoupload="false">
     <serverData>
       <paths name="Alot">
         <serverdata>
           <mappings>
-            <mapping deploy="/home/bzd/GolandProjects/Yunlot" local="$PROJECT_DIR$" web="/" />
+            <mapping deploy="/Yunlot" local="$PROJECT_DIR$" web="/" />
           </mappings>
           <excludedPaths>
             <excludedPath path="/home/bzd/GolandProjects/Yunlot/.idea" />
@@ -20,6 +20,6 @@
         </serverdata>
       </paths>
     </serverData>
-    <option name="myAutoUpload" value="ALWAYS" />
+    <option name="myAutoUpload" value="ON_EXPLICIT_SAVE" />
   </component>
 </project>

+ 32 - 34
Handle/Handle.go

@@ -2,12 +2,12 @@ package Handle
 
 import (
 	"Yunlot/conf"
-	"Yunlot/lib"
 	"Yunlot/logs"
 	"Yunlot/models/Device"
 	"Yunlot/models/Product"
 	"encoding/hex"
 	"encoding/json"
+	"errors"
 	"fmt"
 	"go.mongodb.org/mongo-driver/bson"
 	"plugin"
@@ -16,18 +16,13 @@ import (
 )
 
 // 设备->平台
-func PullHandle(Device_r *Device.Device, topicName string, message []byte) lib.JSONR {
+func PullHandle(Device_r *Device.Device, topicName string, message []byte) error {
 	DeviceRealLogR_ := []string{}
-
-	var Rt_r = lib.JSONR{Code: 200, Msg: "ok"}
-
 	// 设备协议
 	ProductProt_r := Product.ProductProt{Id: Device_r.T_ProductJson.T_prot}
 	if !ProductProt_r.Read() {
 		logs.Println("MqttServer", Device_r.T_sn+"|"+Device_r.T_ProductID+"-"+fmt.Sprintf("%d", Device_r.T_ProductJson.T_prot)+" 设备协议找不到!")
-		Rt_r.Code = 203
-		Rt_r.Msg = "T_prot E!"
-		return Rt_r
+		return errors.New("T_prot E!")
 	}
 
 	//  加入设备日志  类型
@@ -44,17 +39,15 @@ func PullHandle(Device_r *Device.Device, topicName string, message []byte) lib.J
 		p, err := plugin.Open(conf.Analysis_Dir + ProductProt_r.T_analysis + ".so")
 		if err != nil {
 			logs.PrintlnError("打开 SO 失败:", err)
-			Rt_r.Code = 203
-			Rt_r.Msg = "T_analysis E!"
-			return Rt_r
+			return errors.New("T_analysis E!")
 		}
 		logs.Println("Plugin 地址:", &p)
 
 		// 查找库导出信息
 		s, err := p.Lookup("T")
 		if err != nil {
-			logs.Println("", err)
-			panic(any(err))
+			logs.PrintlnError("Plugin:", err)
+			return errors.New("Plugin E!")
 		}
 		// 类型转换
 		messagejson = s.(func(t string, b []byte) string)(topicName, message)
@@ -70,9 +63,7 @@ func PullHandle(Device_r *Device.Device, topicName string, message []byte) lib.J
 		var json_r map[string]interface{}
 		err := json.Unmarshal([]byte(messagejson), &json_r)
 		if err != nil {
-			Rt_r.Code = 203
-			Rt_r.Msg = "json E!"
-			return Rt_r
+			return errors.New("json E!")
 		}
 
 		json_r = AnalysisMap(Device_r, json_r, "")
@@ -132,17 +123,17 @@ func PullHandle(Device_r *Device.Device, topicName string, message []byte) lib.J
 		logs.DeviceRealLogMap[Device_r.T_sn] = v
 	}
 
-	return Rt_r
+	return nil
 }
 
 // 平台->设备
-func PushHandle(Device_r *Device.Device, topicName string, message string) (string, []byte) {
+func PushHandle(Device_r *Device.Device, topicName string, message string) error {
 	DeviceRealLogR_ := []string{}
 	// 设备协议
 	ProductProt_r := Product.ProductProt{Id: Device_r.T_ProductJson.T_prot}
 	if !ProductProt_r.Read() {
 		logs.Println("PushHandle", Device_r.T_sn+"|"+Device_r.T_ProductID+"-"+fmt.Sprintf("%d", Device_r.T_ProductJson.T_prot)+" 设备协议找不到!")
-		return "", []byte{}
+		return errors.New("设备协议找不到")
 	}
 
 	var byte_r []byte
@@ -153,14 +144,14 @@ func PushHandle(Device_r *Device.Device, topicName string, message string) (stri
 		p, err := plugin.Open(conf.Analysis_Dir + ProductProt_r.T_analysis + ".so")
 		if err != nil {
 			logs.PrintlnError("PushHandle:", err)
-			return "", []byte{}
+			return err
 		}
 
 		// 查找库导出信息
 		s, err := p.Lookup("R")
 		if err != nil {
 			logs.PrintlnError("PushHandle:", err)
-			return "", []byte{}
+			return err
 		}
 		DeviceRealLogR_ = append(DeviceRealLogR_, "->转换["+topicName+"]\\r\\n"+time.Now().Format("15:04:05")+"\\r\\n"+message) //  加入设备日志
 		// 类型转换
@@ -173,23 +164,30 @@ func PushHandle(Device_r *Device.Device, topicName string, message string) (stri
 	// 无效消息,不用推送
 	if len(topicName_r) == 0 || len(byte_r) == 0 {
 		logs.Println("无效消息,不用推送!", len(topicName_r), len(byte_r))
-		return "", []byte{}
+		return errors.New("无效消息,不用推送")
 	}
 
 	// 长连接 网关
 	logs.Println("ProductProt_r.T_mode:", ProductProt_r.T_mode)
-	switch ProductProt_r.T_mode {
-	case 1: //mqtt
-		// 如果 订阅地址与发布相同,在后面强行加 _reply,避免发布后无法收到消息
-		if topicName_r == topicName {
-			topicName_r += "_reply"
-		}
-		lib.Mqtt_publish(topicName_r, byte_r) // 返回数据
-		break
-	case 2: //tcp
-		lib.TCP_publish(Device_r.T_sn, byte_r)
-		break
 
+	ProductMode_r, is := Product.ProductModeMap[ProductProt_r.T_mode]
+	if !is {
+		logs.Println("没有找到网关!", ProductProt_r.T_mode)
+		return errors.New("没有找到网关!")
+	}
+
+	//初始化插件
+	FunPushHandle_r, err := ProductMode_r.T_Plugin.Lookup("FunPushHandle")
+	if err != nil {
+		logs.Println("网关 错误!", ProductProt_r.T_mode, err)
+		return errors.New("网关 错误!")
+	}
+
+	// 初始化插件
+	err = FunPushHandle_r.(func(T_topic string, T_data []byte) error)(topicName_r, byte_r)
+	if err != nil {
+		logs.Println("网关 推送失败!", ProductProt_r.T_mode, err)
+		return errors.New("网关 推送失败!")
 	}
 
 	if byte_r[0] == '{' {
@@ -204,7 +202,7 @@ func PushHandle(Device_r *Device.Device, topicName string, message string) (stri
 		logs.DeviceRealLogMap[Device_r.T_sn] = v
 	}
 
-	return topicName_r, byte_r
+	return nil
 
 }
 

+ 0 - 114
Handle/HttpServer/Server.go

@@ -1,114 +0,0 @@
-package HttpServer
-
-import (
-	"Yunlot/Handle"
-	"Yunlot/conf"
-	"Yunlot/lib"
-	"Yunlot/logs"
-	"Yunlot/models/Device"
-	"encoding/json"
-	"fmt"
-	"github.com/gin-gonic/gin"
-	"strings"
-)
-
-func ReturnHandle(Device_r *Device.Device, topicName string, data lib.JSONR) interface{} {
-	b, _ := json.Marshal(data)
-	_, byte_r := Handle.PushHandle(Device_r, topicName, string(b))
-	var json_r map[string]interface{}
-
-	if len(byte_r) > 0 {
-		err := json.Unmarshal(byte_r, &json_r)
-		if err == nil {
-			return json_r
-		}
-		return byte_r
-	}
-
-	err := json.Unmarshal(byte_r, &json_r)
-	if err == nil {
-		return json_r
-	}
-	return b
-}
-
-func json_key() {
-
-}
-
-func Run() {
-
-	// 创建一个Gin路由器
-	r := gin.Default()
-
-	//设备上报属性
-	r.POST("/*topicName", func(c *gin.Context) {
-		logs.Println("T_sn:", c.Query("T_sn"))
-		logs.Println("topicName:", c.Param("topicName"))
-
-		Device_r := Device.Device{T_sn: c.Query("T_sn")}
-		if !Device_r.Read_Tidy() {
-			c.JSON(200, lib.JSONR{Code: lib.Error, Msg: "T_sn 错误!"})
-			return
-		}
-		if Device_r.T_state != 1 {
-			c.JSON(200, lib.JSONR{Code: lib.Error, Msg: "T_sn 错误!"})
-			return
-		}
-		if Device_r.T_password != c.Query("T_password") {
-			c.JSON(200, ReturnHandle(&Device_r, c.Param("topicName"), lib.JSONR{Code: lib.Error, Msg: "T_password 错误!"}))
-			return
-		}
-
-		//
-		byte_r, err := c.GetRawData()
-		if err != nil {
-			c.JSON(200, ReturnHandle(&Device_r, c.Param("topicName"), lib.JSONR{Code: lib.Error, Msg: "JSON 错误!"}))
-			return
-		}
-		if len(byte_r) == 0 {
-			c.JSON(200, ReturnHandle(&Device_r, c.Param("topicName"), lib.JSONR{Code: lib.Error, Msg: "JSON 错误!"}))
-			return
-		}
-		logs.Println("byte", string(byte_r))
-
-		// 转换
-		Rt_r := Handle.PullHandle(&Device_r, c.Param("topicName"), byte_r)
-		//logs.Println("ReturnHandle:",string(ReturnHandle(&Device_r,c.Param("topicName"),Rt_r)))
-
-		c.JSON(200, ReturnHandle(&Device_r, c.Param("topicName"), Rt_r))
-		return
-	})
-
-	//获取属性
-	r.GET("/*topicName", func(c *gin.Context) {
-		logs.Println("T_sn:", c.Query("T_sn"))
-		logs.Println("topicName:", c.Param("topicName"))
-
-		Device_r := Device.Device{T_sn: c.Query("T_sn")}
-		if !Device_r.Read_Tidy() {
-			c.JSON(200, lib.JSONR{Code: lib.Error, Msg: "T_sn 错误!"})
-			return
-		}
-		if Device_r.T_state != 1 {
-			c.JSON(200, lib.JSONR{Code: lib.Error, Msg: "T_sn 错误!"})
-			return
-		}
-		if Device_r.T_password != c.Query("T_password") {
-			c.JSON(200, ReturnHandle(&Device_r, c.Param("topicName"), lib.JSONR{Code: lib.Error, Msg: "T_password 错误!"}))
-			return
-		}
-
-		topicName := strings.Trim(c.Param("topicName"), "/") // 参数: /A/B/C/D
-
-		topicNameList := strings.Split(topicName, "/") // 分割数组
-
-		x := lib.Json_key(topicNameList, 0, Device_r.T_dataJson) //获取指定 json 数据,如果失败,返回已找到的全部json
-
-		c.JSON(200, ReturnHandle(&Device_r, c.Param("topicName"), lib.JSONR{Code: lib.Success, Msg: "ok!", Data: x}))
-		return
-	})
-
-	r.Run(fmt.Sprintf(":%d", conf.HTTPServer_Port))
-
-}

+ 0 - 138
Handle/MqttServer/Clients.go

@@ -1,138 +0,0 @@
-package MqttServer
-
-import (
-	"Yunlot/Handle"
-	"Yunlot/logs"
-	"Yunlot/models/Device"
-	"encoding/json"
-	"time"
-)
-
-// /  -   连接 实体
-type Ms_Project_Connected struct {
-	Clientid  string `json:"clientid"`
-	Username  string `json:"username"`
-	Ipaddress string `json:"ipaddress"`
-	Reason    string `json:"reason"` // sha ccv
-
-}
-
-// /  -   离线断开 实体
-type Ms_Project_Disconnected struct {
-	Clientid  string `json:"clientid"`
-	Username  string `json:"username"`
-	Ipaddress string `json:"ipaddress"`
-	Reason    string `json:"reason"`
-	//终端连接断开原因:
-	//normal:客户端主动断开
-	//kicked:服务端踢出,通过 REST API
-	//keepalive_timeout: keepalive 超时
-	//not_authorized: 认证失败,或者 acl_nomatch = disconnect 时没有权限的 Pub/Sub 会主动断开客户端
-	//tcp_closed: 对端关闭了网络连接
-	//internal_error: 畸形报文或其他未知错误
-}
-
-// 设备连接
-func MessageConnected(topicName string, message []byte) {
-
-	logs.Println("============= MessageConnected Mqtt JSON =============")
-	logs.Println("topic:", topicName, "  message:", string(message))
-
-	//logs.Println("=>", a)
-	var Ms_project Ms_Project_Connected
-	err := json.Unmarshal(message, &Ms_project)
-	if err != nil {
-		logs.PrintlnError("MqttServer", "JSON反序列化失败[Ms_Project]", string(message))
-		return
-	}
-
-	var r_Device Device.Device
-	r_Device.T_sn = Ms_project.Clientid
-	r_Device.Read()
-	if err != nil {
-		logs.Println("MessageDisconnected 没有该设备:", Ms_project.Clientid)
-		return
-	}
-	logs.Println("Clientid:", Ms_project.Clientid)
-	logs.Println("Username:", Ms_project.Username)
-
-	r_Device.T_online = 1
-	// 同步参数
-	r_Device.Update("T_online")
-
-	var Device_online_r map[string]interface{}
-	Device_online_r = make(map[string]interface{})
-	Device_online_r["online"] = r_Device.T_online
-	Device_online_r["msg"] = "设备主动上线[" + Ms_project.Ipaddress + "]"
-	Device_online_r["time"] = time.Now().Format("2006-01-02 15:04:05")
-
-	Handle.AnalysisMap(&r_Device, map[string]interface{}{"online": Device_online_r}, "")
-
-	logs.Println("============= MessageConnected Mqtt JSON AND =============", topicName)
-}
-
-func ToReason(str string) (Reason string) {
-	switch str {
-	case "normal":
-		Reason = "客户端主动断开"
-		break
-	case "kicked":
-		Reason = "设备异常掉线,服务端踢出,通过 REST API"
-		break
-	case "keepalive_timeout":
-		Reason = "设备异常掉线,keepalive 超时"
-		break
-	case "not_authorized":
-		Reason = "设备异常掉线,认证失败"
-		break
-	case "tcp_closed":
-		Reason = "设备异常掉线,对端关闭了网络连接"
-		break
-	case "internal_error":
-		Reason = "设备异常掉线,畸形报文或其他未知错误"
-		break
-	}
-
-	return Reason
-}
-
-// 设备断开
-func MessageDisconnected(topicName string, message []byte) {
-
-	logs.Println("============= MessageDisconnected Mqtt JSON =============")
-	logs.Println("topic:", topicName, "  message:", string(message))
-
-	//logs.Println("=>", a)
-	var Ms_project Ms_Project_Disconnected
-	err := json.Unmarshal(message, &Ms_project)
-	if err != nil {
-		logs.PrintlnError("MqttServer", "JSON反序列化失败[Ms_Project]", string(message))
-		return
-	}
-
-	logs.Println("Clientid:", Ms_project.Clientid)
-	logs.Println("Username:", Ms_project.Username)
-
-	var r_Device Device.Device
-	r_Device.T_sn = Ms_project.Clientid
-	r_Device.Read()
-	if err != nil {
-		logs.Println("MessageDisconnected 没有该设备:", Ms_project.Clientid)
-		return
-	}
-
-	r_Device.T_online = 2
-	// 同步参数
-	r_Device.Update("T_online")
-
-	var Device_online_r map[string]interface{}
-	Device_online_r = make(map[string]interface{})
-	Device_online_r["online"] = r_Device.T_online
-	Device_online_r["msg"] = "设备离线[" + ToReason(Ms_project.Reason) + "]"
-	Device_online_r["time"] = time.Now().Format("2006-01-02 15:04:05")
-
-	Handle.AnalysisMap(&r_Device, map[string]interface{}{"online": Device_online_r}, "")
-
-	logs.Println("============= MessageDisconnected Mqtt JSON AND =============", topicName)
-
-}

+ 0 - 298
Handle/MqttServer/Server.go

@@ -1,298 +0,0 @@
-package MqttServer
-
-import (
-	"Yunlot/Handle"
-	"Yunlot/conf"
-	"Yunlot/lib"
-	"Yunlot/logs"
-	"Yunlot/models/Device"
-	"encoding/json"
-	"fmt"
-	beego "github.com/beego/beego/v2/server/web"
-	"github.com/gin-gonic/gin"
-	"github.com/yosssi/gmq/mqtt"
-	"github.com/yosssi/gmq/mqtt/client"
-	"strconv"
-	"strings"
-	"time"
-)
-
-func Run_MqttServer() {
-
-	time.Sleep(3 * time.Second)
-	logs.Println("============Run_MqttServer=============", "")
-	HTTPPort, _ := beego.AppConfig.String("HTTPPort")
-	// Create an MQTT Client.
-	lib.MqttClient = client.New(&client.Options{
-		// Define the processing of the error handler.
-		ErrorHandler: func(err error) {
-			logs.PrintlnError("err!!!!!! Run_MqttServer:", err.Error())
-
-			time.Sleep(3 * time.Second)
-			go Run_MqttServer() // MQTT 通讯
-
-			return
-		},
-	})
-
-	// Terminate the Client.
-	defer lib.MqttClient.Terminate()
-
-	c := client.ConnectOptions{
-		Network:  "tcp",
-		Address:  conf.MqttServer_Url,
-		ClientID: []byte(conf.MqttServer_ClientID + HTTPPort),
-		UserName: []byte(conf.MqttServer_Username),
-		Password: []byte(conf.MqttServer_Password),
-	}
-	logs.Println("Address:", c.Address)
-	logs.Println("ClientID:", string(c.ClientID))
-
-	// Connect to the MQTT Server.
-	err := lib.MqttClient.Connect(&c)
-
-	if err != nil {
-		logs.Println("MqttServer", "连接MQTT失败 [cli.Connect]", "")
-		logs.Println("err!!!!!! Run_MqttServer:", "连接MQTT失败:", err)
-		fmt.Println("err!!!!!! 连接MQTT失败:", err)
-		lib.MqttClient.Terminate()
-		time.Sleep(3 * time.Second)
-		go Run_MqttServer() // MQTT 通讯
-
-		return
-	}
-	logs.Println("MqttServer", "连接成功!")
-	// Subscribe to topics.
-	err = lib.MqttClient.Subscribe(&client.SubscribeOptions{
-		SubReqs: []*client.SubReq{
-			&client.SubReq{
-				TopicFilter: []byte("#"),
-				QoS:         mqtt.QoS0,
-				// Define the processing of the message handler.
-				Handler: func(topicName, message []byte) {
-					_, exists := lib.TopicMap[string(topicName)]
-					if exists {
-						//logs.Println("跳过:",string(topicName))
-						return // 这个 订阅号 平台->设备,跳过
-					}
-					start := time.Now()
-					messagePubHandler(string(topicName), message)
-					elapsed := time.Since(start)
-					fmt.Printf("代码运行时间:%s\n", elapsed)
-				},
-			},
-			&client.SubReq{ // 设备断开
-				TopicFilter: []byte("$SYS/brokers/+/clients/+/disconnected"),
-				QoS:         mqtt.QoS0,
-				// Define the processing of the message handler.
-				Handler: func(topicName, message []byte) {
-					logs.PrintlnMqtt("<-" + string(topicName) + " " + string(message))
-					MessageDisconnected(string(topicName), message)
-				},
-			},
-			&client.SubReq{ // 设备上线
-				TopicFilter: []byte("$SYS/brokers/+/clients/+/connected"),
-				QoS:         mqtt.QoS0,
-				// Define the processing of the message handler.
-				Handler: func(topicName, message []byte) {
-					logs.PrintlnMqtt("<-" + string(topicName) + " " + string(message))
-					MessageConnected(string(topicName), message)
-				},
-			},
-		},
-	})
-	if err != nil {
-		logs.Println("MqttServer", "订阅消息 [cli.Subscribe]", "")
-		logs.Println("err!!!!!! Run_MqttServer:", "连接MQTT失败:", err)
-	}
-
-	fmt.Println("MQTT ok!")
-
-	go MQTT_Gin_Run() // 初始化 MQTT ACL
-
-}
-
-func MQTT_Gin_Run() {
-
-	// 创建一个Gin路由器
-	r := gin.Default()
-
-	// 定义路由
-	r.POST("/authentication", func(c *gin.Context) {
-		var json struct {
-			Clientid string `json:"clientid"`
-			Username string `json:"username"`
-			Password string `json:"password"`
-		}
-		if err := c.Bind(&json); err != nil {
-			c.JSON(200, gin.H{
-				"result":       "deny", //  认证结果 可选 "allow" | "deny" | "ignore"
-				"is_superuser": false,  // 超级用户 可选 true | false,该项为空时默认为 false
-			})
-			return
-		}
-		// 保证 Clientid唯一,否则会 下线
-		if json.Clientid != json.Username {
-			c.JSON(200, gin.H{
-				"result":       "deny", //  认证结果 可选 "allow" | "deny" | "ignore"
-				"is_superuser": false,  // 超级用户 可选 true | false,该项为空时默认为 false
-			})
-			return
-		}
-		Device_r := Device.Device{
-			T_sn: json.Username,
-		}
-		// 判断是否存在
-		if !Device_r.Read_Tidy() {
-			c.JSON(200, gin.H{
-				"result":       "deny", //  认证结果 可选 "allow" | "deny" | "ignore"
-				"is_superuser": false,  // 超级用户 可选 true | false,该项为空时默认为 false
-			})
-			return
-		}
-		// 判断密码是否正确
-		if Device_r.T_password != json.Password {
-			c.JSON(200, gin.H{
-				"result":       "deny", //  认证结果 可选 "allow" | "deny" | "ignore"
-				"is_superuser": false,  // 超级用户 可选 true | false,该项为空时默认为 false
-			})
-			return
-		}
-
-		c.JSON(200, gin.H{
-			"result":       "allow", // 可选 "allow" | "deny" | "ignore"
-			"is_superuser": false,   // 可选 true | false,该项为空时默认为 false
-		})
-	})
-	r.POST("/Acl", func(c *gin.Context) {
-		logs.Println("Acl!!")
-		var json struct {
-			Clientid   string `json:"clientid"`   //${clientid} — 客户端的 ID。
-			Username   string `json:"username"`   //${username} — 客户端登录是用的用户名。
-			Peerhost   string `json:"peerhost"`   //${peerhost} — 客户端的源 IP 地址。
-			Proto_name string `json:"proto_name"` //${proto_name} — 客户端使用的协议名称。例如 MQTT,CoAP 等。
-			Mountpoint string `json:"mountpoint"` //${mountpoint} — 网关监听器的挂载点(主题前缀)。
-			Action     string `json:"action"`     //${action} — 当前执行的动作请求,例如 publish,subscribe。
-			Topic      string `json:"topic"`      //${topic} — 当前请求想要发布或订阅的主题(或主题过滤器)
-		}
-		if err := c.Bind(&json); err != nil {
-			c.JSON(200, gin.H{
-				"result": "deny", // 可选 "allow" | "deny" | "ignore"
-			})
-		}
-		fmt.Println("json:", json)
-
-		if json.Username == "admin" {
-			c.JSON(200, gin.H{"result": "allow"})
-			return
-		}
-
-		if json.Username == "test" {
-			c.JSON(200, gin.H{"result": "allow"})
-			return
-		}
-
-		// 保证 Clientid唯一,否则会 下线
-		if json.Clientid != json.Username {
-			c.JSON(200, gin.H{"result": "deny"})
-			return
-		}
-		Device_r := Device.Device{
-			T_sn: json.Username,
-		}
-		// 判断是否存在
-		if !Device_r.Read_Tidy() {
-			c.JSON(200, gin.H{"result": "deny"})
-			return
-		}
-
-		//topic  /sub/SN  /pub/SN
-		topic_list := strings.Split(json.Topic, "/")
-		for _, v := range topic_list {
-			if len(v) < 7 {
-				continue // 不是有效SN
-			}
-			if v == Device_r.T_sn {
-				c.JSON(200, gin.H{"result": "allow"})
-				return
-			}
-		}
-
-		logs.Println("MQTT Acl E!topic_list:", topic_list)
-
-		c.JSON(200, gin.H{"result": "deny"})
-		return
-
-		//
-		//Clientid_list := strings.Split(username+"_s", "_")
-		//username = Clientid_list[0]
-		//if topic_list[2] != username {
-		//	fmt.Println("topic_list[2] != username",topic_list[2])
-		//	c.JSON(200, gin.H{"result": "deny"})
-		//	return
-		//}
-
-		//c.JSON(200, gin.H{"result": "allow"})
-		//return
-	})
-	r.Run(":8080")
-}
-
-// 开始处理
-func messagePubHandler(topicName string, message []byte) {
-
-	// 本地测试
-	logs.Println("", "============= Mqtt JSON =============")
-	logs.Println("<-"+topicName, string(message))
-
-	// 过滤
-	topicNameS := strings.Split(topicName, "/")
-	if len(topicNameS) == 1 {
-		logs.Println("MqttServer", "订阅地址错误 len(topicNameS) == 1", strconv.Itoa(len(topicNameS)))
-		return
-	}
-	// 验证设备
-	Device_r := Device.Device{}
-	for _, sn := range topicNameS {
-		if len(sn) < 7 {
-			continue // 不是有效SN
-		}
-		Device_r.T_sn = sn
-		if Device_r.Read_Tidy() {
-			if Device_r.T_state == 3 {
-				continue // 不是有效SN
-			}
-			break
-		}
-	}
-
-	if Device_r.T_state != 1 {
-		logs.Println("MqttServer", Device_r.T_sn+" 设备被 禁用、删除、无效")
-		return
-	}
-
-	Rt_r := Handle.PullHandle(&Device_r, topicName, message)
-
-	// 返回
-	data, _ := json.Marshal(Rt_r)
-	Handle.PushHandle(&Device_r, topicName, string(data))
-
-}
-
-//
-//// 发送数据
-//func Mqtt_publish(topic string, b []byte) {
-//	lib.TopicMap[topic] = true
-//	// Publish a message.
-//	err := lib.MqttClient.Publish(&client.PublishOptions{
-//		QoS:       mqtt.QoS0,
-//		TopicName: []byte(topic),
-//		Message:   b,
-//	})
-//
-//	logs.PrintlnMqtt("-> " + topic + ":" + string(b))
-//	if err != nil {
-//		logs.PrintlnError("MqttServer", "发送消息失败 [Mqtt_publish]", "-> "+topic+" "+string(b))
-//	}
-//
-//}

+ 0 - 23
Handle/MqttServer/配置.md

@@ -1,23 +0,0 @@
-###客户端认证:
-####URL: 
-    http://192.168.11.112:8080/authentication
-####请求体:
-    {
-    "clientid": "${clientid}",
-    "password": "${password}",
-    "username": "${username}"
-    }
-
-
-###客户端授权:
-####URL:
-    http://192.168.11.112:8080/Acl
-####请求体:
-    {
-    "action": "${action}",
-    "clientid": "${clientid}",
-    "mountpoint": "${mountpoint}",
-    "peerhost": "${peerhost}",
-    "topic": "${topic}",
-    "username": "${username}"
-    }

+ 1 - 1
Handle/Relay.go

@@ -75,7 +75,7 @@ func Relay(Device_r *Device.Device, JointTab string, ArticleSlide *bson.M) {
 				break
 			case 2: //  MQTT
 				logs.Println("Relay -> MQTT:", T_pub, string(jsonData))
-				lib.Mqtt_publish(T_pub, jsonData)
+				//lib.Mqtt_publish(T_pub, jsonData)
 				break
 			}
 		}

+ 0 - 166
Handle/TcpServer/Server.go

@@ -1,166 +0,0 @@
-package TcpServer
-
-import (
-	"Yunlot/Handle"
-	"Yunlot/conf"
-	"Yunlot/lib"
-	"Yunlot/lib/TcpServerLib"
-	"Yunlot/logs"
-	"Yunlot/models/Device"
-	"container/list"
-	"encoding/json"
-	"fmt"
-	"net"
-	"strconv"
-	"strings"
-	"time"
-)
-
-var SessionS list.List
-
-func TcpServer() {
-	//SessionS = list.New()
-
-	logs.Println("============TcpServer==============")
-	logs.Println("TCPServer_Port:" + fmt.Sprintf(":%d", conf.TCPServer_Port))
-
-	server := TcpServerLib.NewServer(fmt.Sprintf(":%d", conf.TCPServer_Port))
-
-	server.OnNewClient(OnNewClient)
-	server.OnClientConnectionClosed(OnClientConnectionClosed)
-	server.OnNewMessage(OnNewMessage)
-
-	go server.Listen()
-	go Polling()
-}
-
-func Polling() {
-
-	for true {
-		for i := SessionS.Front(); i != nil; i = i.Next() {
-			t := i.Value.(*TcpServerLib.Session)
-
-			if len(t.Device_Sn) == 0 {
-				t.Verify_num += 1
-				if t.Verify_num > 10 {
-					t.Close()
-					SessionS.Remove(i)
-					logs.Println("Polling 删除", t.Conn().LocalAddr().String())
-				}
-			}
-		}
-		time.Sleep(time.Second * 1)
-	}
-
-}
-
-func OnNewClient(c *TcpServerLib.Session) {
-	logs.Println("OnNewClient")
-	SessionS.PushBack(c)
-	//c.Send(string([]byte{0xff,0x00,0xff}))
-	//c.Send("ok")
-}
-
-func OnClientConnectionClosed(c *TcpServerLib.Session, closeCase int) {
-	logs.Println("OnClientConnectionClosed:", closeCase)
-	// 离线
-	if len(c.Device_Sn) != 0 {
-		if _, is := lib.TcpMap[c.Device_Sn]; !is {
-			delete(lib.TcpMap, c.Device_Sn)
-		}
-
-		r_Device := Device.Device{T_sn: c.Device_Sn}
-		if !r_Device.Read_Tidy() {
-			return
-		}
-
-		r_Device.T_online = 2
-		// 同步参数
-		r_Device.Update("T_online")
-
-		var Device_online_r map[string]interface{}
-		Device_online_r = make(map[string]interface{})
-		Device_online_r["online"] = r_Device.T_online
-		Device_online_r["msg"] = "设备离线[" + ToReason(closeCase) + "]"
-		Device_online_r["time"] = time.Now().Format("2006-01-02 15:04:05")
-
-		Handle.AnalysisMap(&r_Device, map[string]interface{}{"online": Device_online_r}, "")
-
-	}
-
-}
-func ToReason(str int) (Reason string) {
-	switch str {
-	case 1:
-		Reason = "客户端主动断开"
-		break
-	default:
-		Reason = "客户端异常断开[" + strconv.Itoa(str) + "]"
-		break
-	}
-
-	return Reason
-}
-
-func OnNewMessage(c *TcpServerLib.Session, packetData []byte) {
-	if len(c.Device_Sn) == 0 {
-
-		packetData_l := strings.Split(string(packetData), "&")
-		if len(packetData_l) != 2 {
-			logs.Println("登录验证 长度失败:", packetData_l, len(packetData_l))
-			c.Send("e")
-			return
-		}
-		Devicer := Device.Device{T_sn: packetData_l[0]}
-		if !Devicer.Read_Tidy() {
-			logs.Println("登录验证 SN失败:", packetData_l, len(packetData_l))
-			c.Send("e")
-			return
-		}
-		if Devicer.T_password != packetData_l[1] {
-			logs.Println("登录验证 秘钥失败:", packetData_l, len(packetData_l))
-			c.Send("e")
-			return
-		}
-
-		c.Send("ok")
-		c.Device_Sn = Devicer.T_sn
-
-		lib.TcpMap[Devicer.T_sn] = c // 更新 MAP
-
-		//  更新状态
-
-		Devicer.T_online = 1
-		// 同步参数
-		Devicer.Update("T_online")
-
-		// 获取客户端IP地址
-		clientIP, _, _ := net.SplitHostPort(c.Conn().RemoteAddr().String())
-		fmt.Println("Client IP:", clientIP)
-
-		var Device_online_r map[string]interface{}
-		Device_online_r = make(map[string]interface{})
-		Device_online_r["online"] = Devicer.T_online
-		Device_online_r["msg"] = "设备主动上线[" + clientIP + "]"
-		Device_online_r["time"] = time.Now().Format("2006-01-02 15:04:05")
-
-		Handle.AnalysisMap(&Devicer, map[string]interface{}{"online": Device_online_r}, "")
-		return
-	}
-
-	Device_r := Device.Device{T_sn: c.Device_Sn}
-	if !Device_r.Read_Tidy() {
-		c.Send("e")
-		return
-	}
-
-	logs.Println("OnNewMessage:", string(packetData))
-
-	Rt_r := Handle.PullHandle(&Device_r, c.Device_Sn, packetData)
-
-	// 返回
-	data, _ := json.Marshal(Rt_r)
-
-	Handle.PushHandle(&Device_r, c.Device_Sn, string(data))
-
-}

+ 0 - 30
Nats/Nats.go

@@ -1,30 +0,0 @@
-package Nats
-
-import (
-	"Yunlot/Nats/NatsServer"
-	"Yunlot/conf"
-	"Yunlot/lib"
-	"Yunlot/logs"
-	"github.com/nats-io/nats.go"
-	"time"
-)
-
-func init() {
-	go NatsInit()
-}
-
-func NatsInit() {
-	time.Sleep(time.Second * 3)
-	var err error
-	// 连接Nats服务器
-	lib.Nats, err = nats.Connect("nats://" + conf.NatsServer_Url)
-	if err != nil {
-		logs.Println("nats 连接失败!")
-		panic(any(err))
-	}
-	logs.Println("nats OK!")
-
-	go NatsServer.NatsServer_Device()
-	go NatsServer.NatsServer_Product()
-
-}

+ 61 - 0
Nats/NatsServer.go

@@ -0,0 +1,61 @@
+package Nats
+
+import (
+	"Yunlot/Nats/NatsServer"
+	"Yunlot/lib"
+	"Yunlot/logs"
+	"github.com/nats-io/nats-server/v2/server"
+	"github.com/nats-io/nats.go"
+	"time"
+)
+
+var YunlotNats *nats.Conn
+
+// 内部 Nats 通讯
+func Nats_Server_init() {
+	opts := &server.Options{
+		ServerName: "Yunlot-nats-server",
+		Port:       6503,
+	}
+
+	// Initialize new server with options
+	ns, err := server.NewServer(opts)
+
+	if err != nil {
+		panic(any(err))
+	}
+
+	// Start the server via goroutine
+	go ns.Start()
+
+	// Wait for server to be ready for connections
+	if !ns.ReadyForConnections(4 * time.Second) {
+		panic(any("not ready for connection"))
+	}
+	logs.Println("Nats_Server OK!")
+
+	// 连接Nats服务器
+	lib.Nats, err = nats.Connect("nats://127.0.0.1:6503", nats.MaxReconnects(10), nats.ReconnectWait(10*time.Second),
+		nats.DisconnectErrHandler(func(nc *nats.Conn, err error) {
+			// handle disconnect error event
+			logs.PrintlnError("natsS.DisconnectErrHandler 断开 ", err)
+		}),
+		nats.ReconnectHandler(func(nc *nats.Conn) {
+			// handle reconnect event
+			logs.PrintlnError("natsS.ReconnectHandler, 已经重新连接 ")
+		}))
+	if err != nil {
+		logs.Println("natsS 连接失败!")
+		panic(any("natsS 连接失败!" + "nats://127.0.0.1:6503"))
+	}
+
+	if err != nil {
+		logs.Println("nats 连接失败!")
+		panic(any(err))
+	}
+	logs.Println("nats OK!")
+
+	go NatsServer.NatsServer_Device()
+	go NatsServer.NatsServer_Product()
+
+}

+ 32 - 13
Nats/NatsServer/Device.go

@@ -1,6 +1,7 @@
 package NatsServer
 
 import (
+	"Yunlot/Handle"
 	"Yunlot/lib"
 	"Yunlot/logs"
 	"Yunlot/models/Device"
@@ -35,18 +36,19 @@ func NatsServer_Device() {
 	_, _ = lib.Nats.Subscribe("/Device/Device/List", func(m *nats.Msg) {
 		logs.Println("Nats /Device/Device/List: %s\n", string(m.Data))
 
-		var Device_r Device.Device
-		err := msgpack.Unmarshal(m.Data, &Device_r)
+		var Device_Form_r Device.Device_Form
+		err := msgpack.Unmarshal(m.Data, &Device_Form_r)
 		if err != nil {
 			logs.PrintlnError("Nats:", err)
-			b, _ := msgpack.Marshal(&lib.JSONR{Code: lib.Error, Msg: "解析错误!"})
+			b, _ := msgpack.Marshal(&lib.JSONS{})
 			_ = lib.Nats.Publish(m.Reply, b)
 			return
 		}
+		Device_r := Device.Device{T_ProductID: Device_Form_r.T_ProductID, T_sn: Device_Form_r.T_sn, T_online: Device_Form_r.T_online}
 
-		Device_list := Device_r.Lists_All()
+		Device_list, Total := Device_r.Lists(Device_Form_r.PageIndex, Device_Form_r.PageSize)
 
-		b, _ := msgpack.Marshal(&lib.JSONR{Code: lib.Success, Msg: "ok!", Data: Device_list})
+		b, _ := msgpack.Marshal(lib.C_Page(Device_list, Device_Form_r.PageIndex, Device_Form_r.PageSize, Total))
 		_ = lib.Nats.Publish(m.Reply, b)
 	})
 
@@ -57,27 +59,44 @@ func NatsServer_Device() {
 		var DeviceData_Form Device.DeviceData_Form
 		err := msgpack.Unmarshal(m.Data, &DeviceData_Form)
 		if err != nil {
-			logs.PrintlnError("Nats:", err)
-			b, _ := msgpack.Marshal(&lib.JSONR{Code: lib.Error, Msg: "解析错误!"})
+			b, _ := msgpack.Marshal(&lib.JSONS{})
 			_ = lib.Nats.Publish(m.Reply, b)
 			return
 		}
-		if len(DeviceData_Form.T_sn) < 1 {
+
+		JSONR_r := Device.Data_List(DeviceData_Form.T_sn+"_"+DeviceData_Form.T_jointTab, DeviceData_Form.T_jsonFind, DeviceData_Form.T_jsonSort, DeviceData_Form.PageIndex, DeviceData_Form.PageSize)
+		b, _ := msgpack.Marshal(JSONR_r)
+		_ = lib.Nats.Publish(m.Reply, b)
+	})
+	// 请求-响应
+	_, _ = lib.Nats.Subscribe("/Device/Device/Push", func(m *nats.Msg) {
+		logs.Println("Nats /Device/Device/Push: %s\n", string(m.Data))
+
+		var Device_r Device.Device
+		err := msgpack.Unmarshal(m.Data, &Device_r)
+		if err != nil {
 			logs.PrintlnError("Nats:", err)
 			b, _ := msgpack.Marshal(&lib.JSONR{Code: lib.Error, Msg: "解析错误!"})
 			_ = lib.Nats.Publish(m.Reply, b)
 			return
 		}
 
-		if len(DeviceData_Form.T_jointTab) < 1 {
-			logs.PrintlnError("Nats:", err)
-			b, _ := msgpack.Marshal(&lib.JSONR{Code: lib.Error, Msg: "解析错误!"})
+		if len(Device_r.T_data) == 0 {
+			b, _ := msgpack.Marshal(&lib.JSONR{Code: lib.Error, Msg: "T_data E!"})
+			_ = lib.Nats.Publish(m.Reply, b)
+			return
+		}
+		Device_r_ := Device.Device{T_sn: Device_r.T_sn}
+		if !Device_r_.Read_Tidy() {
+			b, _ := msgpack.Marshal(&lib.JSONR{Code: lib.Error, Msg: "SN E!"})
 			_ = lib.Nats.Publish(m.Reply, b)
 			return
 		}
 
-		JSONR_r := Device.Data_List(DeviceData_Form.T_sn+"_"+DeviceData_Form.T_jointTab, DeviceData_Form.T_jsonFind, DeviceData_Form.T_jsonSort, DeviceData_Form.PageIndex, DeviceData_Form.PageSize)
-		b, _ := msgpack.Marshal(&lib.JSONR{Code: lib.Success, Msg: "ok!", Data: JSONR_r})
+		Handle.PushHandle(&Device_r_, Device_r.T_sn, Device_r.T_data)
+
+		b, _ := msgpack.Marshal(&lib.JSONR{Code: lib.Success, Msg: "ok!"})
 		_ = lib.Nats.Publish(m.Reply, b)
 	})
+
 }

+ 5 - 5
Nats/NatsServer/Product.go

@@ -40,14 +40,14 @@ func NatsServer_Product() {
 		err := msgpack.Unmarshal(m.Data, &ProductType_r)
 		if err != nil {
 			logs.PrintlnError("Nats:", err)
-			b, _ := msgpack.Marshal(&lib.JSONR{Code: lib.Error, Msg: "解析错误!"})
+			b, _ := msgpack.Marshal([]Product.ProductType{})
 			_ = lib.Nats.Publish(m.Reply, b)
 			return
 		}
 
 		ProductType_list := ProductType_r.Lists_All()
 
-		b, _ := msgpack.Marshal(&lib.JSONR{Code: lib.Success, Msg: "ok!", Data: ProductType_list})
+		b, _ := msgpack.Marshal(ProductType_list)
 		_ = lib.Nats.Publish(m.Reply, b)
 	})
 
@@ -57,7 +57,7 @@ func NatsServer_Product() {
 
 		ProductModeLists_list, _ := Product.ProductModeLists()
 
-		b, _ := msgpack.Marshal(&lib.JSONR{Code: lib.Success, Msg: "ok!", Data: ProductModeLists_list})
+		b, _ := msgpack.Marshal(ProductModeLists_list)
 		_ = lib.Nats.Publish(m.Reply, b)
 	})
 
@@ -92,14 +92,14 @@ func NatsServer_Product() {
 		err := msgpack.Unmarshal(m.Data, &ProductProt)
 		if err != nil {
 			logs.PrintlnError("Nats:", err)
-			b, _ := msgpack.Marshal(&lib.JSONR{Code: lib.Error, Msg: "解析错误!"})
+			b, _ := msgpack.Marshal([]Product.ProductProt{})
 			_ = lib.Nats.Publish(m.Reply, b)
 			return
 		}
 
 		ProductProt_list := ProductProt.Lists_All()
 
-		b, _ := msgpack.Marshal(&lib.JSONR{Code: lib.Success, Msg: "ok!", Data: ProductProt_list})
+		b, _ := msgpack.Marshal(ProductProt_list)
 		_ = lib.Nats.Publish(m.Reply, b)
 	})
 

+ 70 - 0
Plugin/Mode/Demo.go

@@ -0,0 +1,70 @@
+package main
+
+// 协议基础信息
+var ProductMode = map[string]string{
+	"Id":         "0",                          // 此行不能乱改,需要联系管理员 分配ID
+	"T_name":     "http",                       // 协议名称
+	"T_connect":  "bj-3-mqtt.iot-api.com:1883", // 连接地址
+	"T_describe": "描述内容",                       // 协议描述
+	"T_state":    "0",                          // 连接状态  0停用  1启用
+}
+
+// 参数配置模版
+var ProductModeConfig = map[string]map[string]string{
+	"port": {
+		"T_name":     "端口号",     // 名称  用于参数显示与数据获取标识
+		"T_describe": "填写连接端口号", // 描述
+		"T_value":    "1883",    // 默认值
+	},
+}
+
+// 设备上下线状态推送  T_State:(0 验证  1 在线  2 离线  )  T_Reason:备注内容
+var FunStateHandle func(T_sn, T_password string, T_State int, T_Reason string) error
+
+// 设备->平台
+var FunPullHandle func(T_sn, T_password, T_topic string, T_data []byte) error
+
+// 平台->设备
+func FunPushHandle(T_topic string, T_data []byte) error {
+
+	return nil
+}
+
+// 初始化服务
+func GoInit(FunPluginStateHandle func(T_sn, T_password string, T_State int, T_Reason string) error, FunPluginPullHandle func(T_sn, T_password, T_topic string, T_data []byte) error) {
+	FunStateHandle = FunPluginStateHandle // 设备上下线状态推送  方法指针
+	FunPullHandle = FunPluginPullHandle   // 设备->平台  方法指针
+}
+
+// 开启服务
+func GoRun(TConfig_map map[string]string) (map[string]string, error) {
+	println(ProductMode["T_name"])
+	// TConfig_map["port"]    // 获取配置参数
+
+	ProductMode["T_state"] = "1"
+	return ProductMode, nil
+}
+
+// 通知服务
+func GoStop() (map[string]string, error) {
+	// 关闭服务
+	println(ProductMode["T_name"], " 关闭服务!!")
+
+	ProductMode["T_state"] = "0"
+	return ProductMode, nil
+}
+
+//打包 SO 文件时,一定要注释 main主函数
+//func main() {
+//
+//
+//	GoRun(map[string]string{
+//		"port":"8080",
+//	})
+//
+//	//GoStop()
+//
+//	// 等待信号或其他事件来退出程序
+//	select {}
+//}
+//

+ 4 - 0
Plugin/Mode/plugin.sh

@@ -0,0 +1,4 @@
+
+go env -w GOPROXY="https://goproxy.cn,direct"
+go mod tidy
+go build -buildmode=plugin -o MQTT.so main.go

+ 300 - 0
Plugin/Plugin.go

@@ -0,0 +1,300 @@
+package Plugin
+
+import (
+	"Yunlot/Handle"
+	"Yunlot/lib"
+	"Yunlot/logs"
+	"Yunlot/models/Device"
+	"Yunlot/models/Product"
+	"errors"
+	"fmt"
+	"io/ioutil"
+	"os"
+	"plugin"
+
+	"strings"
+	"time"
+)
+
+func init() {
+
+}
+
+// 设备状态  T_State:(0 验证  1 在线  2 离线  )  T_Reason:备注内容
+func PluginStateHandle(T_sn, T_password string, T_State int, T_Reason string) error {
+
+	Device_r := Device.Device{T_sn: T_sn}
+	if !Device_r.Read_Tidy() {
+		return errors.New("T_sn 错误!")
+	}
+
+	if Device_r.T_password != T_password {
+		return errors.New("T_password 错误!")
+	}
+
+	if T_State != 1 && T_State != 2 {
+		return nil
+	}
+
+	Device_r.T_online = T_State
+	// 同步参数
+	Device_r.Update("T_online")
+
+	var Device_online_r map[string]interface{}
+	Device_online_r = make(map[string]interface{})
+	Device_online_r["online"] = Device_r.T_online
+	Device_online_r["msg"] = T_Reason
+	Device_online_r["time"] = time.Now().Format("2006-01-02 15:04:05")
+
+	Handle.AnalysisMap(&Device_r, map[string]interface{}{"online": Device_online_r}, "")
+
+	// 转换
+	return nil
+
+}
+
+// 设备->平台  T_topic:订阅号   T_data:数据       返回:200 成功  201 失败,描述
+func PluginPullHandle(T_sn, T_password, T_topic string, T_data []byte) error {
+
+	Device_r := Device.Device{T_sn: T_sn}
+	if !Device_r.Read_Tidy() {
+		return errors.New("T_sn 错误!")
+	}
+
+	if Device_r.T_password != T_password {
+		return errors.New("T_password 错误!")
+	}
+	if len(T_data) == 0 {
+		return errors.New("T_data 错误!")
+	}
+
+	// 转换
+	return Handle.PullHandle(&Device_r, T_topic, T_data)
+
+}
+
+// 平台->设备  T_topic:订阅号   T_data:数据
+func PluginPushHandle(ProductModeId int, T_topic string, T_data []byte) error {
+	v, is := Product.ProductModeMap[ProductModeId]
+	if !is {
+		return errors.New("ProductModeId E!")
+	}
+
+	//查找标识符
+	lookup, err := v.T_Plugin.Lookup("PushHandle")
+	if err != nil {
+		return errors.New("ProductModeId PushHandle E!")
+	}
+
+	// 推送
+	return lookup.(func(T_topic string, T_data []byte) error)(T_topic, T_data)
+
+}
+
+// 修改配置信息与启停服务
+func PluginProductModeConfigPu(ProductModeMap_v *Product.ProductMode) error {
+
+	Product.ProductModeMap[ProductModeMap_v.Id] = ProductModeMap_v // 更新参数
+
+	// 导出配置map到文件
+	filePath_json := strings.Replace(strings.Replace(ProductModeMap_v.T_file, ".SO", ".json", -1), ".so", ".json", -1)
+	lib.MapToFile(ProductModeMap_v.T_Config_map, filePath_json)
+
+	return nil
+}
+
+// 开启服务
+func PluginGoRun(ProductModeMap_v *Product.ProductMode) error {
+	logs.Println("PluginGoRun:", ProductModeMap_v.Id)
+	ProductModeMap_v.T_log = "--Stop--"
+	//查找标识符
+	GoRun_r, err := ProductModeMap_v.T_Plugin.Lookup("GoRun")
+	if err != nil {
+		logs.PrintlnError("", err)
+		ProductModeMap_v.T_log += err.Error()
+		Product.ProductModeMap[ProductModeMap_v.Id] = ProductModeMap_v // 更新参数
+		return errors.New("GoRun E!")
+	}
+
+	// 转换配置文件
+	var TConfig_map map[string]string
+	TConfig_map = make(map[string]string)
+	for k, v := range ProductModeMap_v.T_Config_map {
+		TConfig_map[k] = v["T_value"]
+	}
+
+	// 运行插件
+	ProductModeMap, err := GoRun_r.(func(TConfig_map map[string]string) (map[string]string, error))(TConfig_map)
+	if err != nil {
+		ProductModeMap_v.T_log += err.Error()
+		Product.ProductModeMap[ProductModeMap_v.Id] = ProductModeMap_v // 更新参数
+		return errors.New("GoRun E!")
+	}
+
+	if v, is := ProductModeMap["T_state"]; is {
+		ProductModeMap_v.T_state = lib.To_int(v)
+	}
+
+	Product.ProductModeMap[ProductModeMap_v.Id] = ProductModeMap_v // 更新参数
+
+	return nil
+}
+
+// 关闭服务
+func PluginGoStop(ProductModeMap_v *Product.ProductMode) error {
+	logs.Println("PluginGoStop:", ProductModeMap_v.Id)
+	//  关闭服务
+	ProductModeMap_v.T_log = "--Stop--"
+	//查找标识符
+	GoStop_r, err := ProductModeMap_v.T_Plugin.Lookup("GoStop")
+	if err != nil {
+		ProductModeMap_v.T_log += err.Error()
+		Product.ProductModeMap[ProductModeMap_v.Id] = ProductModeMap_v // 更新参数
+		return errors.New("GoStop E!")
+	}
+
+	// 转换配置文件
+	var TConfig_map map[string]string
+	TConfig_map = make(map[string]string)
+	for k, v := range ProductModeMap_v.T_Config_map {
+		TConfig_map[k] = v["T_value"]
+	}
+
+	// 运行插件
+	ProductModeMap, err := GoStop_r.(func() (map[string]string, error))()
+	if err != nil {
+		ProductModeMap_v.T_log += err.Error()
+		logs.PrintlnError("", err)
+	}
+
+	if v, is := ProductModeMap["T_state"]; is {
+		ProductModeMap_v.T_state = lib.To_int(v)
+	}
+
+	Product.ProductModeMap[ProductModeMap_v.Id] = ProductModeMap_v // 更新参数
+
+	return nil
+}
+
+// 插件初始化
+func Plugininit(open *plugin.Plugin, file_r string) {
+	// 协议基础信息
+	ProductMode, err := open.Lookup("ProductMode")
+	if err != nil {
+		logs.PrintlnError("ProductMode", err)
+		return
+	}
+	ProductModeMap := *ProductMode.(*map[string]string)
+
+	// 参数配置模版
+	ProductModeConfig, err := open.Lookup("ProductModeConfig")
+	if err != nil {
+		logs.PrintlnError("ProductModeConfig", err)
+		return
+	}
+	ProductModeConfigMap := *ProductModeConfig.(*map[string]map[string]string)
+
+	// 参数配置 保存文件
+	filePath_json := strings.Replace(strings.Replace(file_r, ".SO", ".json", -1), ".so", ".json", -1)
+	// 从文件中导入map数据
+	for k, v := range lib.MapFromFile(filePath_json) {
+		logs.Println("加载配置:", k, v)
+		ProductModeConfigMap[k] = v
+	}
+
+	// 获取旧的
+	Id_v, is := ProductModeMap["Id"]
+	if !is {
+		return
+	}
+
+	Id_int := lib.To_int(Id_v)
+
+	t, is := Product.ProductModeMap[Id_int]
+	if !is {
+		t = &Product.ProductMode{}
+	}
+
+	if v, is := ProductModeMap["T_name"]; is {
+		t.T_name = lib.To_string(v)
+	}
+	if v, is := ProductModeMap["T_connect"]; is {
+		t.T_connect = lib.To_string(v)
+	}
+	if v, is := ProductModeMap["T_describe"]; is {
+		t.T_describe = lib.To_string(v)
+	}
+
+	t.Id = Id_int
+	t.T_file = file_r
+	t.T_Plugin = open
+	t.T_Config_map = ProductModeConfigMap
+
+	//初始化插件
+	GoInit_r, err := open.Lookup("GoInit")
+	if err != nil {
+		logs.PrintlnError("", err)
+		return
+	}
+	// 初始化插件
+	GoInit_r.(func(FunPluginStateHandle func(T_sn, T_password string, T_State int, T_Reason string) error, FunPluginPullHandle func(T_sn, T_password, T_topic string, T_data []byte) error))(PluginStateHandle, PluginPullHandle)
+	if err != nil {
+		logs.PrintlnError("", err)
+	}
+	fmt.Println("Id_int:", Id_int)
+	Product.ProductModeMap[Id_int] = t // 更新参数
+
+	PluginGoRun(t) // 开启服务
+
+	// 导出配置map到文件
+	lib.MapToFile(ProductModeConfigMap, filePath_json)
+
+}
+
+func PluginInit() {
+	time.Sleep(time.Second * 2)
+	dir, err := os.Getwd()
+	if err != nil {
+		logs.Println("PluginInit:", err)
+		return
+	}
+	logs.Println("dir:", dir)
+
+	logs.Println("---PluginInit Mode----")
+	files, err := ioutil.ReadDir(dir + "/Plugin/Mode")
+	if err == nil {
+		for _, file := range files {
+			if strings.HasSuffix(file.Name(), ".so") {
+				file_r := dir + "/Plugin/Mode/" + file.Name()
+				logs.Println("PluginInit Mode 导入:" + file_r)
+				//打开加载插件,参数是插件的存储位置,可以是相对路径
+				open, err := plugin.Open(file_r)
+				if err != nil {
+					logs.PrintlnError("插件加载失败!", err)
+					continue
+				}
+				println("---")
+				Plugininit(open, file_r) //  插件初始化
+
+			}
+		}
+	}
+
+	logs.Println("---PluginInit Resource----")
+	files, err = ioutil.ReadDir(dir + "/Plugin/Resource")
+	if err == nil {
+		for _, file := range files {
+			if strings.HasSuffix(file.Name(), ".so") {
+				logs.Println("PluginInit Resource 导入:" + file.Name())
+
+				//打开加载插件,参数是插件的存储位置,可以是相对路径
+				file_r := dir + "/Plugin/Mode/" + file.Name()
+				open, err := plugin.Open(file_r)
+				if err != nil {
+					panic(any(err))
+				}
+				Plugininit(open, file_r) //  插件初始化
+			}
+		}
+	}
+}

+ 9 - 4
conf/app.conf

@@ -1,13 +1,13 @@
 appname = Yunlot
 httpport = 6202
 runmode = dev
-
+autorender = false
 
 # 数据解析加载目录
 Analysis_Dir = "/var/lib/docker/volumes/yunlotso/_data/"
 
-# Nats
-NatsServer_Url = "127.0.0.1:4222"
+# Nats   内核服务 127.0.0.1:4222(推荐 使用外部服务)
+NatsServer_Url = "127.0.0.1:6503"
 
 
 # Mysql
@@ -48,7 +48,12 @@ HTTPServer_Open = 1
 HTTPServer_Port = 8081
 
 
-
+# 静态资源
+Qiniu_AccessKey = "-8ezB_d-8-eUFTMvhOGbGzgeQRPeKQnaQ3DBcUxo"
+Qiniu_SecretKey = "KFhkYxTAJ2ZPN3ZS3euTsfWk8-C92rKgkhAMkDRN"
+Qiniu_BUCKET = "bzdstandardoss"  #桶名称
+Qiniu_Dir = "UpFile" #上传保存路径
+Qiniu_Url = "http://xxx.com" #上传保存路径
 
 
 

+ 6 - 2
conf/config.go

@@ -60,5 +60,9 @@ var Analysis_Dir, _ = beego.AppConfig.String("Analysis_Dir")
 // Nats
 var NatsServer_Url, _ = beego.AppConfig.String("NatsServer_Url")
 
-var EWarningAdmin = []int{1} // 管理
-var Page_size = 10
+// Qiniu
+var Qiniu_AccessKey, _ = beego.AppConfig.String("Qiniu_AccessKey")
+var Qiniu_SecretKey, _ = beego.AppConfig.String("Qiniu_SecretKey")
+var Qiniu_BUCKET, _ = beego.AppConfig.String("Qiniu_BUCKET")
+var Qiniu_Dir, _ = beego.AppConfig.String("Qiniu_Dir")
+var Qiniu_Url, _ = beego.AppConfig.String("Qiniu_Url")

+ 2 - 2
controllers/Device.go

@@ -159,13 +159,13 @@ func (c *DeviceController) DataList() {
 	c.ParseForm(&DeviceData_Form)
 
 	if len(DeviceData_Form.T_sn) < 1 {
-		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_sn !"}
+		c.Data["json"] = lib.JSONS{Code: lib.Error, Msg: "T_sn !"}
 		c.ServeJSON()
 		return
 	}
 
 	if len(DeviceData_Form.T_jointTab) < 1 {
-		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_jointTab !"}
+		c.Data["json"] = lib.JSONS{Code: lib.Error, Msg: "T_jointTab !"}
 		c.ServeJSON()
 		return
 	}

+ 84 - 0
controllers/ProductMode.go

@@ -0,0 +1,84 @@
+package controllers
+
+import (
+	"Yunlot/Plugin"
+	"Yunlot/lib"
+	"Yunlot/logs"
+	"Yunlot/models/Product"
+	"encoding/json"
+	beego "github.com/beego/beego/v2/server/web"
+	"time"
+)
+
+type ProductModeController struct {
+	beego.Controller
+}
+
+func (c *ProductModeController) ProductModeLists() {
+
+	ProductProt_r, Total := Product.ProductModeLists()
+
+	c.Data["json"] = lib.JSONR{Code: lib.Success, Msg: "ok!", Data: lib.C_Page(ProductProt_r, 0, 0, Total)}
+	c.ServeJSON()
+	return
+}
+
+func (c *ProductModeController) Updata() {
+
+	Id, _ := c.GetInt("Id", 0)
+
+	if Id <= 0 {
+		// 添加设备
+		//ProductProt_r := Product.ProductMode{}
+		//c.ParseForm(&ProductProt_r)
+		//
+		//ProductProt_r.Id = 0
+		//ProductProt_r.Add()
+
+		c.Data["json"] = lib.JSONR{Code: lib.Success, Msg: "ok!", Data: ""}
+		c.ServeJSON()
+		return
+
+	}
+	ProductModeMap_r, is := Product.ProductModeMap[Id]
+	if !is {
+		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "Id E!"}
+		c.ServeJSON()
+		return
+	}
+
+	T_Config_map := c.GetString("T_Config_map")
+	if len(T_Config_map) > 0 {
+		logs.Println("修改配置参数:", T_Config_map)
+		var articleSlide map[string]map[string]string
+		err := json.Unmarshal([]byte(T_Config_map), &articleSlide)
+		if err != nil {
+			c.Data["json"] = lib.JSONS{Code: lib.Error, Msg: "Data err!"}
+			c.ServeJSON()
+			return
+		}
+		ProductModeMap_r.T_Config_map = articleSlide
+		Plugin.PluginProductModeConfigPu(ProductModeMap_r)
+
+		if ProductModeMap_r.T_state == 1 {
+			Plugin.PluginGoStop(ProductModeMap_r)
+			time.Sleep(time.Second * 2)
+			Plugin.PluginGoRun(ProductModeMap_r)
+		}
+	}
+
+	T_state, err := c.GetInt("T_state")
+	if err == nil {
+		logs.Println("T_state:", T_state)
+		if T_state == 1 {
+			time.Sleep(time.Second * 1)
+			Plugin.PluginGoRun(ProductModeMap_r)
+		} else {
+			Plugin.PluginGoStop(ProductModeMap_r)
+		}
+	}
+
+	c.Data["json"] = lib.JSONR{Code: lib.Success, Msg: "ok!"}
+	c.ServeJSON()
+	return
+}

+ 8 - 8
controllers/ProductOTA.go

@@ -23,8 +23,8 @@ func (c *ProductOTAController) List() {
 
 	// 验证 TOKEY
 	if c.Ctx.Input.Host() != "127.0.0.1" {
-		if len(ProductOTAr.T_tokey) != 8 {
-			c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_tokey!"}
+		if len(ProductOTAr.T_uuid) != 8 {
+			c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_uuid!"}
 			c.ServeJSON()
 			return
 		}
@@ -48,8 +48,8 @@ func (c *ProductOTAController) Get() {
 	}
 
 	// 验证 TOKEY
-	if ProductOTAr.T_tokey != c.GetString("T_tokey") {
-		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_tokey!"}
+	if ProductOTAr.T_uuid != c.GetString("T_uuid") {
+		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_uuid!"}
 		c.ServeJSON()
 		return
 	}
@@ -63,8 +63,8 @@ func (c *ProductOTAController) Add() {
 	ProductOTA_r := Product.ProductOTA{}
 	c.ParseForm(&ProductOTA_r)
 
-	if len(ProductOTA_r.T_tokey) != 8 {
-		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_tokey!"}
+	if len(ProductOTA_r.T_uuid) != 8 {
+		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_uuid!"}
 		c.ServeJSON()
 		return
 	}
@@ -110,8 +110,8 @@ func (c *ProductOTAController) Delete() {
 	}
 
 	// 验证 TOKEY
-	if ProductOTAr.T_tokey != c.GetString("T_tokey") {
-		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_tokey!"}
+	if ProductOTAr.T_uuid != c.GetString("T_uuid") {
+		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_uuid!"}
 		c.ServeJSON()
 		return
 	}

+ 159 - 13
controllers/ProductProt.go

@@ -1,18 +1,26 @@
 package controllers
 
 import (
+	"Yunlot/conf"
 	"Yunlot/lib"
+	"Yunlot/logs"
 	"Yunlot/models/Product"
+	"archive/zip"
+	"encoding/json"
+	"strings"
+
 	beego "github.com/beego/beego/v2/server/web"
+	"io"
+	"os"
 )
 
 type ProductProtController struct {
 	beego.Controller
 }
 
-func (c *ProductProtController) ProductModeLists() {
+func (c *ProductProtController) ProductLangList() {
 
-	ProductProt_r, Total := Product.ProductModeLists()
+	ProductProt_r, Total := Product.ProductLangLists()
 
 	c.Data["json"] = lib.JSONR{Code: lib.Success, Msg: "ok!", Data: lib.C_Page(ProductProt_r, 0, 0, Total)}
 	c.ServeJSON()
@@ -29,8 +37,8 @@ func (c *ProductProtController) Get() {
 	}
 
 	// 验证 TOKEY
-	if ProductProt.T_tokey != c.GetString("T_tokey") {
-		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_tokey!"}
+	if ProductProt.T_uuid != c.GetString("T_uuid") {
+		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_uuid!"}
 		c.ServeJSON()
 		return
 	}
@@ -49,8 +57,8 @@ func (c *ProductProtController) List() {
 
 	// 验证 TOKEY
 	if c.Ctx.Input.Host() != "127.0.0.1" {
-		if len(ProductProtr.T_tokey) != 8 {
-			c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_tokey!"}
+		if len(ProductProtr.T_uuid) != 8 {
+			c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_uuid!"}
 			c.ServeJSON()
 			return
 		}
@@ -63,17 +71,132 @@ func (c *ProductProtController) List() {
 	return
 }
 
-func (c *ProductProtController) Add() {
+func (c *ProductProtController) Import() {
+	// 验证 TOKEY
+	if len(c.GetString("T_uuid")) == 0 {
+		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_uuid!"}
+		c.ServeJSON()
+		return
+	}
+
 	ProductProt_r := Product.ProductProt{}
 	c.ParseForm(&ProductProt_r)
 
-	if len(ProductProt_r.T_tokey) != 8 {
-		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_tokey!"}
+	if len(ProductProt_r.T_uuid) != 8 {
+		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_uuid!"}
+		c.ServeJSON()
+		return
+	}
+
+	// 获取上传的zip文件
+	zipFile, _, err := c.GetFile("sozip")
+	if err != nil {
+		logs.Println("Error getting zip file:", err)
+		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "sozip!"}
+		c.ServeJSON()
+		return
+	}
+	defer zipFile.Close()
+
+	// 创建一个临时文件来保存上传的zip文件
+	tempFile, err := os.Create("temp.zip")
+	if err != nil {
+		logs.Println("Error creating temp file:", err)
+		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "sozip!"}
+		c.ServeJSON()
+		return
+	}
+	defer tempFile.Close()
+
+	// 将上传的zip文件内容复制到临时文件中
+	_, err = io.Copy(tempFile, zipFile)
+	if err != nil {
+		logs.Println("Error copying zip file to temp file:", err)
+		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "Copy!"}
 		c.ServeJSON()
 		return
 	}
 
+	// 打开临时文件
+	zipReader, err := zip.OpenReader("temp.zip")
+	if err != nil {
+		logs.Println("Error opening temp file:", err)
+		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "OpenReader!"}
+		c.ServeJSON()
+		return
+	}
+	defer zipReader.Close()
+
+	// 解压文件
+	for _, file := range zipReader.File {
+		logs.Println("file.Name:", file.Name)
+
+		if file.Name == "ProductProt.json" {
+			// 打开文件
+			rc, err := file.Open()
+			if err != nil {
+				c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "file.Open!"}
+				c.ServeJSON()
+				return
+			}
+
+			defer rc.Close()
+			var contents strings.Builder
+			_, err = io.Copy(&contents, rc)
+			if err != nil {
+				c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "file.Open!"}
+				c.ServeJSON()
+				return
+			}
+			logs.Println("contents:", contents.String())
+
+			// 处理JSON文件
+			err = json.Unmarshal([]byte(contents.String()), &ProductProt_r)
+
+			// 处理jsonData,例如打印到控制台
+			logs.Println("jsonData:", ProductProt_r)
+		} else {
+			// 检查文件是否存在
+			if _, err := os.Stat(conf.Analysis_Dir + file.Name); os.IsNotExist(err) {
+				// 打开zip文件中的文件
+				zippedFile, err := file.Open()
+				if err != nil {
+					logs.Println("Error opening zipped file:", err)
+					c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "opening zipped file!"}
+					c.ServeJSON()
+					return
+				}
+				defer zippedFile.Close()
+
+				// 创建一个新文件来保存解压后的文件
+				newFile, err := os.Create(conf.Analysis_Dir + file.Name)
+				if err != nil {
+					logs.Println("Error creating new file:", err)
+					c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "Error creating new file!"}
+					c.ServeJSON()
+					return
+				}
+				defer newFile.Close()
+
+				// 将解压后的文件内容复制到新文件中
+				_, err = io.Copy(newFile, zippedFile)
+				if err != nil {
+					logs.Println("Error copying zipped file to new file:", err)
+					c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "io.Copy!"}
+					c.ServeJSON()
+					return
+				}
+			} else {
+				logs.Println("文件已经存在:", conf.Analysis_Dir+file.Name)
+
+			}
+
+		}
+
+	}
+
 	ProductProt_r.Id = 0
+	ProductProt_r.T_uuid = c.GetString("T_uuid")
 	ProductProt_r.Add()
 
 	c.Data["json"] = lib.JSONR{Code: lib.Success, Msg: "ok!", Data: ProductProt_r}
@@ -84,6 +207,27 @@ func (c *ProductProtController) Add() {
 func (c *ProductProtController) Update() {
 
 	Id, _ := c.GetInt("Id", 0)
+	// 验证 TOKEY
+	if len(c.GetString("T_uuid")) != 8 {
+		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_uuid!"}
+		c.ServeJSON()
+		return
+	}
+
+	if Id <= 0 {
+		// 添加设备
+		ProductProt_r := Product.ProductProt{}
+		c.ParseForm(&ProductProt_r)
+
+		ProductProt_r.Id = 0
+		ProductProt_r.Add()
+
+		c.Data["json"] = lib.JSONR{Code: lib.Success, Msg: "ok!", Data: ProductProt_r}
+		c.ServeJSON()
+		return
+
+	}
+
 	ProductProtr := Product.ProductProt{Id: Id}
 	if !ProductProtr.Read() {
 		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_ProductID E!"}
@@ -92,8 +236,8 @@ func (c *ProductProtController) Update() {
 	}
 
 	// 验证 TOKEY
-	if ProductProtr.T_tokey != c.GetString("T_tokey") {
-		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_tokey!"}
+	if ProductProtr.T_uuid != c.GetString("T_uuid") {
+		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_uuid!"}
 		c.ServeJSON()
 		return
 	}
@@ -106,6 +250,8 @@ func (c *ProductProtController) Update() {
 		return
 	}
 
+	lib.DownloadSo(ProductProtr.T_analysis) // 下载SO 文件
+
 	c.Data["json"] = lib.JSONR{Code: lib.Success, Msg: "ok!"}
 	c.ServeJSON()
 	return
@@ -121,8 +267,8 @@ func (c *ProductProtController) Delete() {
 	}
 
 	// 验证 TOKEY
-	if ProductProtr.T_tokey != c.GetString("T_tokey") {
-		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_tokey!"}
+	if ProductProtr.T_uuid != c.GetString("T_uuid") {
+		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_uuid!"}
 		c.ServeJSON()
 		return
 	}

+ 49 - 21
controllers/ProductType.go

@@ -21,8 +21,8 @@ func (c *ProductTypeController) List() {
 
 	// 验证 TOKEY
 	if c.Ctx.Input.Host() != "127.0.0.1" {
-		if len(ProductTyper.T_tokey) != 8 {
-			c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_tokey!"}
+		if len(ProductTyper.T_uuid) != 8 {
+			c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_uuid!"}
 			c.ServeJSON()
 			return
 		}
@@ -46,8 +46,8 @@ func (c *ProductTypeController) Get() {
 	}
 
 	// 验证 TOKEY
-	if ProductTyper.T_tokey != c.GetString("T_tokey") {
-		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_tokey!"}
+	if ProductTyper.T_uuid != c.GetString("T_uuid") {
+		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_uuid!"}
 		c.ServeJSON()
 		return
 	}
@@ -57,27 +57,55 @@ func (c *ProductTypeController) Get() {
 	return
 }
 
-func (c *ProductTypeController) Add() {
-	ProductType_r := Product.ProductType{}
-	c.ParseForm(&ProductType_r)
+//func (c *ProductTypeController) Add() {
+//	ProductType_r := Product.ProductType{}
+//	c.ParseForm(&ProductType_r)
+//
+//	if len(ProductType_r.T_uuid) != 8 {
+//		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_uuid!"}
+//		c.ServeJSON()
+//		return
+//	}
+//
+//	ProductType_r.T_ProductID = lib.GetRandstring(8, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0)
+//	ProductType_r.T_akey = lib.GetRandstring(32, "", 0)
+//
+//	ProductType_r.Add()
+//
+//	c.Data["json"] = lib.JSONR{Code: lib.Success, Msg: "ok!", Data: ProductType_r}
+//	c.ServeJSON()
+//	return
+//}
 
-	if len(ProductType_r.T_tokey) != 8 {
-		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_tokey!"}
+func (c *ProductTypeController) Update() {
+
+	T_ProductID := c.GetString("T_ProductID")
+	// 验证 TOKEY
+	if len(c.GetString("T_uuid")) == 0 {
+		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_uuid!"}
 		c.ServeJSON()
 		return
 	}
 
-	ProductType_r.T_ProductID = lib.GetRandstring(8, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0)
-	ProductType_r.T_akey = lib.GetRandstring(32, "", 0)
+	if len(T_ProductID) == 0 {
+		ProductType_r := Product.ProductType{}
+		c.ParseForm(&ProductType_r)
 
-	ProductType_r.Add()
+		if len(ProductType_r.T_uuid) != 8 {
+			c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_uuid!"}
+			c.ServeJSON()
+			return
+		}
 
-	c.Data["json"] = lib.JSONR{Code: lib.Success, Msg: "ok!", Data: ProductType_r}
-	c.ServeJSON()
-	return
-}
+		ProductType_r.T_ProductID = lib.GetRandstring(8, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0)
+		ProductType_r.T_akey = lib.GetRandstring(32, "", 0)
 
-func (c *ProductTypeController) Update() {
+		ProductType_r.Add()
+
+		c.Data["json"] = lib.JSONR{Code: lib.Success, Msg: "ok!", Data: ProductType_r}
+		c.ServeJSON()
+		return
+	}
 
 	ProductTyper := Product.ProductType{T_ProductID: c.GetString("T_ProductID")}
 	if !ProductTyper.Read() {
@@ -87,8 +115,8 @@ func (c *ProductTypeController) Update() {
 	}
 
 	// 验证 TOKEY
-	if ProductTyper.T_tokey != c.GetString("T_tokey") {
-		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_tokey!"}
+	if ProductTyper.T_uuid != c.GetString("T_uuid") {
+		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_uuid!"}
 		c.ServeJSON()
 		return
 	}
@@ -118,8 +146,8 @@ func (c *ProductTypeController) Delete() {
 	}
 
 	// 验证 TOKEY
-	if ProductTyper.T_tokey != c.GetString("T_tokey") {
-		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_tokey!"}
+	if ProductTyper.T_uuid != c.GetString("T_uuid") {
+		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "T_uuid!"}
 		c.ServeJSON()
 		return
 	}

+ 25 - 0
controllers/UpFile.go

@@ -0,0 +1,25 @@
+package controllers
+
+import (
+	"Yunlot/lib"
+	beego "github.com/beego/beego/v2/server/web"
+)
+
+type UpFileController struct {
+	beego.Controller
+}
+
+// 列表 -
+func (c *UpFileController) UpFileToken() {
+	// 验证登录 User_r, User_x
+	//b_, User_r, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
+	//if !b_ {
+	//	c.Data["json"] = lib.JSONS{Code: 302, Msg: "请重新登录!"}
+	//	c.ServeJSON()
+	//	return
+	//}
+
+	c.Data["json"] = lib.JSONR{Code: 200, Msg: "ok!", Data: lib.UploadToken(c.GetString("T_suffix"))}
+	c.ServeJSON()
+	return
+}

+ 7 - 28
go.mod

@@ -5,63 +5,42 @@ go 1.19
 require (
 	github.com/astaxie/beego v1.12.3
 	github.com/beego/beego/v2 v2.0.1
-	github.com/davecgh/go-spew v1.1.1
-	github.com/gin-gonic/gin v1.9.1
 	github.com/go-sql-driver/mysql v1.6.0
 	github.com/nats-io/nats.go v1.16.0
+	github.com/qiniu/go-sdk/v7 v7.18.2
 	github.com/satori/go.uuid v1.2.0
 	github.com/thinkeridea/go-extend v1.3.2
 	github.com/vmihailenco/msgpack/v5 v5.4.0
-	github.com/yosssi/gmq v0.0.1
 	go.mongodb.org/mongo-driver v1.12.0
+	gogs.baozhida.cn/bzdadmin/YunIot_SDK v0.0.0-20231124090009-5e9cbcff9641
 	golang.org/x/text v0.13.0
-)
-
-require github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
-
-require (
+	github.com/minio/highwayhash v1.0.2 // indirect
+	github.com/nats-io/jwt/v2 v2.2.1-0.20220330180145-442af02fd36a // indirect
+	github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
+	golang.org/x/time v0.0.0-20211116232009-f0f3c7e86c11 // indirect
 	github.com/beorn7/perks v1.0.1 // indirect
-	github.com/bytedance/sonic v1.10.0 // indirect
 	github.com/cespare/xxhash/v2 v2.1.1 // indirect
-	github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect
-	github.com/chenzhuoyu/iasm v0.9.0 // indirect
-	github.com/gabriel-vasile/mimetype v1.4.2 // indirect
-	github.com/gin-contrib/sse v0.1.0 // indirect
-	github.com/go-playground/locales v0.14.1 // indirect
-	github.com/go-playground/universal-translator v0.18.1 // indirect
-	github.com/go-playground/validator/v10 v10.15.3 // indirect
-	github.com/goccy/go-json v0.10.2 // indirect
 	github.com/golang/protobuf v1.5.0 // indirect
 	github.com/golang/snappy v0.0.1 // indirect
 	github.com/gomodule/redigo v2.0.0+incompatible // indirect
 	github.com/hashicorp/golang-lru v0.5.4 // indirect
-	github.com/json-iterator/go v1.1.12 // indirect
 	github.com/klauspost/compress v1.14.4 // indirect
-	github.com/klauspost/cpuid/v2 v2.2.5 // indirect
-	github.com/leodido/go-urn v1.2.4 // indirect
-	github.com/mattn/go-isatty v0.0.19 // indirect
 	github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
 	github.com/mitchellh/mapstructure v1.3.3 // indirect
-	github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
-	github.com/modern-go/reflect2 v1.0.2 // indirect
 	github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe // indirect
-	github.com/nats-io/nats-server/v2 v2.8.4 // indirect
+	github.com/nats-io/nats-server/v2 v2.8.4
 	github.com/nats-io/nkeys v0.3.0 // indirect
 	github.com/nats-io/nuid v1.0.1 // indirect
-	github.com/pelletier/go-toml/v2 v2.1.0 // indirect
 	github.com/pkg/errors v0.9.1 // indirect
 	github.com/prometheus/client_golang v1.7.0 // indirect
 	github.com/prometheus/client_model v0.2.0 // indirect
 	github.com/prometheus/common v0.10.0 // indirect
 	github.com/prometheus/procfs v0.1.3 // indirect; indirectS
 	github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 // indirect
-	github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
-	github.com/ugorji/go/codec v1.2.11 // indirect
 	github.com/xdg-go/pbkdf2 v1.0.0 // indirect
 	github.com/xdg-go/scram v1.1.2 // indirect
 	github.com/xdg-go/stringprep v1.0.4 // indirect
 	github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
-	golang.org/x/arch v0.5.0 // indirect
 	golang.org/x/crypto v0.13.0 // indirect
 	golang.org/x/mod v0.8.0 // indirect
 	golang.org/x/net v0.15.0 // indirect

+ 38 - 3
go.sum

@@ -41,6 +41,7 @@ github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfc
 github.com/couchbase/go-couchbase v0.0.0-20200519150804-63f3cdb75e0d/go.mod h1:TWI8EKQMs5u5jLKW/tsb9VwauIrMIxQG1r5fMsswK5U=
 github.com/couchbase/gomemcached v0.0.0-20200526233749-ec430f949808/go.mod h1:srVSlQLB8iXBVXHgnqemxUXqN6FCvClgCMPCsjBDR7c=
 github.com/couchbase/goutils v0.0.0-20180530154633-e865a1461c8a/go.mod h1:BQwMFlJzDjFDG3DJUdU0KORxn88UlsOULuxLExMh3Hs=
+github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
 github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGiisLwp9rITslkFNpZD5rz43tf41QFkTWY=
 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
 github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
@@ -63,11 +64,17 @@ github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2
 github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
 github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
 github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
+github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
 github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
+github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8=
+github.com/go-playground/locales v0.14.0/go.mod h1:sawfccIbzZTqEDETgFXqTho0QybSa7l++s0DH+LDiLs=
 github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
 github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
+github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
+github.com/go-playground/universal-translator v0.18.0/go.mod h1:UvRDBj+xPUEGrFYl+lu/H90nyDXpg0fqeB/AQUGNTVA=
 github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
 github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
+github.com/go-playground/validator/v10 v10.8.0/go.mod h1:9JhgTzTaE31GZDpH/HSvHiRJrJ3iKAgqqH0Bl/Ocjdk=
 github.com/go-playground/validator/v10 v10.15.3 h1:S+sSpunYjNPDuXkWbK+x+bA7iXiW296KG4dL3X7xUZo=
 github.com/go-playground/validator/v10 v10.15.3/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
 github.com/go-redis/redis v6.14.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA=
@@ -131,10 +138,15 @@ github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgSh
 github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
 github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
 github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
+github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
+github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
+github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
 github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
-github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
 github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
 github.com/ledisdb/ledisdb v0.0.0-20200510135210-d35789ec47e6/go.mod h1:n931TsDuKuq+uX4v1fulaMbA/7ZLLhjc85h7chZGBCQ=
+github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY=
 github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
 github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
 github.com/lib/pq v1.0.0 h1:X5PMW56eZitiTeO7tKzZxFCSpbFZJtkMMooicw2us9A=
@@ -146,6 +158,7 @@ github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW
 github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU=
 github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
 github.com/minio/highwayhash v1.0.2 h1:Aak5U0nElisjDCfPSG79Tgzkn2gl66NxOMspRrKnA/g=
+github.com/minio/highwayhash v1.0.2/go.mod h1:BQskDq+xkJ12lmlUUi7U0M5Swg3EWR+dLTk+kldvVxY=
 github.com/mitchellh/mapstructure v1.3.3 h1:SzB1nHZ2Xi+17FP0zVQBHIZqvwRN9408fJO8h+eeNA8=
 github.com/mitchellh/mapstructure v1.3.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
 github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
@@ -159,6 +172,7 @@ github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe h1:iruDEfMl2E6f
 github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=
 github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
 github.com/nats-io/jwt/v2 v2.2.1-0.20220330180145-442af02fd36a h1:lem6QCvxR0Y28gth9P+wV2K/zYUUAkJ+55U8cpS0p5I=
+github.com/nats-io/jwt/v2 v2.2.1-0.20220330180145-442af02fd36a/go.mod h1:0tqz9Hlu6bCBFLWAASKhE5vUA4c24L9KPUUgvwumE/k=
 github.com/nats-io/nats-server/v2 v2.8.4 h1:0jQzze1T9mECg8YZEl8+WYUXb9JKluJfCBriPUtluB4=
 github.com/nats-io/nats-server/v2 v2.8.4/go.mod h1:8zZa+Al3WsESfmgSs98Fi06dRWLH5Bnq90m5bKD/eT4=
 github.com/nats-io/nats.go v1.16.0 h1:zvLE7fGBQYW6MWaFaRdsgm9qT39PJDQoju+DS8KsO1g=
@@ -167,7 +181,6 @@ github.com/nats-io/nkeys v0.3.0 h1:cgM5tL53EvYRU+2YLXIK0G2mJtK12Ft9oeooSZMA2G8=
 github.com/nats-io/nkeys v0.3.0/go.mod h1:gvUNGjVcM2IPr5rCsRsC6Wb3Hr2CQAm08dsxtV6A5y4=
 github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
 github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
-github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
 github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
 github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
 github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
@@ -181,6 +194,7 @@ github.com/pelletier/go-toml v1.8.1/go.mod h1:T2/BmBdy8dvIRq1a/8aqjN41wvWlN4lrap
 github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4=
 github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=
 github.com/peterh/liner v1.0.1-0.20171122030339-3681c2a91233/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc=
+github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
 github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
 github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
 github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
@@ -203,7 +217,14 @@ github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R
 github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
 github.com/prometheus/procfs v0.1.3 h1:F0+tqvhOksq22sc6iCHF5WGlWjdwj92p0udFh1VFBS8=
 github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU=
+github.com/qiniu/dyn v1.3.0/go.mod h1:E8oERcm8TtwJiZvkQPbcAh0RL8jO1G0VXJMW3FAWdkk=
+github.com/qiniu/go-sdk/v7 v7.18.2 h1:vk9eo5OO7aqgAOPF0Ytik/gt7CMKuNgzC/IPkhda6rk=
+github.com/qiniu/go-sdk/v7 v7.18.2/go.mod h1:nqoYCNo53ZlGA521RvRethvxUDvXKt4gtYXOwye868w=
+github.com/qiniu/x v1.10.5/go.mod h1:03Ni9tj+N2h2aKnAz+6N0Xfl8FwMEDRC2PAlxekASDs=
 github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
+github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
+github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8=
+github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
 github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww=
 github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
 github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 h1:X+yvsM2yrEktyI+b2qND5gpH8YhURn0k8OCaeRnkINo=
@@ -221,6 +242,7 @@ github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpE
 github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
 github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
 github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
+github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
 github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
 github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
 github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
@@ -262,6 +284,8 @@ go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
 go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU=
 go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA=
 go.uber.org/zap v1.15.0/go.mod h1:Mb2vm2krFEG5DV0W9qcHBYFtp/Wku1cvYaqPsS/WYfc=
+gogs.baozhida.cn/bzdadmin/YunIot_SDK v0.0.0-20231124090009-5e9cbcff9641 h1:iCxW1s8Vne1rAmMd0CEnD6FJnBsDpiYJHWdqFnkhb3U=
+gogs.baozhida.cn/bzdadmin/YunIot_SDK v0.0.0-20231124090009-5e9cbcff9641/go.mod h1:fo7CpR6Wuck5EQyj6EBaVoh3Ht+JIE4QjaR6ii+IUcM=
 golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
 golang.org/x/arch v0.5.0 h1:jpGode6huXQxcskEIpOCvrU+tzo81b6+oFLUYXWtH/Y=
 golang.org/x/arch v0.5.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
@@ -271,8 +295,10 @@ golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8U
 golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
 golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
 golang.org/x/crypto v0.0.0-20210314154223-e6e6c4f2bb5b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
+golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
 golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
 golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
+golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw=
 golang.org/x/crypto v0.13.0 h1:mvySKfSWJ+UKUii46M40LOvyWfN0s2U+46/jDd0e6Ck=
 golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
 golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
@@ -301,6 +327,7 @@ golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwY
 golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
 golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
 golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
+golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco=
 golang.org/x/net v0.15.0 h1:ugBLEUaxABaB5AJqW9enI0ACdci2RUd4eP51NTBvuJ8=
 golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
 golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
@@ -317,6 +344,7 @@ golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5h
 golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
 golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
 golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20190130150945-aca44879d564/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
 golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
 golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
 golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -328,24 +356,29 @@ golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7w
 golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
 golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
 golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o=
 golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
 golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
+golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
 golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
 golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
 golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
 golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
 golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
 golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
+golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
 golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
 golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
 golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
 golang.org/x/time v0.0.0-20211116232009-f0f3c7e86c11 h1:GZokNIeuVkl3aZHJchRrr13WCsols02MLUcz1U9is6M=
+golang.org/x/time v0.0.0-20211116232009-f0f3c7e86c11/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
 golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
 golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
 golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
@@ -387,8 +420,9 @@ gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLks
 gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
 gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
 gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
-gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU=
 gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
 gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
 gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
 gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA=
@@ -400,6 +434,7 @@ gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
 gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
 gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
 gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
 gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
 gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
 honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=

+ 44 - 0
lib/DownloadSo.go

@@ -0,0 +1,44 @@
+package lib
+
+import (
+	"Yunlot/conf"
+	"fmt"
+	"io"
+	"net/http"
+	"os"
+)
+
+var url = "https://yunlot.baozhida.cn/API/RunCode/Download?T_describe="
+
+func DownloadSo(T_analysis string) {
+	//url := "http://example.com/file.txt"
+
+	// 检查文件是否存在
+	if _, err := os.Stat(conf.Analysis_Dir + T_analysis + ".so"); os.IsNotExist(err) {
+		fmt.Println("File does not exist.")
+	} else {
+		return
+	}
+
+	resp, err := http.Get(url + T_analysis)
+	if err != nil {
+		fmt.Println("Error downloading file:", err)
+		return
+	}
+	defer resp.Body.Close()
+
+	out, err := os.Create(conf.Analysis_Dir + T_analysis + ".so")
+	if err != nil {
+		fmt.Println("Error creating file:", err)
+		return
+	}
+	defer out.Close()
+
+	_, err = io.Copy(out, resp.Body)
+	if err != nil {
+		fmt.Println("Error downloading file:", err)
+		return
+	}
+
+	fmt.Println("File downloaded successfully.")
+}

+ 41 - 0
lib/Qiniu.go

@@ -0,0 +1,41 @@
+package lib
+
+// 存储相关功能的引入包只有这两个,后面不再赘述
+
+// 存储相关功能的引入包只有这两个,后面不再赘述
+import (
+	"Yunlot/conf"
+	"github.com/qiniu/go-sdk/v7/auth/qbox"
+	"github.com/qiniu/go-sdk/v7/storage"
+	uuid "github.com/satori/go.uuid"
+	"strconv"
+	"time"
+)
+
+var Qiniu *qbox.Mac
+
+func init() {
+	Qiniu = qbox.NewMac(conf.Qiniu_AccessKey, conf.Qiniu_SecretKey)
+}
+
+func UploadToken(T_suffix string) string {
+	Tokey := strconv.FormatInt(time.Now().Unix(), 10) + uuid.NewV4().String()
+	if len(T_suffix) == 0 {
+		T_suffix = ".png"
+	}
+	putPolicy := storage.PutPolicy{
+		Scope:      conf.Qiniu_BUCKET,
+		InsertOnly: 1,    // 仅能以新增模式上传文件。
+		Expires:    7200, //示例2小时有效期
+		ReturnBody: `{"key":"` + conf.Qiniu_Url + `/$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)"}`,
+		//{"key":"github-x.png","hash":"FqKXVdTvIx_mPjOYdjDyUSy_H1jr","fsize":6091,"bucket":"if-pbl","name":"github logo"}
+		//{"key":"` + conf.Oss + `/$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}
+		ForceSaveKey: true,
+		SaveKey:      conf.Qiniu_Dir + "/" + Tokey + "." + T_suffix,
+		FsizeLimit:   1024 * 1024 * 10, // 10M
+		//MimeLimit:    "image/*",
+	}
+
+	upToken := putPolicy.UploadToken(Qiniu)
+	return upToken
+}

+ 0 - 271
lib/TcpServerLib/binaryReadWrite.go

@@ -1,271 +0,0 @@
-package TcpServerLib
-
-import (
-	"encoding/binary"
-	"errors"
-)
-
-func packetTotalSize(data []byte) int16 {
-	totalsize := binary.LittleEndian.Uint16(data)
-	return int16(totalsize)
-}
-
-// 출처: https://github.com/gonet2/agent
-type RawPacketData struct {
-	pos   int
-	data  []byte
-	order binary.ByteOrder
-}
-
-func MakeReader(buffer []byte, isLittleEndian bool) RawPacketData {
-	if isLittleEndian {
-		return RawPacketData{data: buffer, order: binary.LittleEndian}
-	}
-	return RawPacketData{data: buffer, order: binary.BigEndian}
-}
-
-func MakeWriter(buffer []byte, isLittleEndian bool) RawPacketData {
-	if isLittleEndian {
-		return RawPacketData{data: buffer, order: binary.LittleEndian}
-	}
-	return RawPacketData{data: buffer, order: binary.BigEndian}
-}
-
-func (p *RawPacketData) Data() []byte {
-	return p.data
-}
-
-func (p *RawPacketData) Length() int {
-	return len(p.data)
-}
-
-// =============================================== Readers
-func (p *RawPacketData) ReadBool() (ret bool, err error) {
-	b, _err := p.ReadByte()
-
-	if b != byte(1) {
-		return false, _err
-	}
-
-	return true, _err
-}
-
-func (p *RawPacketData) ReadS8() (ret int8, err error) {
-	_ret, _err := p.ReadByte()
-	ret = int8(_ret)
-	err = _err
-	return
-}
-
-func (p *RawPacketData) ReadU16() (ret uint16, err error) {
-	if p.pos+2 > len(p.data) {
-		err = errors.New("read uint16 failed")
-		return
-	}
-	buf := p.data[p.pos : p.pos+2]
-	ret = p.order.Uint16(buf)
-	p.pos += 2
-	return
-}
-
-func (p *RawPacketData) ReadS16() (ret int16, err error) {
-	_ret, _err := p.ReadU16()
-	ret = int16(_ret)
-	err = _err
-	return
-}
-
-func (p *RawPacketData) ReadU32() (ret uint32, err error) {
-	if p.pos+4 > len(p.data) {
-		err = errors.New("read uint32 failed")
-		return
-	}
-
-	buf := p.data[p.pos : p.pos+4]
-	ret = p.order.Uint32(buf)
-	p.pos += 4
-	return
-}
-
-func (p *RawPacketData) ReadS32() (ret int32, err error) {
-	_ret, _err := p.ReadU32()
-	ret = int32(_ret)
-	err = _err
-	return
-}
-
-func (p *RawPacketData) ReadU64() (ret uint64, err error) {
-	if p.pos+8 > len(p.data) {
-		err = errors.New("read uint64 failed")
-		return
-	}
-
-	buf := p.data[p.pos : p.pos+8]
-	ret = p.order.Uint64(buf)
-	p.pos += 8
-	return
-}
-
-func (p *RawPacketData) ReadS64() (ret int64, err error) {
-	_ret, _err := p.ReadU64()
-	ret = int64(_ret)
-	err = _err
-	return
-}
-
-func (p *RawPacketData) ReadByte() (ret byte, err error) {
-	if p.pos >= len(p.data) {
-		err = errors.New("read byte failed")
-		return
-	}
-
-	ret = p.data[p.pos]
-	p.pos++
-	return
-}
-
-func (p *RawPacketData) ReadBytes(readSize int) (refSlice []byte) {
-	refSlice = p.data[p.pos : p.pos+readSize]
-	p.pos += readSize
-	return
-}
-
-func (p *RawPacketData) ReadString() (ret string, err error) {
-	if p.pos+2 > len(p.data) {
-		err = errors.New("read string header failed")
-		return
-	}
-
-	size, _ := p.ReadU16()
-	if p.pos+int(size) > len(p.data) {
-		err = errors.New("read string Data failed")
-		return
-	}
-
-	bytes := p.data[p.pos : p.pos+int(size)]
-	p.pos += int(size)
-	ret = string(bytes)
-	return
-}
-
-/*
-func (p *RawPacketData) ReadFloat32() (ret float32, err error) {
-	bits, _err := p.ReadU32()
-	if _err != nil {
-		return float32(0), _err
-	}
-
-	ret = math.Float32frombits(bits)
-	if math.IsNaN(float64(ret)) || math.IsInf(float64(ret), 0) {
-		return 0, nil
-	}
-
-	return ret, nil
-}
-
-func (p *RawPacketData) ReadFloat64() (ret float64, err error) {
-	bits, _err := p.ReadU64()
-	if _err != nil {
-		return float64(0), _err
-	}
-
-	ret = math.Float64frombits(bits)
-	if math.IsNaN(ret) || math.IsInf(ret, 0) {
-		return 0, nil
-	}
-
-	return ret, nil
-}
-*/
-
-// ================================================ Writers
-func (p *RawPacketData) WriteS8(v int8) {
-	p.data[p.pos] = (byte)(v)
-	p.pos++
-}
-
-func (p *RawPacketData) WriteU16(v uint16) {
-	p.order.PutUint16(p.data[p.pos:], v)
-	p.pos += 2
-}
-
-func (p *RawPacketData) WriteS16(v int16) {
-	p.WriteU16(uint16(v))
-}
-
-func (p *RawPacketData) WriteBytes(v []byte) {
-	copy(p.data[p.pos:], v)
-	p.pos += len(v)
-}
-
-func (p *RawPacketData) WriteU32(v uint32) {
-	p.order.PutUint32(p.data[p.pos:], v)
-	p.pos += 4
-}
-
-func (p *RawPacketData) WriteS32(v int32) {
-	p.WriteU32(uint32(v))
-}
-
-func (p *RawPacketData) WriteU64(v uint64) {
-	p.order.PutUint64(p.data[p.pos:], v)
-	p.pos += 8
-}
-
-func (p *RawPacketData) WriteS64(v int64) {
-	p.WriteU64(uint64(v))
-}
-
-func (p *RawPacketData) WriteString(v string) {
-	copyLen := copy(p.data[p.pos:], v)
-	p.pos += copyLen
-}
-
-/*
-func (p *RawPacketData) WriteZeros(n int) {
-	for i := 0; i < n; i++ {
-		p.Data = append(p.Data, byte(0))
-	}
-}
-
-func (p *RawPacketData) WriteBool(v bool) {
-	if v {
-		p.Data = append(p.Data, byte(1))
-	} else {
-		p.Data = append(p.Data, byte(0))
-	}
-}
-
-func (p *RawPacketData) WriteByte(v byte) {
-	p.Data = append(p.Data, v)
-}
-
-func (p *RawPacketData) WriteBytes(v []byte) {
-	p.WriteU16(uint16(len(v)))
-	p.Data = append(p.Data, v...)
-}
-
-func (p *RawPacketData) WriteRawBytes(v []byte) {
-	p.Data = append(p.Data, v...)
-}
-
-func (p *RawPacketData) WriteString(v string) {
-	bytes := []byte(v)
-	p.WriteU16(uint16(len(bytes)))
-	p.Data = append(p.Data, bytes...)
-}
-
-func (p *RawPacketData) WriteU24(v uint32) {
-	p.Data = append(p.Data, byte(v>>16), byte(v>>8), byte(v))
-}
-
-func (p *RawPacketData) WriteFloat32(f float32) {
-	v := math.Float32bits(f)
-	p.WriteU32(v)
-}
-
-func (p *RawPacketData) WriteFloat64(f float64) {
-	v := math.Float64bits(f)
-	p.WriteU64(v)
-}
-*/

+ 0 - 16
lib/TcpServerLib/define.go

@@ -1,16 +0,0 @@
-package TcpServerLib
-
-const (
-	MAX_RECEIVE_BUFFER_SIZE = 4012
-	HEADER_SIZE             = 4
-	MAX_PACKET_SIZE         = 1024
-)
-
-const (
-	NET_ERROR_NONE                                   = 0
-	NET_ERROR_RECV_MAKE_PACKET_TOO_LARGE_PACKET_SIZE = 1
-)
-const (
-	NET_CLOSE_REMOTE                   = 1
-	NET_CLOSE_RECV_TOO_SMALL_RECV_DATA = 2
-)

+ 0 - 73
lib/TcpServerLib/packet.go

@@ -1,73 +0,0 @@
-package TcpServerLib
-
-// protocol Id
-const (
-	Pkt_ID_Echo_Req = 101
-	Pkt_ID_Echo_Res = 102
-
-	Pkt_ID_LoginReq = 201
-	Pkt_ID_LoginRes = 202
-
-	Pkt_ID_NewRoomReq = 203
-	Pkt_ID_NewRoomRes = 204
-
-	Pkt_ID_EnterRoomReq = 206
-	Pkt_ID_EnterRoomRes = 207
-
-	Pkt_ID_LeaveRoomReq = 209
-	Pkt_ID_LeaveRoomRes = 210
-
-	Pkt_ID_ChatRoomReq = 214
-	Pkt_ID_ChatRoomRes = 215
-	Pkt_ID_ChatRoomNtf = 216
-)
-
-type PacketHeader struct {
-	TotalSize int16
-	Id        int16
-}
-
-func DecodingPacketHeader(header *PacketHeader, data []byte) {
-	reader := MakeReader(data, true)
-	header.TotalSize, _ = reader.ReadS16()
-	header.Id, _ = reader.ReadS16()
-}
-
-func EncodingPacketHeader(writer *RawPacketData, totalSize int16, pktId int16, packetType int8) {
-	writer.WriteS16(totalSize)
-	writer.WriteS16(pktId)
-}
-
-type RoomChatReqPacket struct {
-	MsgLength int16
-	Msgs      []byte
-}
-
-func (request RoomChatReqPacket) EncodingPacket(packetId int16) ([]byte, int16) {
-
-	totalSize := HEADER_SIZE + 2 + int16(request.MsgLength)
-	sendBuf := make([]byte, totalSize)
-	writer := MakeWriter(sendBuf, true)
-	EncodingPacketHeader(&writer, totalSize, packetId, 0)
-
-	writer.WriteS16(request.MsgLength)
-	writer.WriteBytes(request.Msgs)
-	return sendBuf, totalSize
-}
-
-func (request *RoomChatReqPacket) DecodingPacketPre(Data []byte) bool {
-	bodyLength := len(Data)
-	if bodyLength < 2 {
-		return false
-	}
-
-	reader := MakeReader(Data, true)
-	request.MsgLength, _ = reader.ReadS16()
-
-	if bodyLength != int((2 + request.MsgLength)) {
-		return false
-	}
-
-	request.Msgs = Data[2:]
-	return true
-}

+ 0 - 107
lib/TcpServerLib/session.go

@@ -1,107 +0,0 @@
-package TcpServerLib
-
-import (
-	"net"
-)
-
-// Session holds info about connection
-type Session struct {
-	conn       net.Conn
-	Server     *server
-	Device_Sn  string
-	Verify_num int
-}
-
-func (session *Session) handleTcpRead() {
-	session.Server.onNewClientCallback(session)
-
-	//var startRecvPos int16
-	//var result int
-	recviveBuff := make([]byte, MAX_RECEIVE_BUFFER_SIZE)
-
-	for {
-		recvBytes, err := session.conn.Read(recviveBuff)
-
-		if err != nil {
-			/*logs.PrintlnError("TCP - handleTcpRead",err)
-			continue;*/
-			//logs.PrintlnError("TCP - handleTcpRead",err)
-			session.closeProcess(NET_CLOSE_REMOTE)
-			return
-		}
-		//logs.Println("recvBytes:",recvBytes)
-		session.Server.onNewMessage(session, recviveBuff[:recvBytes])
-		//
-		//if recvBytes < HEADER_SIZE {
-		//	session.closeProcess(NET_CLOSE_RECV_TOO_SMALL_RECV_DATA)
-		//	return
-		//}
-		//
-		//readAbleByte := int16(startRecvPos) + int16(recvBytes)
-		//startRecvPos, result = session.makePacket(readAbleByte, recviveBuff)
-		//if result != NET_ERROR_NONE {
-		//	session.closeProcess(result)
-		//	return
-		//}
-
-	}
-}
-
-func (session *Session) closeProcess(reason int) {
-	session.conn.Close()
-	session.Server.onClientConnectionClosed(session, reason)
-}
-
-func (session *Session) makePacket(readAbleByte int16, recviveBuff []byte) (int16, int) {
-	var startRecvPos int16 = 0
-	var readPos int16
-
-	for {
-		if readAbleByte < HEADER_SIZE {
-			break
-		}
-
-		requireDataSize := packetTotalSize(recviveBuff[readPos:])
-
-		if requireDataSize > readAbleByte {
-			break
-		}
-
-		if requireDataSize > MAX_PACKET_SIZE {
-			return startRecvPos, NET_ERROR_RECV_MAKE_PACKET_TOO_LARGE_PACKET_SIZE
-		}
-
-		ltvPacket := recviveBuff[readPos:(readPos + requireDataSize)]
-		readPos += requireDataSize
-		readAbleByte -= requireDataSize
-
-		session.Server.onNewMessage(session, ltvPacket)
-	}
-
-	if readAbleByte > 0 {
-		copy(recviveBuff, recviveBuff[readPos:(readPos+readAbleByte)])
-	}
-
-	startRecvPos = readAbleByte
-	return startRecvPos, NET_ERROR_NONE
-}
-
-// Send text message to client
-func (session *Session) Send(message string) error {
-	_, err := session.conn.Write([]byte(message))
-	return err
-}
-
-// Send bytes to client
-func (session *Session) SendBytes(b []byte) error {
-	_, err := session.conn.Write(b)
-	return err
-}
-
-func (session *Session) Conn() net.Conn {
-	return session.conn
-}
-
-func (session *Session) Close() error {
-	return session.conn.Close()
-}

+ 0 - 85
lib/TcpServerLib/tcpServer.go

@@ -1,85 +0,0 @@
-package TcpServerLib
-
-import (
-	"github.com/davecgh/go-spew/spew"
-	"log"
-	"net"
-	"runtime"
-)
-
-// TCP server
-type server struct {
-	address                  string // Address to open connection: localhost:9999
-	onNewClientCallback      func(c *Session)
-	onClientConnectionClosed func(c *Session, closeCase int)
-	onNewMessage             func(c *Session, packetData []byte)
-}
-
-// Called right after server starts listening new client
-func (s *server) OnNewClient(callback func(c *Session)) {
-	s.onNewClientCallback = callback
-}
-
-// Called right after connection closed
-func (s *server) OnClientConnectionClosed(callback func(c *Session, closeCase int)) {
-	s.onClientConnectionClosed = callback
-}
-
-// Called when Session receives new message
-func (s *server) OnNewMessage(callback func(c *Session, packetData []byte)) {
-	s.onNewMessage = callback
-}
-
-// Creates new tcp server instance
-func NewServer(address string) *server {
-	log.Println("Creating server with address", address)
-	server := &server{
-		address: address,
-	}
-
-	server.OnNewClient(func(c *Session) {})
-	server.OnNewMessage(func(c *Session, packetData []byte) {})
-	server.OnClientConnectionClosed(func(c *Session, closeCase int) {})
-
-	return server
-}
-
-// Start network server
-func (s *server) Listen() {
-	listener, err := net.Listen("tcp", s.address)
-	if err != nil {
-		log.Fatal("Error starting TCP server.")
-	}
-	defer listener.Close()
-
-	for {
-		conn, _ := listener.Accept()
-		client := &Session{
-			conn:   conn,
-			Server: s,
-		}
-
-		go client.handleTcpRead()
-	}
-}
-
-// 출처: https://github.com/gonet2/agent
-func PrintPanicStack(extras ...interface{}) {
-	if x := recover(); x != any(nil) {
-		log.Printf("%v", x)
-
-		i := 0
-		funcName, file, line, ok := runtime.Caller(i)
-
-		for ok {
-			log.Printf("PrintPanicStack. [func]: %s, [file]: %s, [line]: %d\n", runtime.FuncForPC(funcName).Name(), file, line)
-
-			i++
-			funcName, file, line, ok = runtime.Caller(i)
-		}
-
-		for k := range extras {
-			log.Printf("EXRAS#%v DATA:%v\n", k, spew.Sdump(extras[k]))
-		}
-	}
-}

+ 29 - 41
lib/lib.go

@@ -1,8 +1,6 @@
 package lib
 
 import (
-	"Yunlot/lib/TcpServerLib"
-	"Yunlot/logs"
 	"bytes"
 	"crypto/sha256"
 	"encoding/hex"
@@ -10,13 +8,12 @@ import (
 	"fmt"
 	"github.com/nats-io/nats.go"
 	"github.com/thinkeridea/go-extend/exunicode/exutf8"
-	"github.com/yosssi/gmq/mqtt"
-	"github.com/yosssi/gmq/mqtt/client"
+
 	"golang.org/x/text/encoding/simplifiedchinese"
 	"golang.org/x/text/transform"
 	"io/ioutil"
 	"math/rand"
-	"plugin"
+
 	"reflect"
 	"runtime"
 	"strconv"
@@ -26,15 +23,9 @@ import (
 )
 
 var Nats *nats.Conn
-var MqttClient *client.Client
-var TopicMap map[string]bool
-var PluginMap map[string]*plugin.Plugin
-var TcpMap map[string]*TcpServerLib.Session
 
 func init() {
-	TopicMap = make(map[string]bool)
-	PluginMap = make(map[string]*plugin.Plugin)
-	TcpMap = make(map[string]*TcpServerLib.Session)
+
 }
 
 const Success = 200
@@ -48,6 +39,8 @@ type JSONR struct {
 }
 type JSONS struct {
 	//必须的大写开头
+	Code      int16
+	Msg       string
 	List      interface{}
 	Total     int16
 	PageIndex int
@@ -445,23 +438,6 @@ func WeekByDate() string {
 	return fmt.Sprintf("%d%02d", t.Year(), week) // 202253
 }
 
-// 发送数据
-func Mqtt_publish(topic string, b []byte) {
-	TopicMap[topic] = true
-	// Publish a message.
-	err := MqttClient.Publish(&client.PublishOptions{
-		QoS:       mqtt.QoS0,
-		TopicName: []byte(topic),
-		Message:   b,
-	})
-
-	logs.PrintlnMqtt("Mqtt-> " + topic + ":" + string(b))
-	if err != nil {
-		logs.PrintlnError("MqttServer", "发送消息失败 [Mqtt_publish]", "-> "+topic+" "+string(b))
-	}
-
-}
-
 // 获取json指定参数   [AAAA BBBB],0,JSON    !!!如果失败,返回已找到的全部json
 func Json_key(topicNameList []string, topicNameI int, articleSlide map[string]interface{}) interface{} {
 	if len(topicNameList) > topicNameI {
@@ -481,18 +457,30 @@ func Json_key(topicNameList []string, topicNameI int, articleSlide map[string]in
 	return articleSlide[topicNameList[topicNameI]]
 }
 
-// 发送数据
-func TCP_publish(T_sn string, byte_r []byte) {
-
-	logs.PrintlnMqtt("TCP-> " + T_sn + ":" + string(byte_r))
-
-	if v, is := TcpMap[T_sn]; is {
-		err := v.Send(string(byte_r))
-		if err != nil {
-			logs.PrintlnError("TCP", "发送消息失败 [TCP_publish]", "-> "+T_sn+" "+string(byte_r))
-		}
-	} else {
-		logs.PrintlnError("TCP", "TcpMap[T_sn] 不存在,发送消息失败 [TCP_publish]", "-> "+T_sn+" "+string(byte_r))
+// 导出map到文件
+func MapToFile(data map[string]map[string]string, filePath string) error {
+	jsonData, err := json.Marshal(data)
+	if err != nil {
+		return err
+	}
+	err = ioutil.WriteFile(filePath, jsonData, 0644)
+	if err != nil {
+		return err
 	}
+	return nil
+}
 
+// 从文件中导入map数据
+func MapFromFile(filePath string) map[string]map[string]string {
+	jsonData, err := ioutil.ReadFile(filePath)
+	if err != nil {
+		return nil
+	}
+	var importedMap map[string]map[string]string
+	err = json.Unmarshal(jsonData, &importedMap)
+	if err != nil {
+		fmt.Println("Error unmarshalling JSON:", err)
+		return nil
+	}
+	return importedMap
 }

+ 42 - 42
main.go

@@ -1,17 +1,14 @@
 package main
 
 import (
-	"Yunlot/Handle/HttpServer"
-	"Yunlot/Handle/MqttServer"
-	"Yunlot/Handle/TcpServer"
+	"Yunlot/Nats"
 	_ "Yunlot/Nats"
+	"Yunlot/Plugin"
 	"Yunlot/RunCode"
 	"Yunlot/TimeTask"
 	"Yunlot/conf"
 	"Yunlot/logs"
-	"Yunlot/models/Product"
 	_ "Yunlot/routers"
-	"fmt"
 	"github.com/beego/beego/v2/adapter/orm"
 	orm2 "github.com/beego/beego/v2/client/orm"
 	beego "github.com/beego/beego/v2/server/web"
@@ -37,6 +34,7 @@ func main() {
 	beego.BConfig.ServerName = conf.AppName + "_" + strconv.Itoa(conf.HTTPPort) //server  名称
 	beego.BConfig.RunMode = "dev"                                               //  应用的运行模式
 	beego.BConfig.Listen.HTTPPort = conf.HTTPPort                               //监听端口  本地:8518  线上:8528
+
 	orm2.Debug = true
 	logs.Println("MqttServer", " ======= 项目启动 ========")
 	//go MqttServer2.Run_MqttServer() // MQTT 通讯
@@ -44,46 +42,48 @@ func main() {
 	//go MqttServer.DeviceMqttMap_go() //// 缓存数据发送-确保设备在休眠后 能收到数据
 
 	// MQTT 通讯
-	if conf.MqttServer_Open == 1 {
-		mode := Product.ProductMode{
-			Id:         1,
-			T_name:     "MQTT",
-			T_address:  fmt.Sprintf("mqtt://%s", conf.MqttServer_Url),
-			T_describe: "MQTT 接入方式为设备和云平台提供双向连接,设备既可上报属性数据,也可接收云端的消息下发。",
-			T_state:    1,
-		}
-		mode.Add()
-		go MqttServer.Run_MqttServer()
-	}
-	// TCP 通讯
-	if conf.TCPServer_Open == 1 {
-		mode := Product.ProductMode{
-			Id:         2,
-			T_name:     "TCP",
-			T_address:  fmt.Sprintf("TCP:%d", conf.TCPServer_Port),
-			T_describe: "TCP 接入方式为设备和云平台提供双向连接,设备既可上报属性数据,也可接收云端的消息下发。",
-			T_state:    1,
-		}
-		mode.Add()
-		go TcpServer.TcpServer()
-	}
-	// HTTP 通讯
-	if conf.HTTPServer_Open == 1 {
-		mode := Product.ProductMode{
-			Id:         6,
-			T_name:     "HTTP",
-			T_address:  fmt.Sprintf("http://:%d", conf.HTTPServer_Port),
-			T_describe: "HTTP 接入方式为设备和云平台提供双向连接,设备既可上报属性数据,也可接收云端的消息下发。",
-			T_state:    1,
-		}
-		mode.Add()
-		go HttpServer.Run()
-	}
+	//if conf.MqttServer_Open == 1 {
+	//	mode := Product.ProductMode{
+	//		Id:         1,
+	//		T_name:     "MQTT",
+	//		T_address:  fmt.Sprintf("mqtt://%s", conf.MqttServer_Url),
+	//		T_describe: "MQTT 接入方式为设备和云平台提供双向连接,设备既可上报属性数据,也可接收云端的消息下发。",
+	//		T_state:    1,
+	//	}
+	//	Product.ProductModeAdd(mode)
+	//	go MqttServer.Run_MqttServer()
+	//}
+	//// TCP 通讯
+	//if conf.TCPServer_Open == 1 {
+	//	mode := Product.ProductMode{
+	//		Id:         2,
+	//		T_name:     "TCP",
+	//		T_address:  fmt.Sprintf("TCP:%d", conf.TCPServer_Port),
+	//		T_describe: "TCP 接入方式为设备和云平台提供双向连接,设备既可上报属性数据,也可接收云端的消息下发。",
+	//		T_state:    1,
+	//	}
+	//	Product.ProductModeAdd(mode)
+	//	go TcpServer.TcpServer()
+	//}
+	//// HTTP 通讯
+	//if conf.HTTPServer_Open == 1 {
+	//	mode := Product.ProductMode{
+	//		Id:         6,
+	//		T_name:     "HTTP",
+	//		T_address:  fmt.Sprintf("http://:%d", conf.HTTPServer_Port),
+	//		T_describe: "HTTP 接入方式为设备和云平台提供双向连接,设备既可上报属性数据,也可接收云端的消息下发。",
+	//		T_state:    1,
+	//	}
+	//	Product.ProductModeAdd(mode)
+	//	go HttpServer.Run()
+	//}
 
 	//go Nats.NatsInit() // Nats 通讯
 
-	go TimeTask.Init()        // 时间任务
-	go RunCode.RunCode_Inte() // 代码编译
+	go TimeTask.Init()         // 时间任务
+	go RunCode.RunCode_Inte()  // 代码编译
+	go Nats.Nats_Server_init() // 内部 Nats 通讯
+	go Plugin.PluginInit()     // Plugin 初始化
 
 	beego.Run()
 

+ 3 - 4
models/Device/Device.go

@@ -110,8 +110,6 @@ func (t *Device) Read() (is bool) {
 	if err != nil {
 		return false
 	}
-
-	t.Redis_Set()
 	return true
 }
 
@@ -123,11 +121,12 @@ func (t *Device) Read_Tidy() (bool bool) {
 	o := orm.NewOrm()
 	err := o.Read(t) // o.Read(&r,"Tokey") 如果不是 主键 就得指定字段名
 	if err != nil {
-		//t.T_state = 3 // 3 无效
-		//t.Redis_Set() // Redis 更新缓存
 		return false
 	}
 	t.Redis_Set() // Redis 更新缓存
+	if t.T_state == 2 {
+		return false
+	}
 	return true
 }
 

+ 19 - 21
models/Device/DeviceData.go

@@ -30,6 +30,15 @@ type DeviceData_R struct {
 }
 
 // 表单
+type Device_Form struct {
+	T_ProductID string `json:"T_ProductID" form:"T_ProductID"` // Sn
+	T_sn        string `json:"T_sn" form:"T_sn"`               // 标签路径
+	T_online    int    `json:"T_online" form:"T_online"`       // 当前页码
+	PageIndex   int    `json:"PageIndex" form:"PageIndex"`     // 当前页码
+	PageSize    int    `json:"PageSize" form:"PageSize"`       // 每页文档数量
+}
+
+// 表单
 type DeviceData_Form struct {
 	T_sn       string `json:"T_sn" form:"T_sn"`             // Sn
 	T_jointTab string `json:"T_jointTab" form:"T_jointTab"` // 标签路径
@@ -143,13 +152,13 @@ func Data_Read(JointTab string, bson_r *bson.M) {
 /*
 ----------------
 // 数据列表
-JointTab:2023445039284316_params_varData
+JointTab:2023445039284316_params.varData
 // 条件 jsonFind := `{"$or":[{"name":"TempSet"},{"value":"26"}]}`
 // 排序 jsonSort := `{"value": 1}`
 // 当前页码 page := 2
 // 每页文档数量 pageSize := 2
 */
-func Data_List(JointTab, jsonFind, jsonSort string, page, pageSize int) (JSONr lib.JSONR) {
+func Data_List(JointTab, jsonFind, jsonSort string, page, pageSize int) lib.JSONS {
 	var err error
 	// 初始化 Mongodb_DB
 	collection := Mongodb_DB.Collection(JointTab)
@@ -169,9 +178,7 @@ func Data_List(JointTab, jsonFind, jsonSort string, page, pageSize int) (JSONr l
 		err = json.Unmarshal([]byte(jsonSort), &jsonSortMap)
 		if err != nil {
 			logs.PrintlnError("解码JSON 错误", err)
-			JSONr.Code = lib.Error
-			JSONr.Msg = "排序 解码JSON 错误!"
-			return
+			return lib.JSONS{Code: lib.Error, Msg: "排序 解码JSON 错误!"}
 		}
 
 		options = options.SetSort(bson.M(jsonSortMap))
@@ -184,9 +191,7 @@ func Data_List(JointTab, jsonFind, jsonSort string, page, pageSize int) (JSONr l
 		err = json.Unmarshal([]byte(jsonFind), &jsonFindMap)
 		if err != nil {
 			logs.PrintlnError("解码JSON 错误", err)
-			JSONr.Code = lib.Error
-			JSONr.Msg = "条件 解码JSON 错误!"
-			return
+			return lib.JSONS{Code: lib.Error, Msg: "条件 解码JSON 错误!"}
 		}
 		jsonFind_M = jsonFindMap
 	}
@@ -194,36 +199,29 @@ func Data_List(JointTab, jsonFind, jsonSort string, page, pageSize int) (JSONr l
 	cursor, err := collection.Find(context.Background(), jsonFind_M, options)
 	if err != nil {
 		logs.PrintlnError("Find 错误", err)
-		JSONr.Code = lib.Error
-		JSONr.Msg = "Find 错误!"
-		return
+		return lib.JSONS{Code: lib.Error, Msg: "Find 错误!"}
 	}
 	defer cursor.Close(context.Background())
 
 	var results []bson.M
 	if err = cursor.All(context.Background(), &results); err != nil {
 		logs.PrintlnError("cursor.All 错误", err)
-		JSONr.Code = lib.Error
-		JSONr.Msg = "cursor.All 错误!"
-		return
+		return lib.JSONS{Code: lib.Error, Msg: "cursor.All 错误!"}
 	}
 
 	// 执行计数操作
 	count, err := collection.CountDocuments(context.Background(), jsonFind_M)
 	if err != nil {
 		logs.PrintlnError("Count 错误", err)
-		JSONr.Code = lib.Error
-		JSONr.Msg = "Count 错误!"
-		return
+		return lib.JSONS{Code: lib.Error, Msg: "Count 错误!"}
 	}
 
-	JSONr.Data = lib.JSONS{
+	return lib.JSONS{
+		Code:      lib.Success,
+		Msg:       "ok!",
 		List:      results,
 		Total:     int16(count),
 		PageIndex: page,
 		PageSize:  pageSize,
 	}
-	JSONr.Code = lib.Success
-	JSONr.Msg = "ok!"
-	return
 }

+ 46 - 0
models/Product/ProductLang.go

@@ -0,0 +1,46 @@
+package Product
+
+// 产品语言
+type ProductLang struct {
+	Id     int    `json:"Id"`
+	T_name string `json:"T_name"` // 协议语言
+}
+
+var ProductLangList = []ProductLang{}
+
+// ---------------- 方法 -------------------
+func init() {
+	ProductLangAdd(ProductLang{
+		Id:     0,
+		T_name: "无解析",
+	})
+	ProductLangAdd(ProductLang{
+		Id:     1,
+		T_name: "Goland",
+	})
+	//Add(ProductLang{
+	//	Id:     2,
+	//	T_name: "C",
+	//})
+	//Add(ProductLang{
+	//	Id:     3,
+	//	T_name: "Python",
+	//})
+	//Add(ProductLang{
+	//	Id:     4,
+	//	T_name: "JavaScript",
+	//})
+
+}
+
+// 添加
+func ProductLangAdd(t ProductLang) {
+	ProductLangList = append(ProductLangList, t)
+
+}
+
+// 获取列表
+func ProductLangLists() (r []ProductLang, Total int64) {
+
+	return ProductLangList, int64(len(ProductLangList))
+}

+ 28 - 11
models/Product/ProductMode.go

@@ -1,26 +1,43 @@
 package Product
 
-// 产品协议 1:Mqtt  2:tcp  3:CoAP   6:http  7:https  8:websocket
+import (
+	"plugin"
+)
+
+// 网关
 type ProductMode struct {
 	Id         int    `json:"Id"`
 	T_name     string `json:"T_name"`     // 协议名称  Mqtt
-	T_address  string `json:"T_address"`  //接入地址    bj-3-mqtt.iot-api.com:1883
+	T_connect  string `json:"T_connect"`  //接入地址    bj-3-mqtt.iot-api.com:1883
 	T_describe string `json:"T_describe"` // 描述内容
-	T_state    int    `json:"T_state"`    //状态
-}
+	T_state    int    `json:"T_state"`    //状态  0停用  1 开启
+	T_file     string `json:"-"`          //文件地址
+	T_log      string `json:"T_log"`      //文件地址
 
-var ProductModeList = []*ProductMode{}
-
-// ---------------- 方法 -------------------
+	T_Config_map map[string]map[string]string `json:"T_Config_map"` //接入端口   8888
+	T_Plugin     *plugin.Plugin               `json:"-"`            //状态
+}
 
-// 添加
-func (t *ProductMode) Add() {
-	ProductModeList = append(ProductModeList, t)
+var ProductModeMap map[int]*ProductMode
 
+func init() {
+	ProductModeMap = make(map[int]*ProductMode)
 }
 
 // 获取列表
-func ProductModeLists() (r []*ProductMode, Total int64) {
+func ProductModeLists() (r []ProductMode, Total int64) {
+	var ProductModeList = []ProductMode{}
+	for _, v := range ProductModeMap {
+		ProductModeList = append(ProductModeList, ProductMode{Id: v.Id, T_name: v.T_name, T_connect: v.T_connect, T_describe: v.T_describe, T_state: v.T_state, T_Config_map: v.T_Config_map})
+	}
 
 	return ProductModeList, int64(len(ProductModeList))
 }
+
+/*
+1:MQTT
+2:TCP
+6:HTTP
+
+
+*/

+ 3 - 3
models/Product/ProductOTA.go

@@ -13,7 +13,7 @@ import (
 // OTA
 type ProductOTA struct {
 	Id          int    `orm:"column(ID);size(11);auto;pk" json:"Id" form:"Id"`
-	T_tokey     string `orm:"size(8);index" json:"T_tokey" form:"T_tokey"`                // 用户识别码(8位) ,管理员可以为空
+	T_uuid      string `orm:"size(8);index" json:"T_uuid" form:"T_uuid"`                  // 用户识别码(8位) ,管理员可以为空
 	T_ProductID string `orm:"size(8);index" json:"T_ProductID" form:"T_ProductID"`        // 产品型号 随机生成(8位)
 	T_name      string `orm:"size(256);" json:"T_name" form:"T_name"`                     // 固件名称
 	T_version   string `orm:"size(200);" json:"T_version" form:"T_version"`               // 版本
@@ -96,8 +96,8 @@ func (t *ProductOTA) Lists(PageIndex int, PageSize int) (r []ProductOTA, Total i
 	if len(t.T_version) > 0 {
 		cond = cond.And("T_version__icontains", t.T_version) // .AndNot("status__in", 1).Or("profile__age__gt", 2000)
 	}
-	if len(t.T_tokey) == 8 {
-		cond = cond.And("T_tokey", t.T_tokey) // 用户识别码
+	if len(t.T_uuid) == 8 {
+		cond = cond.And("T_uuid", t.T_uuid) // 用户识别码
 	}
 	// 执行
 	qs.Limit(PageSize, offset).SetCond((*orm2.Condition)(cond)).All(&r)

+ 12 - 12
models/Product/ProductProt.go

@@ -15,15 +15,15 @@ import (
 
 // 产品协议
 type ProductProt struct {
-	Id      int    `orm:"column(ID);size(11);auto;pk" json:"Id" form:"Id"`
-	T_tokey string `orm:"size(8);index" json:"T_tokey" form:"T_tokey"`    // 用户识别码(8位) ,管理员可以为空
-	T_name  string `orm:"size(256);" json:"T_name" form:"T_name"`         // 协议名称
-	T_mode  int    `orm:"size(1);default(0)" json:"T_mode" form:"T_mode"` //接入方式  0:Mqtt  1:http  2:tcp  3:CoAP  4:websocket
+	Id     int    `orm:"column(ID);size(11);auto;pk" json:"Id" form:"Id"`
+	T_uuid string `orm:"size(8);index" json:"T_uuid" form:"T_uuid"`      // 用户识别码(8位) ,管理员可以为空
+	T_name string `orm:"size(256);" json:"T_name" form:"T_name"`         // 协议名称
+	T_mode int    `orm:"size(1);default(0)" json:"T_mode" form:"T_mode"` //接入方式  0:Mqtt  1:http  2:tcp  3:CoAP  4:websocket
 	//T_prot     int    `orm:"size(1);default(0)" json:"T_Prot" form:"T_prot"`                              //接入协议ID  0:统一协议
-	T_lang     int    `orm:"size(1);default(1)" json:"T_lang" form:"T_lang"`                                  //编程语言 0: 无解析 1: go   2: C
-	T_analysis string `orm:"size(100);default(yunlot-pxxxx-v1.19-01.so)" json:"T_analysis" form:"T_analysis"` //数据解析
-	T_text     string `orm:"type(text);default('')" json:"T_text" form:"T_text"`                              // 代码内容
-	T_describe string `orm:"type(text);default('')" json:"T_describe" form:"T_describe"`                      // 描述内容
+	T_lang     int    `orm:"size(1);default(1)" json:"T_lang" form:"T_lang"`             //编程语言 0: 无解析 1: go   2: C
+	T_analysis string `orm:"size(100);default('')" json:"T_analysis" form:"T_analysis"`  //数据解析
+	T_text     string `orm:"type(text);default('')" json:"T_text" form:"T_text"`         // 代码内容
+	T_describe string `orm:"type(text);default('')" json:"T_describe" form:"T_describe"` // 描述内容
 	//T_reply    string `orm:"size(100);default(_reply)" json:"T_reply" form:"T_reply"`                       //返回后缀  _reply
 
 }
@@ -160,8 +160,8 @@ func (t *ProductProt) Lists(PageIndex int, PageSize int) (r []ProductProt, Total
 	if len(t.T_name) > 0 {
 		cond = cond.And("T_name__icontains", t.T_name) // .AndNot("status__in", 1).Or("profile__age__gt", 2000)
 	}
-	if len(t.T_tokey) == 8 {
-		cond = cond.And("T_tokey", t.T_tokey) // 用户识别码
+	if len(t.T_uuid) == 8 {
+		cond = cond.And("T_uuid", t.T_uuid) // 用户识别码
 	}
 
 	// 执行
@@ -187,8 +187,8 @@ func (t *ProductProt) Lists_All() (r []ProductProt) {
 	if len(t.T_name) > 0 {
 		cond = cond.And("T_name__icontains", t.T_name) // .AndNot("status__in", 1).Or("profile__age__gt", 2000)
 	}
-	if len(t.T_tokey) == 8 {
-		cond = cond.And("T_tokey", t.T_tokey) // 用户识别码
+	if len(t.T_uuid) == 8 {
+		cond = cond.And("T_uuid", t.T_uuid) // 用户识别码
 	}
 	// 执行
 	qs.SetCond((*orm2.Condition)(cond)).All(&r)

+ 5 - 5
models/Product/ProductType.go

@@ -17,7 +17,7 @@ import (
 // 产品类型
 type ProductType struct {
 	T_ProductID string `orm:"size(8);pk" json:"T_ProductID" form:"T_ProductID"` // 产品型号 随机生成(8位)
-	T_tokey     string `orm:"size(8);index" json:"T_tokey" form:"T_tokey"`      // 用户识别码(8位) ,管理员可以为空
+	T_uuid      string `orm:"size(8);index" json:"T_uuid" form:"T_uuid"`        // 用户识别码(8位) ,管理员可以为空
 	T_name      string `orm:"size(256);" json:"T_name" form:"T_name"`           // 产品名称
 	T_img       string `orm:"size(200);" json:"T_img" form:"T_img"`             // 图片
 	T_akey      string `orm:"size(56);" json:"T_akey" `                         // 授权密钥
@@ -250,8 +250,8 @@ func (t *ProductType) Lists(PageIndex int, PageSize int) (r []ProductType, Total
 	if len(t.T_ProductID) > 0 {
 		cond = cond.And("T_ProductID", t.T_ProductID) // .AndNot("status__in", 1).Or("profile__age__gt", 2000)
 	}
-	if len(t.T_tokey) == 8 {
-		cond = cond.And("T_tokey", t.T_tokey) // 用户识别码
+	if len(t.T_uuid) == 8 {
+		cond = cond.And("T_uuid", t.T_uuid) // 用户识别码
 	}
 
 	// 执行
@@ -292,8 +292,8 @@ func (t *ProductType) Lists_All() (r []ProductType) {
 	if len(t.T_ProductID) > 0 {
 		cond = cond.And("T_ProductID", t.T_ProductID) // .AndNot("status__in", 1).Or("profile__age__gt", 2000)
 	}
-	if len(t.T_tokey) == 8 {
-		cond = cond.And("T_tokey", t.T_tokey) // 用户识别码
+	if len(t.T_uuid) == 8 {
+		cond = cond.And("T_uuid", t.T_uuid) // 用户识别码
 	}
 	// 执行
 	qs.SetCond((*orm2.Condition)(cond)).All(&r)

+ 5 - 3
routers/Product.go

@@ -8,17 +8,19 @@ import (
 func init() {
 	prefix := "/Product"
 	// 接入网关
-	beego.Router(prefix+"/ProductModeLists/List", &controllers.ProductProtController{}, "*:ProductModeLists") // 获取未读消息
+	beego.Router(prefix+"/ProductMode/List", &controllers.ProductModeController{}, "*:ProductModeLists") // 获取未读消息
+	beego.Router(prefix+"/ProductMode/Updata", &controllers.ProductModeController{}, "*:Updata")         // 获取未读消息
+	beego.Router(prefix+"/ProductLang/List", &controllers.ProductProtController{}, "*:ProductLangList")  // 获取未读消息
 
 	// 产品类型
-	beego.Router(prefix+"/ProductType/Add", &controllers.ProductTypeController{}, "*:Add")       // 获取未读消息
+	//beego.Router(prefix+"/ProductType/Add", &controllers.ProductTypeController{}, "*:Add")       // 获取未读消息
 	beego.Router(prefix+"/ProductType/Get", &controllers.ProductTypeController{}, "*:Get")       // 获取未读消息
 	beego.Router(prefix+"/ProductType/List", &controllers.ProductTypeController{}, "*:List")     // 获取未读消息
 	beego.Router(prefix+"/ProductType/Update", &controllers.ProductTypeController{}, "*:Update") // 获取未读消息
 	beego.Router(prefix+"/ProductType/Delete", &controllers.ProductTypeController{}, "*:Delete") // 获取未读消息
 
 	// 产品协议
-	beego.Router(prefix+"/ProductProt/Add", &controllers.ProductProtController{}, "*:Add")       // 获取未读消息
+	beego.Router(prefix+"/ProductProt/Import", &controllers.ProductProtController{}, "*:Import") // 获取未读消息
 	beego.Router(prefix+"/ProductProt/Get", &controllers.ProductProtController{}, "*:Get")       // 获取未读消息
 	beego.Router(prefix+"/ProductProt/List", &controllers.ProductProtController{}, "*:List")     // 获取未读消息
 	beego.Router(prefix+"/ProductProt/Update", &controllers.ProductProtController{}, "*:Update") // 获取未读消息

+ 3 - 3
routers/RunCode.go

@@ -8,8 +8,8 @@ import (
 func init() {
 
 	// 日志
-	beego.Router("/RunCode/Languages", &controllers.RuncodeController{}, "*:Languages") // 获取未读消息
-	beego.Router("/RunCode/Run", &controllers.RuncodeController{}, "*:Run")             // 获取未读消息
-	beego.Router("/RunCode/Build", &controllers.RuncodeController{}, "*:Build")         // 获取未读消息
+	//beego.Router("/RunCode/Languages", &controllers.RuncodeController{}, "*:Languages") // 获取未读消息
+	beego.Router("/RunCode/Run", &controllers.RuncodeController{}, "*:Run")     // 获取未读消息
+	beego.Router("/RunCode/Build", &controllers.RuncodeController{}, "*:Build") // 获取未读消息
 
 }

+ 4 - 0
routers/router.go

@@ -7,4 +7,8 @@ import (
 
 func init() {
 	beego.Router("/", &controllers.MainController{})
+
+	//----------- 配置图片
+	beego.Router("/UpFile/Token", &controllers.UpFileController{}, "*:UpFileToken") // *全部;  get,post:
+
 }

+ 56 - 0
tests/NatsServer_test.go

@@ -0,0 +1,56 @@
+package test
+
+import (
+	"fmt"
+	"github.com/nats-io/nats-server/v2/server"
+	"github.com/nats-io/nats.go"
+	"testing"
+	"time"
+)
+
+func TestNats_server(t *testing.T) {
+	opts := &server.Options{
+		ServerName: "Yunlot-nats-server",
+		Port:       6503,
+	}
+
+	// Initialize new server with options
+	ns, err := server.NewServer(opts)
+
+	if err != nil {
+		panic(any(err))
+	}
+
+	// Start the server via goroutine
+	go ns.Start()
+
+	// Wait for server to be ready for connections
+	if !ns.ReadyForConnections(4 * time.Second) {
+		panic(any("not ready for connection"))
+	}
+
+	// Connect to server
+	nc, err := nats.Connect(ns.ClientURL())
+
+	if err != nil {
+		panic(any(err))
+	}
+
+	subject := "my-subject"
+
+	// Subscribe to the subject
+	nc.Subscribe(subject, func(msg *nats.Msg) {
+		// Print message data
+		data := string(msg.Data)
+		fmt.Println(data)
+
+		// Shutdown the server (optional)
+		ns.Shutdown()
+	})
+
+	// Publish data to the subject
+	nc.Publish(subject, []byte("Hello embedded NATS!"))
+
+	// Wait for server shutdown
+	ns.WaitForShutdown()
+}

+ 110 - 0
tests/sdk_test.go

@@ -0,0 +1,110 @@
+package test
+
+import (
+	//YunIot "gogs.baozhida.cn/bzdadmin/YunIot_SDK"
+	YunIot "Yunlot/SDK"
+	"fmt"
+	"testing"
+)
+
+func TestYunIot(t *testing.T) {
+
+	YunIot_r, err := YunIot.NewYunIot("192.168.11.112")
+	if err != nil {
+		panic(any(err))
+	}
+	// 获取设备信息
+	// T_sn string 设备Sn
+	Device_r, err := YunIot_r.GetDevice("2023468279548912")
+	if err != nil {
+		println("没找到SN")
+	}
+	fmt.Println(Device_r)
+
+	// 获取设备列表
+	// T_ProductID string 产品类型
+	// T_sn string 设备Sn
+	// T_online int 在线状态 0所有  1在线   2离线   3未激活
+	// PageIndex int 页码
+	// PageSize int  每页数量 默认为10
+	DeviceList_r, err := YunIot_r.GetDeviceList("", "", 0, 0, 0)
+	if err != nil {
+		println(err)
+	}
+	fmt.Println(DeviceList_r)
+
+	// 推送设备数据
+	// T_sn string 设备Sn
+	// T_data string 发送内容 json 数据
+	err = YunIot_r.GetDevicePush("2023456942857102", "{\"AAAA\":[{\"BBBB\":[{\"name\":\"TempSet\",\"value\":\"266666\"}]}]}")
+	if err != nil {
+		println("推送失败!")
+	} else {
+		println("推送成功!")
+	}
+
+	// 获取设备数据
+	// T_sn string 产品sn
+	// T_jointTab string 参数  AAAA.CCCC 拼接符.
+	// jsonFind string 条件 {"$or":[{"name":"TempSet"},{"value":"26"}]}
+	// jsonSort string 排序  {"value": 1}
+	// PageIndex int 页码
+	// PageSize int  每页数量 默认为10
+	DeviceData_r, err := YunIot_r.GetDeviceData("2023456942857102", "AAAA.CCCC", "", "", 0, 0)
+	if err != nil {
+		println(err)
+	}
+	for _, v := range DeviceData_r.List {
+		d := v.(map[string]interface{})
+		fmt.Println(d["name"], ":", d["value"])
+	}
+
+	// 获取产品
+	// T_ProductID string 产品型号
+	ProductType_r, err := YunIot_r.GetProductType("ujRXdIYz")
+	if err != nil {
+		println(err)
+	}
+	fmt.Println(ProductType_r)
+
+	// 获取产品列表
+	// T_uuid string 用户识别码(8位)
+	// T_name string 产品名称
+	ProductTypeList_r, err := YunIot_r.GetProductTypeList("", "")
+	if err != nil {
+		println(err)
+	}
+	for _, v := range ProductTypeList_r {
+		fmt.Println(v)
+	}
+
+	//获取协议
+	//T_ProductID string 产品型号
+	ProductProt_r, err := YunIot_r.GetProductProt(31)
+	if err != nil {
+		println(err)
+	}
+	fmt.Println(ProductProt_r)
+
+	//获取协议列表
+	//T_uuid string 用户识别码(8位)
+	//T_mode int 根据 网关列表
+	//T_name string 产品名称
+	ProductProtList_r, err := YunIot_r.GetProductProtList("", 0, "")
+	if err != nil {
+		println(err)
+	}
+	for _, v := range ProductProtList_r {
+		fmt.Println(v)
+	}
+
+	//获取网关列表
+	ProductModeList_r, err := YunIot_r.GetProductModeList()
+	if err != nil {
+		println(err)
+	}
+	for _, v := range ProductModeList_r {
+		fmt.Println(v)
+	}
+
+}