DeviceData.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. package Device
  2. import (
  3. "Yunlot/conf"
  4. "Yunlot/lib"
  5. "Yunlot/logs"
  6. "Yunlot/models"
  7. "context"
  8. "encoding/json"
  9. "fmt"
  10. "github.com/astaxie/beego/cache"
  11. _ "github.com/astaxie/beego/cache/redis"
  12. _ "github.com/go-sql-driver/mysql"
  13. "go.mongodb.org/mongo-driver/bson"
  14. "go.mongodb.org/mongo-driver/mongo"
  15. "go.mongodb.org/mongo-driver/mongo/options"
  16. "strconv"
  17. "time"
  18. )
  19. // 模板
  20. type DeviceData_R struct {
  21. T_tab string `orm:"size(256);index" json:"T_Rtab"` //转发 TAB 标识 拼接:AAAA.BBBB. 对象后面加点
  22. T_type int `orm:"size(200);default(4)"` // 数据类型 (1,'bool'),(2,'int'),(3,'float'),(4,'str'),(5,'time'),(7,'u8'[模式图片]);
  23. T_bool bool `orm:"type(text);size(200);"` // 值
  24. T_int int `orm:"type(text);size(200);null"` // 值
  25. T_float float64 `orm:"type(text);size(200);null"` // 值
  26. T_time models.Time `orm:"type(timestamp);null;"` // 采集时间
  27. CreateTime models.Time `orm:"column(create_time);type(timestamp);null;auto_now_add"` //auto_now_add 第一次保存时才设置时间
  28. }
  29. // 表单
  30. type Device_Form struct {
  31. T_ProductID string `json:"T_ProductID" form:"T_ProductID"` // Sn
  32. T_sn string `json:"T_sn" form:"T_sn"` // 标签路径
  33. T_online int `json:"T_online" form:"T_online"` // 当前页码
  34. PageIndex int `json:"PageIndex" form:"PageIndex"` // 当前页码
  35. PageSize int `json:"PageSize" form:"PageSize"` // 每页文档数量
  36. }
  37. // 表单
  38. type DeviceData_Form struct {
  39. T_sn string `json:"T_sn" form:"T_sn"` // Sn
  40. T_jointTab string `json:"T_jointTab" form:"T_jointTab"` // 标签路径
  41. T_jsonFind string `json:"T_jsonFind" form:"T_jsonFind"` // 条件
  42. T_jsonSort string `json:"T_jsonSort" form:"T_jsonSort"` // 排序
  43. PageIndex int `json:"PageIndex" form:"PageIndex"` // 当前页码
  44. PageSize int `json:"PageSize" form:"PageSize"` // 每页文档数量
  45. }
  46. var redis_DeviceData cache.Cache
  47. var Mongodb_client *mongo.Client
  48. var Mongodb_DB *mongo.Database
  49. func init() {
  50. credential := options.Credential{
  51. //AuthSource: conf.Mongodb_DB,
  52. Username: conf.Mongodb_Username,
  53. Password: conf.Mongodb_Password,
  54. }
  55. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  56. defer cancel()
  57. var err error
  58. Mongodb_client, err = mongo.Connect(ctx, options.Client().ApplyURI(conf.Mongodb_Url).SetAuth(credential).SetMaxPoolSize(200))
  59. if err != nil {
  60. logs.PrintlnError("Mongodb 连接错误!", err)
  61. panic(any(err))
  62. }
  63. Mongodb_DB = Mongodb_client.Database(conf.Mongodb_DB)
  64. config := fmt.Sprintf(`{"key":"%s","conn":"%s","dbNum":"%s","password":"%s"}`,
  65. "redis_DeviceData", conf.Redis_address, conf.Redis_dbNum, conf.Redis_password)
  66. logs.Println(config)
  67. redis_DeviceData, err = cache.NewCache("redis", config)
  68. if err != nil || redis_DeviceData == nil {
  69. errMsg := "failed to init redis"
  70. logs.Println(errMsg, err)
  71. }
  72. }
  73. // ---------------- Redis -------------------
  74. // Redis_Set(m.T_sn,m) // Redis 更新缓存
  75. func RedisDeviceData_Set(T_sn string, T_id int, r DeviceData_R) (err error) {
  76. key := T_sn + "|" + strconv.Itoa(T_id)
  77. if redis_DeviceData.IsExist(key) {
  78. var t DeviceData_R
  79. v := redis_DeviceData.Get(key)
  80. json.Unmarshal(v.([]byte), &t)
  81. // 防止时间溢出
  82. if time.Now().Unix() <= r.T_time.Unix() {
  83. r.T_time.NowDbTime()
  84. }
  85. // 提前最新数据
  86. if t.T_time.Unix() > r.T_time.Unix() {
  87. // 储存的 是最新数据
  88. return
  89. }
  90. }
  91. //json序列化
  92. str, err := json.Marshal(r)
  93. if err != nil {
  94. logs.PrintlnError("RedisDeviceData_Set", err)
  95. return
  96. }
  97. err = redis_DeviceData.Put(key, str, 1*time.Hour)
  98. if err != nil {
  99. logs.Println("set key:", key, ",value:", str, err)
  100. }
  101. return
  102. }
  103. func RedisDeviceData_Get(key string) (r DeviceData_R, is bool) {
  104. if redis_DeviceData.IsExist(key) {
  105. v := redis_DeviceData.Get(key)
  106. json.Unmarshal(v.([]byte), &r)
  107. return r, true
  108. }
  109. return DeviceData_R{}, false
  110. }
  111. // ----------------
  112. func Data_Add(JointTab string, bson_r *bson.M) {
  113. logs.Println("JointTab:", JointTab, *bson_r)
  114. collection := Mongodb_DB.Collection(JointTab)
  115. _, err := collection.InsertOne(context.TODO(), bson_r)
  116. if err != nil {
  117. panic(any(err))
  118. }
  119. }
  120. // db.getCollection("2023445039284316_params_varData").find({ $and : [{"name" : "TempSet"}, {"value" : "26"}] }).limit(1000).skip(0)
  121. // ----------------
  122. func Data_Read(JointTab string, bson_r *bson.M) {
  123. logs.Println("JointTab:", JointTab, *bson_r)
  124. collection := Mongodb_DB.Collection(JointTab)
  125. _, err := collection.InsertOne(context.TODO(), bson_r)
  126. if err != nil {
  127. panic(any(err))
  128. }
  129. }
  130. /*
  131. ----------------
  132. // 数据列表
  133. JointTab:2023445039284316_params.varData
  134. // 条件 jsonFind := `{"$or":[{"name":"TempSet"},{"value":"26"}]}`
  135. // 排序 jsonSort := `{"value": 1}`
  136. // 当前页码 page := 2
  137. // 每页文档数量 pageSize := 2
  138. */
  139. func Data_List(JointTab, jsonFind, jsonSort string, page, pageSize int) lib.JSONS {
  140. var err error
  141. // 初始化 Mongodb_DB
  142. collection := Mongodb_DB.Collection(JointTab)
  143. if page < 1 {
  144. page = 1
  145. }
  146. // 限制 过小、过大
  147. if pageSize < 1 || pageSize > 9999 {
  148. page = 10
  149. }
  150. // 分页
  151. options := options.Find().SetSkip(int64((page - 1) * pageSize)).SetLimit(int64(pageSize))
  152. // 排序
  153. if len(jsonSort) != 0 {
  154. // 解码JSON
  155. var jsonSortMap map[string]interface{}
  156. err = json.Unmarshal([]byte(jsonSort), &jsonSortMap)
  157. if err != nil {
  158. logs.PrintlnError("解码JSON 错误", err)
  159. return lib.JSONS{Code: lib.Error, Msg: "排序 解码JSON 错误!"}
  160. }
  161. options = options.SetSort(bson.M(jsonSortMap))
  162. }
  163. // 条件
  164. jsonFind_M := bson.M{}
  165. if len(jsonFind) != 0 {
  166. // 解码JSON
  167. var jsonFindMap map[string]interface{}
  168. err = json.Unmarshal([]byte(jsonFind), &jsonFindMap)
  169. if err != nil {
  170. logs.PrintlnError("解码JSON 错误", err)
  171. return lib.JSONS{Code: lib.Error, Msg: "条件 解码JSON 错误!"}
  172. }
  173. jsonFind_M = jsonFindMap
  174. }
  175. cursor, err := collection.Find(context.Background(), jsonFind_M, options)
  176. if err != nil {
  177. logs.PrintlnError("Find 错误", err)
  178. return lib.JSONS{Code: lib.Error, Msg: "Find 错误!"}
  179. }
  180. defer cursor.Close(context.Background())
  181. var results []bson.M
  182. if err = cursor.All(context.Background(), &results); err != nil {
  183. logs.PrintlnError("cursor.All 错误", err)
  184. return lib.JSONS{Code: lib.Error, Msg: "cursor.All 错误!"}
  185. }
  186. // 执行计数操作
  187. count, err := collection.CountDocuments(context.Background(), jsonFind_M)
  188. if err != nil {
  189. logs.PrintlnError("Count 错误", err)
  190. return lib.JSONS{Code: lib.Error, Msg: "Count 错误!"}
  191. }
  192. return lib.JSONS{
  193. Code: lib.Success,
  194. Msg: "ok!",
  195. List: results,
  196. Total: int16(count),
  197. PageIndex: page,
  198. PageSize: pageSize,
  199. }
  200. }