siked 1 year ago
commit
5fb74c93fa
9 changed files with 957 additions and 0 deletions
  1. 27 0
      TimeTask/OrmLog.go
  2. 21 0
      TimeTask/TimeTask.go
  3. 11 0
      Z_Build.bat
  4. 19 0
      conf/config.go
  5. 84 0
      controllers/PublishCode.go
  6. 442 0
      lib/lib.go
  7. 94 0
      logs/LogPrintln.go
  8. 70 0
      models/GTime.go
  9. 189 0
      models/PublishCode.go

+ 27 - 0
TimeTask/OrmLog.go

@@ -0,0 +1,27 @@
+package TimeTask
+
+import (
+	"PublishCode/logs"
+	"fmt"
+	"io/ioutil"
+	"os"
+	"time"
+)
+
+var OrmLogOrmLog *os.File
+
+func OrmLog_MonitorScanStatus() {
+
+	logs.Println("------- ORM 日志清理 --------")
+	Data, err := ioutil.ReadFile(OrmLogOrmLog.Name())
+	if err != nil {
+		fmt.Printf("文件打开失败=%v\n", err)
+		return
+	}
+	err = ioutil.WriteFile("logs/orm/logx_"+time.Now().Format("2006-01-02")+".log", Data, 0666)
+	if err != nil {
+		fmt.Printf("文件打开失败=%v\n", err)
+	}
+	logs.Println("清空:", os.Truncate(OrmLogOrmLog.Name(), 0))
+
+}

+ 21 - 0
TimeTask/TimeTask.go

@@ -0,0 +1,21 @@
+package TimeTask
+
+import (
+	"PublishCode/logs"
+	"PublishCode/models"
+	"fmt"
+	"github.com/robfig/cron/v3"
+)
+
+func TimeTaskGo() {
+	logs.Println("==========定时任务开始==========")
+	crontab := cron.New(cron.WithSeconds())
+
+	_, err := crontab.AddFunc("0 0 0 * * *", models.PublishCode_Indexes)
+	if err != nil {
+		fmt.Printf("err: %v\n", err)
+		logs.Println("Cron [models.PublishCode_Indexes] OK!")
+	}
+
+	crontab.Start() // 开始任务
+}

+ 11 - 0
Z_Build.bat

@@ -0,0 +1,11 @@
+cd %~dp0
+set GOARCH=amd64
+set GOOS=linux
+set GOPATH=C:\Users\SIKED\go
+set GO111MODULE=auto
+set GOROOT=C:\Program Files\Go
+
+go build -o PublishCode main.go
+
+
+PAUSE

+ 19 - 0
conf/config.go

@@ -0,0 +1,19 @@
+package conf
+
+import (
+	beego "github.com/beego/beego/v2/server/web"
+)
+
+var HTTPPort, _ = beego.AppConfig.Int("HTTPPort")
+var AppName, _ = beego.AppConfig.String("appname")
+
+// Redis
+var Redis_address, _ = beego.AppConfig.String("Redis_address")
+var Redis_password, _ = beego.AppConfig.String("Redis_password")
+var Redis_dbNum, _ = beego.AppConfig.String("Redis_dbNum")
+
+// Mongodb
+var Mongodb_Url, _ = beego.AppConfig.String("Mongodb_Url")
+var Mongodb_DB, _ = beego.AppConfig.String("Mongodb_DB")
+var Mongodb_Username, _ = beego.AppConfig.String("Mongodb_Username")
+var Mongodb_Password, _ = beego.AppConfig.String("Mongodb_Password")

+ 84 - 0
controllers/PublishCode.go

