forked from ruizeng/pando-cloud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
online.go
117 lines (99 loc) · 2.29 KB
/
online.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
// package online manage device online state and store it in redis.
package online
import (
"errors"
"github.com/PandoCloud/pando-cloud/pkg/redispool"
"github.com/PandoCloud/pando-cloud/pkg/serializer"
"github.com/garyburd/redigo/redis"
"strconv"
)
const (
OnlineStatusKeyPrefix = "device:onlinestatus:"
)
type Status struct {
ClientIP string
AccessRPCHost string
HeartbeatInterval uint32
}
type Manager struct {
redishost string
}
func NewManager(host string) *Manager {
mgr := &Manager{
redishost: host,
}
return mgr
}
func (mgr *Manager) GetStatus(id uint64) (*Status, error) {
key := OnlineStatusKeyPrefix + strconv.FormatUint(id, 10)
conn, err := redispool.GetClient(mgr.redishost)
if err != nil {
return nil, err
}
status := &Status{}
// get status from redis
bufferStr, err := redis.String(conn.Do("GET", key))
if err != nil {
return nil, err
}
err = serializer.String2Struct(bufferStr, status)
if err != nil {
return nil, err
}
return status, nil
}
func (mgr *Manager) GetOnline(id uint64, status Status) error {
key := OnlineStatusKeyPrefix + strconv.FormatUint(id, 10)
conn, err := redispool.GetClient(mgr.redishost)
if err != nil {
return err
}
// serialize and store the device's online status info in redis
bufferStr, err := serializer.Struct2String(status)
if err != nil {
return err
}
_, err = conn.Do("SET", key, bufferStr)
if err != nil {
return err
}
_, err = conn.Do("EXPIRE", key, status.HeartbeatInterval+status.HeartbeatInterval/2)
if err != nil {
return err
}
return nil
}
func (mgr *Manager) SetHeartbeat(id uint64) error {
status, err := mgr.GetStatus(id)
if err != nil {
return err
}
if err != nil {
return nil
}
if status == nil {
return errors.New("device offline.")
}
key := OnlineStatusKeyPrefix + strconv.FormatUint(id, 10)
conn, err := redispool.GetClient(mgr.redishost)
if err != nil {
return err
}
_, err = conn.Do("EXPIRE", key, status.HeartbeatInterval+status.HeartbeatInterval/2)
if err != nil {
return err
}
return nil
}
func (mgr *Manager) GetOffline(id uint64) error {
key := OnlineStatusKeyPrefix + strconv.FormatUint(id, 10)
conn, err := redispool.GetClient(mgr.redishost)
if err != nil {
return err
}
_, err = conn.Do("DEL", key)
if err != nil {
return err
}
return nil
}