123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- package cache
- import (
- "github.com/go-redis/redis"
- "github.com/sirupsen/logrus"
- "iot_manager_service/config"
- "iot_manager_service/util/common"
- "strconv"
- "time"
- )
- var Redis *redis.Client
- func InitRedis() error {
- cfg := config.Instance()
- addr := cfg.Redis.Host
- Redis = redis.NewClient(&redis.Options{
- Addr: addr,
- DialTimeout: 10 * time.Second,
- ReadTimeout: 30 * time.Second,
- WriteTimeout: 30 * time.Second,
- PoolSize: 10,
- PoolTimeout: 30 * time.Second,
- Password: cfg.Redis.Password,
- DB: 1, //指定 哪个数据库,不然找不到数据
- })
- _, err := Redis.Ping().Result()
- if err != nil {
- return err
- }
- return nil
- }
- const (
- DeviceStateKey = "dev_stat_"
- ONLINE = "online"
- TLast = "tlast"
- DeviceDataKey = "dev_data_"
- TIME = "time"
- )
- // GetDeviceState 获取设备状态 1在线 2离线
- func GetDeviceState(id string) (retTime time.Time, retState string) {
- defer func() {
- if err1 := recover(); err1 != nil {
- logrus.Errorln("GetDeviceState err = ", err1)
- }
- }()
- retTime = time.Time{}
- retState = "2"
- //redis中 1在线 0离线
- //todo 需要统一
- list, err := Redis.HMGet(DeviceStateKey+id, TLast, ONLINE).Result()
- if err == nil && list[0] != nil || list[1] != nil {
- t, err1 := common.MlParseTime(list[0].(string))
- s, err0 := strconv.Atoi(list[1].(string))
- if err0 == nil && err1 == nil {
- if s == 1 {
- retState = "1"
- }
- retTime = t
- }
- }
- return
- }
- // GetSwitchState 查灯是否开关
- func GetSwitchState(id string) bool {
- _, values := GetDeviceData(id)
- value, ok := values[1]
- if ok && value > 1 {
- return true
- }
- return false
- }
- // GetDeviceData 获取设备数据 时间 key-value
- func GetDeviceData(id string) (retTime time.Time, values map[int]float32) {
- values = make(map[int]float32)
- if mapData, err := Redis.HGetAll(DeviceDataKey + id).Result(); err == nil {
- for k, v1 := range mapData {
- if k == TIME {
- if t, err := common.MlParseTime(v1); err == nil {
- retTime = t
- }
- } else {
- if sid, err := strconv.Atoi(k); err == nil {
- if val, err := strconv.ParseFloat(v1, 32); err == nil {
- values[sid] = float32(val)
- }
- }
- }
- }
- }
- return
- }
- // 取led信息屏
- func GetDeviceLedData(id string) (values map[string]interface{}) {
- values = make(map[string]interface{})
- if mapData, err := Redis.HGetAll(DeviceDataKey + id).Result(); err == nil {
- for k, v1 := range mapData {
- values[k] = (v1)
- }
- }
- return
- }
|