@@ -0,0 +1,84 @@
+package controllers
+
+import (
+	"PublishCode/lib"
+	"PublishCode/models"
+	beego "github.com/beego/beego/v2/server/web"
+	"go.mongodb.org/mongo-driver/bson"
+)
+
+type PublishCodeController struct {
+	beego.Controller
+}
+
+func (c *PublishCodeController) PublishCode() {
+	// 验证秘钥
+	//ProductKey := c.GetString("ProductKey")
+	//ProductID := c.GetString("ProductID")
+	//ProductType_r := models.PublishCode_R{T_ProductID: ProductID}
+
+	if len(string(c.Ctx.Input.RequestBody)) > 9999 {
+		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "json 过大,请减少内容!"}
+		c.ServeJSON()
+		return
+	}
+	//println(string(c.Ctx.Input.RequestBody))
+	if len(c.Ctx.Input.RequestBody) == 0 {
+		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "json 不能为空!"}
+		c.ServeJSON()
+		return
+	}
+
+	//// 解析json
+	//var datajson map[string]interface{}
+	//err := json.Unmarshal(c.Ctx.Input.RequestBody, &datajson)
+	//if err != nil {
+	//	c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "json 解析失败!"}
+	//	c.ServeJSON()
+	//	return
+	//}
+	//// 将数据编码为JSON
+	//jsonData, err := json.Marshal(datajson)
+	//if err != nil {
+	//	fmt.Println("Error encoding JSON:", err)
+	//	return
+	//}
+
+	GetRandstringI := len(c.Ctx.Input.RequestBody) % 100
+	var CodeNum, JointTab string
+	for true {
+		JointTab = lib.WeekByDate()
+		CodeNum = lib.GetRandstring(15, "0123456789123456789", int64(GetRandstringI))
+		bson_r := bson.M{"CodeNum": CodeNum, "Data": c.Ctx.Input.RequestBody}
+		//for key, value := range datajson {
+		//	//fmt.Println(key, "->:", value)
+		//	if key != "CodeNum" {  // 防止被强行改变 CodeNum
+		//		bson_r[key] = value
+		//	}
+		//}
+
+		if models.PublishCode_Add(JointTab, &bson_r) == nil {
+			break
+		}
+		//println("!!!!!!!!!!!",CodeNum)
+		GetRandstringI += 1
+	}
+
+	c.Data["json"] = lib.JSONR{Code: lib.Success, Msg: "ok!", Data: "9" + JointTab + CodeNum}
+	c.ServeJSON()
+	return
+}
+func (c *PublishCodeController) CodeNum_Read() {
+	CodeNum := c.Ctx.Input.Param(":CodeNum")
+
+	r, err := models.CodeNum_Read(CodeNum)
+	if err != nil {
+		c.Data["json"] = lib.JSONR{Code: lib.Error, Msg: "无此码!"}
+		c.ServeJSON()
+		return
+	}
+	c.Data["json"] = lib.JSONR{Code: lib.Success, Msg: "ok!", Data: r}
+	c.ServeJSON()
+	return
+
+}

+ 442 - 0
lib/lib.go

