package service
|
|
import (
|
"time"
|
"vamicro/config"
|
"vamicro/saas-service/service/nodeService"
|
|
"basic.com/valib/go-aiot.git/aiotProto/aiot"
|
"basic.com/valib/go-aiot.git/client"
|
"basic.com/valib/logger.git"
|
"go.uber.org/zap"
|
)
|
|
const DefaultNetRetry = 15 * time.Second
|
|
var CliSrv tcpCli
|
|
type tcpCli struct {
|
Cli *client.Client
|
IsMaster bool
|
}
|
|
func StartSrv(log *zap.SugaredLogger) {
|
// 初始化节点
|
nodeList := make([]*aiot.DeviceNode, 0)
|
if len(nodeService.Node.NodeLists) > 0 {
|
for _, node := range nodeService.Node.NodeLists {
|
deviceNode := &aiot.DeviceNode{}
|
deviceNode.DeviceId = node.NodeId
|
nodeList = append(nodeList, deviceNode)
|
}
|
}
|
deviceRegister := &aiot.DeviceRegister{
|
DeviceId: nodeService.Node.NodeId,
|
ServerName: config.Server.ServerName,
|
ClusterId: nodeService.Node.ClusterId,
|
ClusterName: nodeService.Node.ClusterName,
|
VirtualIp: nodeService.Node.VirtualIp,
|
DeviceList: nodeList,
|
}
|
CliSrv.Cli = client.NewClient(config.ClusterSet.SaasReportUrl, nodeService.Node.NodeId, deviceRegister, cliCon, log)
|
CliSrv.IsMaster = nodeService.Node.IsMaster
|
if nodeService.Node.IsMaster {
|
CliSrv.Cli.InitClient()
|
CliSrv.Cli.StartSrv()
|
} else {
|
CliSrv.Cli.SetState(client.StateDisconnected)
|
}
|
}
|
|
func WatchSrv(log *zap.SugaredLogger) {
|
ticker := time.NewTicker(DefaultNetRetry)
|
for {
|
select {
|
case <-ticker.C:
|
CliSrv.IsMaster = nodeService.Node.IsMaster
|
if !nodeService.Node.IsMaster {
|
// 非主节点
|
logger.Debug("client is not master... ", nodeService.Node.NodeId)
|
// 已连接,则强制断开
|
if CliSrv.Cli != nil && !CliSrv.Cli.IsClosed() && CliSrv.Cli.GetState() != client.StateInit {
|
CliSrv.Cli.Close()
|
}
|
} else {
|
// 是主节点
|
logger.Debug("client is is master connect status: ", CliSrv.Cli.GetState())
|
// 启动服务
|
if !CliSrv.Cli.IsConnected() {
|
go StartSrv(log)
|
}
|
}
|
}
|
}
|
}
|