qixiaoning
2025-07-08 84d2ef9760af0a4a4aa933937294400b3caa291d
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
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)
                }
            }
        }
    }
}