@@ -0,0 +1,442 @@
+package lib
+
+import (
+	"encoding/json"
+	"fmt"
+
+	"go.mongodb.org/mongo-driver/bson"
+
+	"math/rand"
+
+	"reflect"
+	"strconv"
+	"strings"
+	"time"
+)
+
+func init() {
+
+}
+
+const Success = 200
+const Error = 201
+
+type JSONR struct {
+	//必须的大写开头
+	Code int16
+	Msg  string
+	Data interface{} // 泛型
+}
+type JSONS struct {
+	//必须的大写开头
+	Code      int16
+	Msg       string
+	List      interface{}
+	Total     int16
+	PageIndex int
+	PageSize  int
+}
+
+func C_Page(list interface{}, PageIndex, PageSize int, Total int64) (Jsons JSONS) {
+	Jsons.List = list
+	Jsons.Total = int16(Total)
+	Jsons.PageIndex = PageIndex
+	Jsons.PageSize = PageSize
+	//Jsons.PageSize = int16(math.Ceil(float64(Total) / float64(PageSize)))
+	return Jsons
+}
+
+func Strval(value interface{}) string {
+	var key string
+	if value == nil {
+		return key
+	}
+
+	switch value.(type) {
+	case float64:
+		ft := value.(float64)
+		key = strconv.FormatFloat(ft, 'f', -1, 64)
+	case float32:
+		ft := value.(float32)
+		key = strconv.FormatFloat(float64(ft), 'f', -1, 64)
+	case int:
+		it := value.(int)
+		key = strconv.Itoa(it)
+	case uint:
+		it := value.(uint)
+		key = strconv.Itoa(int(it))
+	case int8:
+		it := value.(int8)
+		key = strconv.Itoa(int(it))
+	case uint8:
+		it := value.(uint8)
+		key = strconv.Itoa(int(it))
+	case int16:
+		it := value.(int16)
+		key = strconv.Itoa(int(it))
+	case uint16:
+		it := value.(uint16)
+		key = strconv.Itoa(int(it))
+	case int32:
+		it := value.(int32)
+		key = strconv.Itoa(int(it))
+	case uint32:
+		it := value.(uint32)
+		key = strconv.Itoa(int(it))
+	case int64:
+		it := value.(int64)
+		key = strconv.FormatInt(it, 10)
+	case uint64:
+		it := value.(uint64)
+		key = strconv.FormatUint(it, 10)
+	case string:
+		key = value.(string)
+	case []byte:
+		key = string(value.([]byte))
+	default:
+		newValue, _ := json.Marshal(value)
+		key = string(newValue)
+	}
+
+	return key
+}
+
+// 取一个
+func Take_one(a, b string) string {
+	if len(a) == 0 {
+		return b
+	}
+	return a
+}
+
+func To_int(value interface{}) int {
+	var key int
+	if value == nil {
+		return key
+	}
+	switch value.(type) {
+	case float64:
+		key = int(value.(float64))
+	case float32:
+		key = int(value.(float32))
+	case int:
+		key = int(value.(int))
+	case uint:
+		key = int(value.(uint))
+	case int8:
+		key = int(value.(int8))
+	case uint8:
+		key = int(value.(uint8))
+	case int16:
+		key = int(value.(int16))
+	case uint16:
+		key = int(value.(uint16))
+	case int32:
+		key = int(value.(int32))
+	case uint32:
+		key = int(value.(uint32))
+	case int64:
+		key = int(value.(int64))
+	case uint64:
+		key = int(value.(uint64))
+	case string:
+		key, _ = strconv.Atoi(value.(string))
+	case []byte:
+		key, _ = strconv.Atoi(string(value.([]byte)))
+	default:
+		newValue, _ := json.Marshal(value)
+		key, _ = strconv.Atoi(string(newValue))
+	}
+	return key
+}
+func To_int64(value interface{}) int64 {
+	var key int64
+	if value == nil {
+		return key
+	}
+	switch value.(type) {
+	case float64:
+		key = int64(value.(float64))
+	case float32:
+		key = int64(value.(float32))
+	case int:
+		key = int64(value.(int))
+	case uint:
+		key = int64(value.(uint))
+	case int8:
+		key = int64(value.(int8))
+	case uint8:
+		key = int64(value.(uint8))
+	case int16:
+		key = int64(value.(int16))
+	case uint16:
+		key = int64(value.(uint16))
+	case int32:
+		key = int64(value.(int32))
+	case uint32:
+		key = int64(value.(uint32))
+	case int64:
+		key = int64(value.(int64))
+	case uint64:
+		key = int64(value.(uint64))
+	case string:
+		key, _ = strconv.ParseInt(value.(string), 10, 64)
+	case []byte:
+		key, _ = strconv.ParseInt(string(value.([]byte)), 10, 64)
+	default:
+		newValue, _ := json.Marshal(value)
+		key, _ = strconv.ParseInt(string(newValue), 10, 64)
+	}
+	return key
+}
+
+func To_float32(value interface{}) float32 {
+	var key float32
+	if value == nil {
+		return key
+	}
+
+	switch value.(type) {
+	case float64:
+		key = float32(value.(float64))
+	case float32:
+		key = float32(value.(float32))
+	case int:
+		key = float32(value.(int))
+	case uint:
+		key = float32(value.(uint))
+	case int8:
+		key = float32(value.(int8))
+	case uint8:
+		key = float32(value.(uint8))
+	case int16:
+		key = float32(value.(int16))
+	case uint16:
+		key = float32(value.(uint16))
+	case int32:
+		key = float32(value.(int32))
+	case uint32:
+		key = float32(value.(uint32))
+	case int64:
+		key = float32(value.(int64))
+	case uint64:
+		key = float32(value.(uint64))
+	case string:
+		key_float64, _ := strconv.ParseFloat(value.(string), 32/64)
+		key = float32(key_float64)
+	case []byte:
+		key_float64, _ := strconv.ParseFloat(string(value.([]byte)), 32/64)
+		key = float32(key_float64)
+	default:
+		newValue, _ := json.Marshal(value)
+		key_float64, _ := strconv.ParseFloat(string(newValue), 32/64)
+		key = float32(key_float64)
+	}
+
+	key_float64, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", key), 32/64)
+	key = float32(key_float64)
+
+	return key
+}
+
+func To_string(value interface{}) string {
+	var key string
+	if value == nil {
+		return key
+	}
+
+	switch value.(type) {
+	case float64:
+		ft := value.(float64)
+		key = strconv.FormatFloat(ft, 'f', -1, 64)
+	case float32:
+		ft := value.(float32)
+		key = strconv.FormatFloat(float64(ft), 'f', -1, 64)
+	case int:
+		it := value.(int)
+		key = strconv.Itoa(it)
+	case uint:
+		it := value.(uint)
+		key = strconv.Itoa(int(it))
+	case int8:
+		it := value.(int8)
+		key = strconv.Itoa(int(it))
+	case uint8:
+		it := value.(uint8)
+		key = strconv.Itoa(int(it))
+	case int16:
+		it := value.(int16)
+		key = strconv.Itoa(int(it))
+	case uint16:
+		it := value.(uint16)
+		key = strconv.Itoa(int(it))
+	case int32:
+		it := value.(int32)
+		key = strconv.Itoa(int(it))
+	case uint32:
+		it := value.(uint32)
+		key = strconv.Itoa(int(it))
+	case int64:
+		it := value.(int64)
+		key = strconv.FormatInt(it, 10)
+	case uint64:
+		it := value.(uint64)
+		key = strconv.FormatUint(it, 10)
+	case string:
+		key = value.(string)
+	case []byte:
+		key = string(value.([]byte))
+	default:
+		newValue, _ := json.Marshal(value)
+		key = string(newValue)
+	}
+	return key
+}
+
+func Random(min, max int) int {
+	rand.Seed(time.Now().Unix()) //Seed生成的随机数
+	return rand.Intn(max-min) + min
+}
+
+// #取得随机字符串:通过打乱slice来操作
+func GetRandstring(length int, char string, rand_x int64) string {
+	if length < 1 {
+		return ""
+	}
+
+	if len(char) <= 6 || len(char) <= length {
+		char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+	}
+
+	charArr := strings.Split(char, "")
+	ran := rand.New(rand.NewSource(time.Now().Unix() + rand_x))
+
+	l := len(charArr)
+	for i := l - 1; i > 0; i-- {
+		r := ran.Intn(i)
+		charArr[r], charArr[i] = charArr[i], charArr[r]
+	}
+	rchar := charArr[:length]
+	return strings.Join(rchar, "")
+}
+
+// 判断时间是当年的第几周
+func WeekByDate() string {
+	t := time.Now()
+	yearDay := t.YearDay()
+	yearFirstDay := t.AddDate(0, 0, -yearDay+1)
+	firstDayInWeek := int(yearFirstDay.Weekday())
+
+	//今年第一周有几天
+	firstWeekDays := 1
+	if firstDayInWeek != 0 {
+		firstWeekDays = 7 - firstDayInWeek + 1
+	}
+	var week int
+	if yearDay <= firstWeekDays {
+		week = 1
+	} else {
+		week = (yearDay-firstWeekDays)/7 + 2
+	}
+	return fmt.Sprintf("%d%02d", t.Year()%100, week) // 2253
+}
+
+// 将 时间格式为 bson.M 时间格式
+func MongdbJsonHtime(ArticleSlide bson.M) bson.M {
+	bson_M := bson.M{}
+	for key, value := range ArticleSlide {
+		//logs.Println(reflect.TypeOf(value).String())
+		switch reflect.TypeOf(value).String() {
+		case "map[string]interface {}":
+			jsonFind_M := bson.M{}
+			data, _ := json.Marshal(value.(map[string]interface{}))
+			err := json.Unmarshal(data, &jsonFind_M)
+			if err == nil {
+				bson_M[key] = MongdbJsonHtime(jsonFind_M)
+			}
+
+			break
+		case "[]interface {}":
+			bson_M_list := []bson.M{}
+			for _, valuex := range value.([]interface{}) {
+				if reflect.TypeOf(valuex).String() == "map[string]interface {}" {
+					jsonFind_M := bson.M{}
+					data, _ := json.Marshal(valuex.(map[string]interface{}))
+					err := json.Unmarshal(data, &jsonFind_M)
+					if err == nil {
+						bson_M_list = append(bson_M_list, MongdbJsonHtime(jsonFind_M))
+					}
+				}
+			}
+			bson_M[key] = bson_M_list
+			//return json_r
+			break
+		default:
+			t1, err := time.ParseInLocation("2006-01-02 15:04:05", value.(string), time.Local) // +8  时差
+			if err == nil {
+				bson_M[key] = t1
+			} else {
+				bson_M[key] = value
+			}
+
+			break
+		}
+	}
+
+	return bson_M
+}
+
+// 判断字符串是否在数组中
+func StringExistsInSlice(str string, slice []string) bool {
+	for _, s := range slice {
+		if s == str {
+			return true
+		}
+	}
+	return false
+}
+
+// 获取 JSON 指定位置  field : "AAA.BBB.d_name"
+func JsonGetField(data map[string]interface{}, field string) interface{} {
+	fields := strings.Split(field, ".")
+	result := data
+	for _, f := range fields {
+		if val, ok := result[f]; ok {
+			switch val.(type) {
+			case map[string]interface{}:
+				result = val.(map[string]interface{})
+			default:
+				return val
+			}
+		} else {
+			return nil
+		}
+	}
+	return result
+}
+
+// 获取 JSON 指定位置 data:修改的field必须存在  field : "AAA.BBB.d_name"   value: 123
+func JsonSetField(data map[string]interface{}, field string, value interface{}) {
+	fields := strings.Split(field, ".")
+	current := data
+	for i, fieldv := range fields {
+		if i == len(fields)-1 {
+			current[fieldv] = value
+		} else {
+			next, ok := current[fieldv].(map[string]interface{})
+			if !ok {
+				return
+			}
+			current = next
+		}
+	}
+}
+
+// 复制一份 Map
+func CopyMap(inputMap map[string]interface{}) map[string]interface{} {
+	copiedMap := make(map[string]interface{})
+	for key, value := range inputMap {
+		copiedMap[key] = value
+	}
+	return copiedMap
+}

