| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227 | 
							- package Device
 
- import (
 
- 	"Yunlot/conf"
 
- 	"Yunlot/lib"
 
- 	"Yunlot/logs"
 
- 	"Yunlot/models"
 
- 	"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/mongo"
 
- 	"go.mongodb.org/mongo-driver/mongo/options"
 
- 	"strconv"
 
- 	"time"
 
- )
 
- // 模板
 
- type DeviceData_R struct {
 
- 	T_tab      string      `orm:"size(256);index" json:"T_Rtab"`                         //转发 TAB 标识 拼接:AAAA.BBBB.   对象后面加点
 
- 	T_type     int         `orm:"size(200);default(4)"`                                  // 数据类型  (1,'bool'),(2,'int'),(3,'float'),(4,'str'),(5,'time'),(7,'u8'[模式图片]);
 
- 	T_bool     bool        `orm:"type(text);size(200);"`                                 // 值
 
- 	T_int      int         `orm:"type(text);size(200);null"`                             // 值
 
- 	T_float    float64     `orm:"type(text);size(200);null"`                             // 值
 
- 	T_time     models.Time `orm:"type(timestamp);null;"`                                 // 采集时间
 
- 	CreateTime models.Time `orm:"column(create_time);type(timestamp);null;auto_now_add"` //auto_now_add 第一次保存时才设置时间
 
- }
 
- // 表单
 
- 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"` // 标签路径
 
- 	T_jsonFind string `json:"T_jsonFind" form:"T_jsonFind"` // 条件
 
- 	T_jsonSort string `json:"T_jsonSort" form:"T_jsonSort"` // 排序
 
- 	PageIndex  int    `json:"PageIndex" form:"PageIndex"`   // 当前页码
 
- 	PageSize   int    `json:"PageSize" form:"PageSize"`     // 每页文档数量
 
- }
 
- var redis_DeviceData cache.Cache
 
- var Mongodb_client *mongo.Client
 
- var Mongodb_DB *mongo.Database
 
- func init() {
 
- 	credential := options.Credential{
 
- 		//AuthSource: conf.Mongodb_DB,
 
- 		Username: conf.Mongodb_Username,
 
- 		Password: conf.Mongodb_Password,
 
- 	}
 
- 	ctx, cancel := context.WithTimeout(context.Background(), 10*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))
 
- 	}
 
- 	Mongodb_DB = Mongodb_client.Database(conf.Mongodb_DB)
 
- 	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 {
 
- 		errMsg := "failed to init redis"
 
- 		logs.Println(errMsg, err)
 
- 	}
 
- }
 
- // ---------------- Redis -------------------
 
- // Redis_Set(m.T_sn,m) // Redis 更新缓存
 
- func RedisDeviceData_Set(T_sn string, T_id int, r DeviceData_R) (err error) {
 
- 	key := T_sn + "|" + strconv.Itoa(T_id)
 
- 	if redis_DeviceData.IsExist(key) {
 
- 		var t DeviceData_R
 
- 		v := redis_DeviceData.Get(key)
 
- 		json.Unmarshal(v.([]byte), &t)
 
- 		// 防止时间溢出
 
- 		if time.Now().Unix() <= r.T_time.Unix() {
 
- 			r.T_time.NowDbTime()
 
- 		}
 
- 		// 提前最新数据
 
- 		if t.T_time.Unix() > r.T_time.Unix() {
 
- 			// 储存的 是最新数据
 
- 			return
 
- 		}
 
- 	}
 
- 	//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 DeviceData_R, is bool) {
 
- 	if redis_DeviceData.IsExist(key) {
 
- 		v := redis_DeviceData.Get(key)
 
- 		json.Unmarshal(v.([]byte), &r)
 
- 		return r, true
 
- 	}
 
- 	return DeviceData_R{}, false
 
- }
 
- // ----------------
 
- func Data_Add(JointTab string, bson_r *bson.M) {
 
- 	logs.Println("JointTab:", JointTab, *bson_r)
 
- 	collection := Mongodb_DB.Collection(JointTab)
 
- 	_, err := collection.InsertOne(context.TODO(), bson_r)
 
- 	if err != nil {
 
- 		panic(any(err))
 
- 	}
 
- }
 
- // db.getCollection("2023445039284316_params_varData").find({ $and : [{"name" : "TempSet"}, {"value" : "26"}] }).limit(1000).skip(0)
 
- // ----------------
 
- func Data_Read(JointTab string, bson_r *bson.M) {
 
- 	logs.Println("JointTab:", JointTab, *bson_r)
 
- 	collection := Mongodb_DB.Collection(JointTab)
 
- 	_, err := collection.InsertOne(context.TODO(), bson_r)
 
- 	if err != nil {
 
- 		panic(any(err))
 
- 	}
 
- }
 
- /*
 
- ----------------
 
- // 数据列表
 
- 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) lib.JSONS {
 
- 	var err error
 
- 	// 初始化 Mongodb_DB
 
- 	collection := Mongodb_DB.Collection(JointTab)
 
- 	if page < 1 {
 
- 		page = 1
 
- 	}
 
- 	// 限制 过小、过大
 
- 	if pageSize < 1 || pageSize > 9999 {
 
- 		page = 10
 
- 	}
 
- 	// 分页
 
- 	options := options.Find().SetSkip(int64((page - 1) * pageSize)).SetLimit(int64(pageSize))
 
- 	// 排序
 
- 	if len(jsonSort) != 0 {
 
- 		// 解码JSON
 
- 		var jsonSortMap map[string]interface{}
 
- 		err = json.Unmarshal([]byte(jsonSort), &jsonSortMap)
 
- 		if err != nil {
 
- 			logs.PrintlnError("解码JSON 错误", err)
 
- 			return lib.JSONS{Code: lib.Error, Msg: "排序 解码JSON 错误!"}
 
- 		}
 
- 		options = options.SetSort(bson.M(jsonSortMap))
 
- 	}
 
- 	// 条件
 
- 	jsonFind_M := bson.M{}
 
- 	if len(jsonFind) != 0 {
 
- 		// 解码JSON
 
- 		var jsonFindMap map[string]interface{}
 
- 		err = json.Unmarshal([]byte(jsonFind), &jsonFindMap)
 
- 		if err != nil {
 
- 			logs.PrintlnError("解码JSON 错误", err)
 
- 			return lib.JSONS{Code: lib.Error, Msg: "条件 解码JSON 错误!"}
 
- 		}
 
- 		jsonFind_M = jsonFindMap
 
- 	}
 
- 	cursor, err := collection.Find(context.Background(), jsonFind_M, options)
 
- 	if err != nil {
 
- 		logs.PrintlnError("Find 错误", err)
 
- 		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)
 
- 		return lib.JSONS{Code: lib.Error, Msg: "cursor.All 错误!"}
 
- 	}
 
- 	// 执行计数操作
 
- 	count, err := collection.CountDocuments(context.Background(), jsonFind_M)
 
- 	if err != nil {
 
- 		logs.PrintlnError("Count 错误", err)
 
- 		return lib.JSONS{Code: lib.Error, Msg: "Count 错误!"}
 
- 	}
 
- 	return lib.JSONS{
 
- 		Code:      lib.Success,
 
- 		Msg:       "ok!",
 
- 		List:      results,
 
- 		Total:     int16(count),
 
- 		PageIndex: page,
 
- 		PageSize:  pageSize,
 
- 	}
 
- }
 
 
  |