Skip to content

Commit

Permalink
feat:优化网关心跳发送时机
Browse files Browse the repository at this point in the history
  • Loading branch information
microrain authored and microrain committed May 29, 2024
1 parent 5104e2c commit 3cc108f
Showing 1 changed file with 30 additions and 21 deletions.
51 changes: 30 additions & 21 deletions gateway.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,34 +118,43 @@ func (gw *gateway) heartbeat(duration time.Duration) {
duration = 60
}
ticker := time.NewTicker(time.Second * duration)
//defer ticker.Stop()

// 立即发送一次心跳消息
gw.sendHeartbeat()

for {
select {
case <-ticker.C:
//设备数量
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 {
log.Error("publish error: %s", token.Error())
}
// 发送心跳消息
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 {
log.Error("publish error: %s", token.Error())
}
}

// SubscribeDeviceUpData 在mqtt网络类型的设备情况下,订阅设备上传数据
func (gw *gateway) SubscribeDeviceUpData() {
if gw.MQTTClient == nil || !gw.MQTTClient.IsConnected() {
Expand Down

0 comments on commit 3cc108f

Please sign in to comment.