+ 94 - 0
logs/LogPrintln.go

@@ -0,0 +1,94 @@
+package logs
+
+import (
+	"github.com/astaxie/beego/logs"
+	orm2 "github.com/beego/beego/v2/client/orm"
+	"time"
+)
+
+// var Test = true
+var logx *logs.BeeLogger
+var logxE *logs.BeeLogger
+var logxData *logs.BeeLogger
+
+var DeviceRealLogMap map[string]DeviceRealLogR // 设备实时日志
+
+type DeviceRealLogR struct {
+	Time time.Time //
+	Data []string  // 泛型数组
+}
+
+func init() {
+
+	DeviceRealLogMap = make(map[string]DeviceRealLogR)
+	go func() {
+		for true {
+			for key, value := range DeviceRealLogMap {
+				subM := time.Now().Sub(value.Time)
+				println(key+"日志-", subM.Minutes(), "分钟")
+				if subM.Minutes() > 3 {
+					delete(DeviceRealLogMap, key) // 删除日志
+				}
+			}
+
+			time.Sleep(time.Minute * 1)
+		}
+
+	}()
+
+	logx = logs.NewLogger()
+	logx.SetLogger(logs.AdapterFile, `{"filename":"logs/logx/logx.log","perm":"0666"}`)
+
+	logxE = logs.NewLogger()
+	logxE.SetLogger(logs.AdapterFile, `{"filename":"logs/logxE/logx.log","perm":"0666"}`)
+
+	logxData = logs.NewLogger()
+	logxData.SetLogger(logs.AdapterFile, `{"filename":"logs/Data/logx.log","perm":"0666"}`)
+
+	orm2.DebugLog = orm2.NewLog(logx)
+
+	// 测试 日志分割
+	//go func() {
+	//	t := 1
+	//	orm2.DebugLog.Println("==========DebugLog=========")
+	//	for true {
+	//		t +=1
+	//		orm2.DebugLog.Println("DebugLog:",t)
+	//		time.Sleep(time.Second * 1)
+	//	}
+	//}()
+	//go TimeTask.OrmLog_MonitorScanStatus()
+}
+
+func Println(format string, v ...interface{}) {
+
+	logx.Info(format, v)
+
+}
+
+func PrintlnError(format string, v ...interface{}) {
+
+	logxE.Error(format, v)
+	logx.Info(format, v)
+}
+
+func PrintlnData(str string) {
+
+	logxData.Info(str)
+}
+
+//func Println(a ...interface{}) {
+//	if test {
+//		fmt.Printf("=>", a)
+//	}
+//	logx.Info(">", a)
+//}
+
+// 日志
+// logs.Println(time.Now().Format("2006-01-02 15:04:05"), "=>", a)
+
+// 重要
+// logs.Println("MqttServer", " 存在报警 跳过:", string(msg))
+
+// 严重
+// logs.Println("MqttServer", " 存在报警 跳过:", string(msg))

