liuxiaolong
2022-08-25 fe74ddd6ae6e6df4d65083094401e824ee760313
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
package bhomedbapi
 
import (
    "basic.com/valib/c_bhomebus.git/proto/source/bhome_msg"
)
 
//Factory new client
/*
    跨机请求时,topic devId ip必须非空
*/
func NewClient(opts ...IOption) Client {
    opt := defaultOption()
    for _,o := range opts {
        o.apply(&opt)
    }
    if opt.ip != "" { //跨机请求
        if opt.topic == "" {
            return nil
        }
        opt.nodes = n_getNetNode(opt.topic)
        logPrint("NewClient ip:", opt.ip, " topic:", opt.topic, " nodes:", opt.nodes)
        if !checkRemoteNetNode(opt.ip, &opt.nodes) {
            return nil
        }
    }
    return &SBusClient{
        nodes: opt.nodes,
    }
}
 
 
type Option struct {
    nodes         []*bhome_msg.MsgQueryTopicReply_BHNodeAddress
    topic         string
    devId         string
    ip               string
    port         int32
}
 
type IOption interface {
    apply(*Option)
}
 
type funcOption struct {
    f func(*Option)
}
 
func (fo *funcOption) apply(o *Option) {
    fo.f(o)
}
 
func newFuncOption(f func(*Option)) *funcOption {
    return &funcOption{
        f:f,
    }
}
 
func WithNodes(nodeArr []*bhome_msg.MsgQueryTopicReply_BHNodeAddress) IOption {
    return newFuncOption(func(o *Option) {
        o.nodes = nodeArr
    })
}
 
func WithTopic(topic string) IOption {
    return newFuncOption(func(o *Option){
        o.topic = topic
    })
}
 
func WithIp(ip string) IOption {
    return newFuncOption(func(o *Option) {
        o.ip = ip
    })
}
 
func WithDevId(devId string) IOption {
    return newFuncOption(func(o *Option) {
        o.devId = devId
    })
}
 
func WithPort(port int32) IOption {
    return newFuncOption(func(o *Option) {
        o.port = port
    })
}
 
func defaultOption() Option {
    return Option{
 
    }
}
 
func checkRemoteNetNode(rip string, netNode *[]*bhome_msg.MsgQueryTopicReply_BHNodeAddress) bool {
    if netNode == nil || len(*netNode) == 0 {
        return false
    }
 
    for _,n := range *netNode {
        if n.Addr != nil && string(n.Addr.Ip) == rip && n.Addr.Port >0 {
            *netNode = append([]*bhome_msg.MsgQueryTopicReply_BHNodeAddress{}, &bhome_msg.MsgQueryTopicReply_BHNodeAddress{
                Addr: &bhome_msg.BHAddress{
                    Ip: []byte(rip),
                    Port: n.Addr.Port,
                },
            })
            return true
        }
    }
    return false
}