-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathgateway.go
225 lines (203 loc) · 6.77 KB
/
gateway.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package iotgateway
import (
"context"
"fmt"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/gogf/gf/v2/encoding/gjson"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/glog"
"github.com/gogf/gf/v2/util/gconv"
"github.com/gogf/gf/v2/util/guid"
"github.com/gookit/event"
"github.com/sagoo-cloud/iotgateway/conf"
"github.com/sagoo-cloud/iotgateway/consts"
"github.com/sagoo-cloud/iotgateway/events"
"github.com/sagoo-cloud/iotgateway/log"
"github.com/sagoo-cloud/iotgateway/mqttClient"
"github.com/sagoo-cloud/iotgateway/mqttProtocol"
"github.com/sagoo-cloud/iotgateway/network"
"github.com/sagoo-cloud/iotgateway/vars"
"github.com/sagoo-cloud/iotgateway/version"
"strings"
"time"
)
const (
propertyTopic = "/sys/%s/%s/thing/event/property/pack/post"
serviceTopic = "/sys/+/%s/thing/service/#"
setTopic = "/sys/+/%s/thing/service/property/set"
)
type Gateway struct {
Address string
Version string
Status string
ctx context.Context // 上下文
options *conf.GatewayConfig
MQTTClient mqtt.Client
Server network.NetworkServer
Protocol network.ProtocolHandler
cancel context.CancelFunc
}
var ServerGateway *Gateway
func NewGateway(ctx context.Context, protocol network.ProtocolHandler) (gw *Gateway, err error) {
//读取配置文件
options := new(conf.GatewayConfig)
confData, err := g.Cfg().Data(ctx)
if err != nil {
glog.Debug(context.Background(), "读取配置文件失败", err)
return
}
err = gconv.Scan(confData, options)
if err != nil {
glog.Error(ctx, "读取配置文件失败", err)
return
}
options.MqttConfig.ClientId = options.GatewayServerConfig.DeviceKey
client, err := mqttClient.GetMQTTClient(options.MqttConfig) //初始化mqtt客户端
if err != nil {
log.Debug("mqttClient.GetMQTTClient error:", err)
}
if options.GatewayServerConfig.NetType == "" {
options.GatewayServerConfig.NetType = consts.NetTypeTcpServer
}
vars.GatewayServerConfig = options.GatewayServerConfig
gw = &Gateway{
options: options,
Address: options.GatewayServerConfig.Addr,
MQTTClient: client, // will be set later
Server: nil,
Protocol: protocol,
}
gw.ctx, gw.cancel = context.WithCancel(context.Background())
defer gw.cancel()
//初始化事件
defer func() {
err := event.CloseWait()
if err != nil {
glog.Debugf(context.Background(), "event.CloseWait() error: %s", err.Error())
}
}()
events.LoadingPublishEvent() //加载发布事件
ServerGateway = gw
return
}
func (gw *Gateway) Start() {
name := gw.options.GatewayServerConfig.Name
if name == "" {
name = "SagooIoT Gateway Server"
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
//订阅网关设备服务下发事件
gw.SubscribeServiceEvent(gw.options.GatewayServerConfig.DeviceKey)
go gw.heartbeat(gw.options.GatewayServerConfig.Duration) //启动心跳
switch gw.options.GatewayServerConfig.NetType {
case consts.NetTypeTcpServer:
// 创建 TCP 服务器
gw.Server = network.NewTCPServer(
network.WithTimeout(1*time.Minute),
network.WithProtocolHandler(gw.Protocol),
network.WithCleanupInterval(5*time.Minute),
network.WithPacketHandling(network.PacketConfig{Type: network.Delimiter, Delimiter: "\r\n"}),
)
glog.Infof(ctx, "%s started Tcp listening on %v", name, gw.options.GatewayServerConfig.Addr)
// 启动 TCP 服务器
if err := gw.Server.Start(ctx, gw.options.GatewayServerConfig.Addr); err != nil {
log.Info("TCP 服务器错误: %v", err)
}
case consts.NetTypeUDPServer:
// 创建 UDP 服务器
gw.Server = network.NewUDPServer(
network.WithTimeout(1*time.Minute),
network.WithProtocolHandler(gw.Protocol),
network.WithCleanupInterval(5*time.Minute),
)
glog.Infof(ctx, "%s started UDP listening on %v", name, gw.options.GatewayServerConfig.Addr)
// 启动 UDP 服务器
if err := gw.Server.Start(ctx, gw.options.GatewayServerConfig.Addr); err != nil {
log.Info("UDP 服务器错误: %v", err)
}
case consts.NetTypeMqttServer:
//启动mqtt类型的设备网关服务
glog.Infof(context.Background(), "%s started listening ......", name)
//log.Info("%s started listening ......")
gw.SubscribeDeviceUpData()
select {}
}
return
}
// heartbeat 网关服务心跳
func (gw *Gateway) heartbeat(duration time.Duration) {
if duration == 0 {
duration = 60
}
ticker := time.NewTicker(time.Second * duration)
// 立即发送一次心跳消息
gw.sendHeartbeat()
for {
select {
case <-ticker.C:
// 发送心跳消息
gw.sendHeartbeat()
}
}
}
// sendHeartbeat 发送心跳消息
func (gw *Gateway) sendHeartbeat() {
// 设备数量
versionInfo := version.GetVersion()
if versionInfo == "" || versionInfo == "0.0" {
versionInfo = "v0.0.1"
}
count := vars.CountDevices()
builder := mqttProtocol.NewGatewayBatchReqBuilder().SetId(guid.S())
builder.SetVersion("1.0")
builder.AddProperty("Status", 0)
builder.AddProperty("Count", count)
builder.AddProperty("Version", versionInfo)
builder.SetMethod("thing.event.property.pack.post")
data := gconv.Map(builder.Build())
outData := gjson.New(data).MustToJson()
topic := fmt.Sprintf(propertyTopic, vars.GatewayServerConfig.ProductKey, vars.GatewayServerConfig.DeviceKey)
glog.Debugf(context.Background(), "网关向平台发送心跳数据:%s", string(outData))
token := gw.MQTTClient.Publish(topic, 1, false, outData)
if token.Error() != nil {
glog.Errorf(context.Background(), "publish error: %s", token.Error())
}
}
// SubscribeDeviceUpData 在mqtt网络类型的设备情况下,订阅设备上传数据
func (gw *Gateway) SubscribeDeviceUpData() {
if gw.MQTTClient == nil || !gw.MQTTClient.IsConnected() {
log.Error("Client has lost connection with the MQTT broker.")
return
}
log.Debug("订阅设备上传数据topic: ", gw.options.GatewayServerConfig.SerUpTopic)
if gw.options.GatewayServerConfig.SerUpTopic != "" {
token := gw.MQTTClient.Subscribe(gw.options.GatewayServerConfig.SerUpTopic, 1, onDeviceUpDataMessage)
if token.Error() != nil {
log.Debug("subscribe error: ", token.Error())
}
}
}
// onDeviceUpDataMessage 设备上传数据
var onDeviceUpDataMessage mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
//忽略_reply结尾的topic
if strings.HasSuffix(msg.Topic(), "_reply") {
return
}
if msg != nil {
ServerGateway.Protocol.Decode(nil, msg.Payload())
}
}
// DeviceDownData 在mqtt网络类型的设备情况下,向设备下发数据
func (gw *Gateway) DeviceDownData(data interface{}) {
if gw.MQTTClient == nil || !gw.MQTTClient.IsConnected() {
log.Error("Client has lost connection with the MQTT broker.")
return
}
if gw.options.GatewayServerConfig.SerDownTopic != "" {
token := gw.MQTTClient.Publish(gw.options.GatewayServerConfig.SerDownTopic, 1, false, data)
if token.Error() != nil {
log.Error("publish error: %s", token.Error())
}
}
}