+ 70 - 0
models/GTime.go

@@ -0,0 +1,70 @@
+package models
+
+import (
+	"encoding/json"
+	"fmt"
+	orm2 "github.com/beego/beego/v2/client/orm"
+	"time"
+)
+
+type Time struct {
+	time.Time
+}
+
+// MarshalJSON 序列化为JSON
+func (t Time) MarshalJSON() ([]byte, error) {
+	if t.IsZero() {
+		return []byte("\"\""), nil
+	}
+	stamp := fmt.Sprintf("\"%s\"", t.Format("2006-01-02 15:04:05"))
+	return []byte(stamp), nil
+}
+
+// UnmarshalJSON 反序列化为JSON
+func (t *Time) UnmarshalJSON(data []byte) error {
+	var err error
+	t.Time, err = time.Parse("2006-01-02 15:04:05", string(data)[1:20])
+	return err
+}
+
+func (t *Time) String() string {
+	data, _ := json.Marshal(t)
+	return string(data)
+}
+
+func (t *Time) FieldType() int {
+	return orm2.TypeDateTimeField
+}
+
+func (t *Time) SetRaw(value interface{}) error {
+	switch value.(type) {
+	case time.Time:
+		t.Time = value.(time.Time)
+	}
+	return nil
+}
+
+func (t *Time) RawValue() interface{} {
+	str := t.Format("2006-01-02 15:04:05")
+	if str == "0001-01-01 00:00:00" {
+		return nil
+	}
+	return str
+}
+
+func (t *Time) NowDbTime() Time {
+	dbTime := Time{}
+	dbTime.Time = time.Now()
+	return dbTime
+}
+func (t *Time) AddDates(years int, months int, days int) Time {
+	dbTime := Time{}
+	dbTime.Time = t.Time.AddDate(years, months, days)
+	return dbTime
+}
+func TimeParse(value string) (Time, error) {
+	dbTime := Time{}
+	times, err := time.Parse("2006-01-02 15:04:05", value)
+	dbTime.Time = times
+	return dbTime, err
+}

