DeviceData.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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 DeviceData_Form struct {
  31. T_sn string `json:"T_sn" form:"T_sn"` // Sn
  32. T_jointTab string `json:"T_jointTab" form:"T_jointTab"` // 标签路径
  33. T_jsonFind string `json:"T_jsonFind" form:"T_jsonFind"` // 条件
  34. T_jsonSort string `json:"T_jsonSort" form:"T_jsonSort"` // 排序
  35. PageIndex int `json:"PageIndex" form:"PageIndex"` // 当前页码
  36. PageSize int `json:"PageSize" form:"PageSize"` // 每页文档数量
  37. }
  38. var redis_DeviceData cache.Cache
  39. var Mongodb_client *mongo.Client
  40. var Mongodb_DB *mongo.Database
  41. func init() {
  42. credential := options.Credential{
  43. //AuthSource: conf.Mongodb_DB,
  44. Username: conf.Mongodb_Username,
  45. Password: conf.Mongodb_Password,
  46. }
  47. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  48. defer cancel()
  49. var err error
  50. Mongodb_client, err = mongo.Connect(ctx, options.Client().ApplyURI(conf.Mongodb_Url).SetAuth(credential).SetMaxPoolSize(200))
  51. if err != nil {
  52. logs.PrintlnError("Mongodb 连接错误!", err)
  53. panic(any(err))
  54. }
  55. Mongodb_DB = Mongodb_client.Database(conf.Mongodb_DB)
  56. config := fmt.Sprintf(`{"key":"%s","conn":"%s","dbNum":"%s","password":"%s"}`,
  57. "redis_DeviceData", conf.Redis_address, conf.Redis_dbNum, conf.Redis_password)
  58. logs.Println(config)
  59. redis_DeviceData, err = cache.NewCache("redis", config)
  60. if err != nil || redis_DeviceData == nil {
  61. errMsg := "failed to init redis"
  62. logs.Println(errMsg, err)
  63. }
  64. }
  65. // ---------------- Redis -------------------
  66. // Redis_Set(m.T_sn,m) // Redis 更新缓存
  67. func RedisDeviceData_Set(T_sn string, T_id int, r DeviceData_R) (err error) {
  68. key := T_sn + "|" + strconv.Itoa(T_id)
  69. if redis_DeviceData.IsExist(key) {
  70. var t DeviceData_R
  71. v := redis_DeviceData.Get(key)
  72. json.Unmarshal(v.([]byte), &t)
  73. // 防止时间溢出
  74. if time.Now().Unix() <= r.T_time.Unix() {
  75. r.T_time.NowDbTime()
  76. }
  77. // 提前最新数据
  78. if t.T_time.Unix() > r.T_time.Unix() {
  79. // 储存的 是最新数据
  80. return
  81. }
  82. }
  83. //json序列化
  84. str, err := json.Marshal(r)
  85. if err != nil {
  86. logs.PrintlnError("RedisDeviceData_Set", err)
  87. return
  88. }
  89. err = redis_DeviceData.Put(key, str, 1*time.Hour)
  90. if err != nil {
  91. logs.Println("set key:", key, ",value:", str, err)
  92. }
  93. return
  94. }
  95. func RedisDeviceData_Get(key string) (r DeviceData_R, is bool) {
  96. if redis_DeviceData.IsExist(key) {
  97. v := redis_DeviceData.Get(key)
  98. json.Unmarshal(v.([]byte), &r)
  99. return r, true
  100. }
  101. return DeviceData_R{}, false
  102. }
  103. // ----------------
  104. func Data_Add(JointTab string, bson_r *bson.M) {
  105. logs.Println("JointTab:", JointTab, *bson_r)
  106. collection := Mongodb_DB.Collection(JointTab)
  107. _, err := collection.InsertOne(context.TODO(), bson_r)
  108. if err != nil {
  109. panic(any(err))
  110. }
  111. }
  112. // db.getCollection("2023445039284316_params_varData").find({ $and : [{"name" : "TempSet"}, {"value" : "26"}] }).limit(1000).skip(0)
  113. // ----------------
  114. func Data_Read(JointTab string, bson_r *bson.M) {
  115. logs.Println("JointTab:", JointTab, *bson_r)
  116. collection := Mongodb_DB.Collection(JointTab)
  117. _, err := collection.InsertOne(context.TODO(), bson_r)
  118. if err != nil {
  119. panic(any(err))
  120. }
  121. }
  122. /*
  123. ----------------
  124. // 数据列表
  125. JointTab:2023445039284316_params_varData
  126. // 条件 jsonFind := `{"$or":[{"name":"TempSet"},{"value":"26"}]}`
  127. // 排序 jsonSort := `{"value": 1}`
  128. // 当前页码 page := 2
  129. // 每页文档数量 pageSize := 2
  130. */
  131. func Data_List(JointTab, jsonFind, jsonSort string, page, pageSize int) (JSONr lib.JSONR) {
  132. var err error
  133. // 初始化 Mongodb_DB
  134. collection := Mongodb_DB.Collection(JointTab)
  135. if page < 1 {
  136. page = 1
  137. }
  138. // 限制 过小、过大
  139. if pageSize < 1 || pageSize > 9999 {
  140. page = 10
  141. }
  142. // 分页
  143. options := options.Find().SetSkip(int64((page - 1) * pageSize)).SetLimit(int64(pageSize))
  144. // 排序
  145. if len(jsonSort) != 0 {
  146. // 解码JSON
  147. var jsonSortMap map[string]interface{}
  148. err = json.Unmarshal([]byte(jsonSort), &jsonSortMap)
  149. if err != nil {
  150. logs.PrintlnError("解码JSON 错误", err)
  151. JSONr.Code = lib.Error
  152. JSONr.Msg = "排序 解码JSON 错误!"
  153. return
  154. }
  155. options = options.SetSort(bson.M(jsonSortMap))
  156. }
  157. // 条件
  158. jsonFind_M := bson.M{}
  159. if len(jsonFind) != 0 {
  160. // 解码JSON
  161. var jsonFindMap map[string]interface{}
  162. err = json.Unmarshal([]byte(jsonFind), &jsonFindMap)
  163. if err != nil {
  164. logs.PrintlnError("解码JSON 错误", err)
  165. JSONr.Code = lib.Error
  166. JSONr.Msg = "条件 解码JSON 错误!"
  167. return
  168. }
  169. jsonFind_M = jsonFindMap
  170. }
  171. cursor, err := collection.Find(context.Background(), jsonFind_M, options)
  172. if err != nil {
  173. logs.PrintlnError("Find 错误", err)
  174. JSONr.Code = lib.Error
  175. JSONr.Msg = "Find 错误!"
  176. return
  177. }
  178. defer cursor.Close(context.Background())
  179. var results []bson.M
  180. if err = cursor.All(context.Background(), &results); err != nil {
  181. logs.PrintlnError("cursor.All 错误", err)
  182. JSONr.Code = lib.Error
  183. JSONr.Msg = "cursor.All 错误!"
  184. return
  185. }
  186. // 执行计数操作
  187. count, err := collection.CountDocuments(context.Background(), jsonFind_M)
  188. if err != nil {
  189. logs.PrintlnError("Count 错误", err)
  190. JSONr.Code = lib.Error
  191. JSONr.Msg = "Count 错误!"
  192. return
  193. }
  194. JSONr.Data = lib.JSONS{
  195. List: results,
  196. Total: int16(count),
  197. PageIndex: page,
  198. PageSize: pageSize,
  199. }
  200. JSONr.Code = lib.Success
  201. JSONr.Msg = "ok!"
  202. return
  203. }