redis.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. package cache
  2. import (
  3. "github.com/go-redis/redis"
  4. "github.com/sirupsen/logrus"
  5. "iot_manager_service/config"
  6. "iot_manager_service/util/common"
  7. "strconv"
  8. "time"
  9. )
  10. var Redis *redis.Client
  11. func InitRedis() error {
  12. cfg := config.Instance()
  13. addr := cfg.Redis.Host
  14. Redis = redis.NewClient(&redis.Options{
  15. Addr: addr,
  16. DialTimeout: 10 * time.Second,
  17. ReadTimeout: 30 * time.Second,
  18. WriteTimeout: 30 * time.Second,
  19. PoolSize: 10,
  20. PoolTimeout: 30 * time.Second,
  21. Password: cfg.Redis.Password,
  22. DB: 1, //指定 哪个数据库,不然找不到数据
  23. })
  24. _, err := Redis.Ping().Result()
  25. if err != nil {
  26. return err
  27. }
  28. return nil
  29. }
  30. const (
  31. DeviceStateKey = "dev_stat_"
  32. ONLINE = "online"
  33. TLast = "tlast"
  34. DeviceDataKey = "dev_data_"
  35. TIME = "time"
  36. )
  37. // GetDeviceState 获取设备状态 1在线 2离线
  38. func GetDeviceState(id string) (retTime time.Time, retState string) {
  39. defer func() {
  40. if err1 := recover(); err1 != nil {
  41. logrus.Errorln("GetDeviceState err = ", err1)
  42. }
  43. }()
  44. retTime = time.Time{}
  45. retState = "2"
  46. //redis中 1在线 0离线
  47. //todo 需要统一
  48. list, err := Redis.HMGet(DeviceStateKey+id, TLast, ONLINE).Result()
  49. if err == nil && list[0] != nil || list[1] != nil {
  50. t, err1 := common.MlParseTime(list[0].(string))
  51. s, err0 := strconv.Atoi(list[1].(string))
  52. if err0 == nil && err1 == nil {
  53. if s == 1 {
  54. retState = "1"
  55. }
  56. retTime = t
  57. }
  58. }
  59. return
  60. }
  61. // GetSwitchState 查灯是否开关
  62. func GetSwitchState(id string) bool {
  63. _, values := GetDeviceData(id)
  64. value, ok := values[1]
  65. if ok && value > 1 {
  66. return true
  67. }
  68. return false
  69. }
  70. // GetDeviceData 获取设备数据 时间 key-value
  71. func GetDeviceData(id string) (retTime time.Time, values map[int]float32) {
  72. values = make(map[int]float32)
  73. if mapData, err := Redis.HGetAll(DeviceDataKey + id).Result(); err == nil {
  74. for k, v1 := range mapData {
  75. if k == TIME {
  76. if t, err := common.MlParseTime(v1); err == nil {
  77. retTime = t
  78. }
  79. } else {
  80. if sid, err := strconv.Atoi(k); err == nil {
  81. if val, err := strconv.ParseFloat(v1, 32); err == nil {
  82. values[sid] = float32(val)
  83. }
  84. }
  85. }
  86. }
  87. }
  88. return
  89. }
  90. // 取led信息屏
  91. func GetDeviceLedData(id string) (values map[string]interface{}) {
  92. values = make(map[string]interface{})
  93. if mapData, err := Redis.HGetAll(DeviceDataKey + id).Result(); err == nil {
  94. for k, v1 := range mapData {
  95. values[k] = (v1)
  96. }
  97. }
  98. return
  99. }