+ 189 - 0
models/PublishCode.go

@@ -0,0 +1,189 @@
+package models
+
+import (
+	"PublishCode/conf"
+	"PublishCode/lib"
+	"PublishCode/logs"
+	"context"
+	"encoding/json"
+	"fmt"
+	"github.com/astaxie/beego/cache"
+	_ "github.com/astaxie/beego/cache/redis"
+	_ "github.com/go-sql-driver/mysql"
+	"go.mongodb.org/mongo-driver/bson"
+	"go.mongodb.org/mongo-driver/bson/primitive"
+	"go.mongodb.org/mongo-driver/mongo"
+	"go.mongodb.org/mongo-driver/mongo/options"
+	"strconv"
+	"time"
+)
+
+// 模板
+type PublishCode_R struct {
+	CodeNum string `bson:"CodeNum"`
+	Data    string `bson:"Data"`
+	City    Time   `bson:"CreateTime"`
+}
+
+var redis_DeviceData cache.Cache
+var Mongodb_client *mongo.Client
+var Mongodb_DB *mongo.Database
+
+func init() {
+	var err error
+	config := fmt.Sprintf(`{"key":"%s","conn":"%s","dbNum":"%s","password":"%s"}`,
+		"redis_DeviceData", conf.Redis_address, conf.Redis_dbNum, conf.Redis_password)
+	logs.Println(config)
+
+	redis_DeviceData, err = cache.NewCache("redis", config)
+	if err != nil || redis_DeviceData == nil {
+		logs.PrintlnError(config, err)
+		panic(any(err))
+	}
+	ConnectMongodb()
+}
+
+// 连接 Mongodb
+func ConnectMongodb() {
+	credential := options.Credential{
+		//AuthSource: conf.Mongodb_DB,
+		Username:   conf.Mongodb_Username,
+		Password:   conf.Mongodb_Password,
+		AuthSource: conf.Mongodb_DB,
+	}
+	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+	defer cancel()
+	var err error
+	Mongodb_client, err = mongo.Connect(ctx, options.Client().ApplyURI(conf.Mongodb_Url).SetAuth(credential).SetMaxPoolSize(200))
+	if err != nil {
+		logs.PrintlnError("Mongodb 连接错误!", err)
+		panic(any(err))
+	} else {
+		logs.Println("Mongodb OK!", conf.Mongodb_Url)
+	}
+	Mongodb_DB = Mongodb_client.Database(conf.Mongodb_DB)
+
+	//测试连接
+	logs.Println("Mongodb 测试连接!")
+	collection := Mongodb_DB.Collection("yuniot")
+
+	_, err = collection.InsertOne(context.TODO(), bson.D{{"time", time.Now()}})
+	if err != nil {
+		logs.Println("Mongodb:", conf.Mongodb_Url, conf.Mongodb_Username, conf.Mongodb_Password, conf.Mongodb_DB)
+		logs.PrintlnError("Mongodb 连接测试错误!", err)
+		panic(any(err))
+	} else {
+		logs.Println("Mongodb 测试连接 OK!")
+	}
+
+}
+
+// ---------------- Redis -------------------
+// Redis_Set(m.T_sn,m) // Redis 更新缓存
+func RedisDeviceData_Set(T_sn string, T_id int, r PublishCode_R) (err error) {
+	key := T_sn + "|" + strconv.Itoa(T_id)
+
+	if redis_DeviceData.IsExist(key) {
+		var t PublishCode_R
+		v := redis_DeviceData.Get(key)
+		json.Unmarshal(v.([]byte), &t)
+		// 防止时间溢出
+
+	}
+
+	//json序列化
+	str, err := json.Marshal(r)
+	if err != nil {
+		logs.PrintlnError("RedisDeviceData_Set", err)
+		return
+	}
+	err = redis_DeviceData.Put(key, str, 1*time.Hour)
+	if err != nil {
+		logs.Println("set key:", key, ",value:", str, err)
+	}
+	return
+}
+
+func RedisDeviceData_Get(key string) (r PublishCode_R, is bool) {
+	if redis_DeviceData.IsExist(key) {
+		v := redis_DeviceData.Get(key)
+		json.Unmarshal(v.([]byte), &r)
+		return r, true
+	}
+	return PublishCode_R{}, false
+}
+
+// ----------------
+func PublishCode_Add(JointTab string, bson_r *bson.M) error {
+
+	//dd, _ := time.ParseDuration("8h")
+	//(*bson_r)["CreateTime"] = time.Now().Add(dd)  // 插入默认时间
+	(*bson_r)["CreateTime"] = time.Now() // 插入默认时间
+
+	//logs.Println("JointTab:", JointTab, *bson_r)
+
+	//
+	collection := Mongodb_DB.Collection(JointTab)
+
+	_, err := collection.InsertOne(context.TODO(), bson_r)
+	if err != nil {
+		logs.PrintlnError("Data_Add:", err.Error())
+	}
+	return err
+}
+
+// ---------------- 索引
+func PublishCode_Indexes() {
+
+	JointTab := lib.WeekByDate()
+	//
+	collection := Mongodb_DB.Collection(JointTab)
+
+	// 创建索引
+	_, err := collection.Indexes().CreateOne(context.TODO(), mongo.IndexModel{
+		Keys:    bson.D{{"CodeNum", 1}},          // 设置索引字段和排序方式
+		Options: options.Index().SetUnique(true), // 设置索引为唯一索引
+	})
+
+	if err != nil {
+		logs.PrintlnError("Data_Add Indexes:", err.Error())
+	}
+
+	return
+}
+
+// db.getCollection("2023445039284316_params_varData").find({ $and : [{"name" : "TempSet"}, {"value" : "26"}] }).limit(1000).skip(0)
+// ----------------
+func CodeNum_Read(CodeNum string) (r map[string]interface{}, err error) {
+	r = make(map[string]interface{})
+	collection := Mongodb_DB.Collection(CodeNum[1:5])
+
+	// 定义筛选条件
+	filter := bson.D{{"CodeNum", CodeNum[5:]}}
+	println(filter)
+	// 执行查询操作
+	var result bson.M
+
+	err = collection.FindOne(context.Background(), filter).Decode(&result)
+	r["CodeNum"] = CodeNum
+	if err != nil {
+		fmt.Println("Error finding document:", err)
+		return
+	}
+	var articleSlide map[string]interface{}
+	err = json.Unmarshal(result["Data"].(primitive.Binary).Data, &articleSlide)
+	if err != nil {
+		r["Data"] = lib.To_string(result["Data"])
+	} else {
+		r["Data"] = articleSlide
+	}
+
+	// 获取时间字段
+	timeField := result["CreateTime"].(primitive.DateTime) / 1000
+	timeValue := time.Unix(int64(timeField), 0)
+
+	r["CreateTime"] = timeValue.Format("2006-01-02 15:04:05")
+
+	fmt.Println("Found document:", r)
+	return
+}