|
| 1 | +package core |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/tls" |
| 5 | + "crypto/x509" |
| 6 | + "errors" |
| 7 | + "fmt" |
| 8 | + MQTT "github.com/eclipse/paho.mqtt.golang" |
| 9 | + "mqtts/utils" |
| 10 | + "strconv" |
| 11 | + "strings" |
| 12 | + "sync" |
| 13 | + "time" |
| 14 | +) |
| 15 | + |
| 16 | +var tmpClient = &Client{} |
| 17 | +var tmpClientLock sync.Mutex |
| 18 | + |
| 19 | +type Client struct { |
| 20 | + CurrentClient MQTT.Client |
| 21 | + ClientOptions *MQTT.ClientOptions |
| 22 | + ClientLocker *sync.Mutex |
| 23 | + MessageHandler func(client *Client, msg *Message) |
| 24 | + Certificate x509.Certificate |
| 25 | +} |
| 26 | + |
| 27 | +type Message struct { |
| 28 | + Topic string |
| 29 | + Msg string |
| 30 | +} |
| 31 | + |
| 32 | +func ConnectWithOpts(opts *TargetOptions) Client { |
| 33 | + client := GetMQTTClient(opts) |
| 34 | + connectError := client.Connect() |
| 35 | + if connectError == nil { |
| 36 | + SetClientToken(opts.Host, opts.Port, *client) |
| 37 | + return *client |
| 38 | + } else { |
| 39 | + SetClientToken(opts.Host, opts.Port, *client) |
| 40 | + utils.OutputInfoMessage(opts.Host, opts.Port, "Connect mqtt server failed err:"+connectError.Error()) |
| 41 | + return *client |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +func GenerateClientId(id string) string { |
| 46 | + return "mqttSecurityCheck" + id |
| 47 | +} |
| 48 | + |
| 49 | +func connectHandler(client MQTT.Client) { |
| 50 | + //utils.OutputInfoMessage("Connect MQTT Service Success") |
| 51 | +} |
| 52 | + |
| 53 | +func connectLostHandler(client MQTT.Client, err error) { |
| 54 | + reader := client.OptionsReader() |
| 55 | + if len(reader.Servers()) > 0 { |
| 56 | + utils.OutputErrorMessageWithoutOption("[" + reader.Servers()[0].Host + "] Loss MQTT connection") |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +func verifyPeerCertificateHandler(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error { |
| 61 | + cert, _ := x509.ParseCertificate(rawCerts[0]) |
| 62 | + tmpClient.Certificate = *cert |
| 63 | + setCertificate(tmpClient) |
| 64 | + return nil |
| 65 | +} |
| 66 | + |
| 67 | +func verifyConnectionHandler(state tls.ConnectionState) error { |
| 68 | + return nil |
| 69 | +} |
| 70 | + |
| 71 | +func GetMQTTClient(opts *TargetOptions) *Client { |
| 72 | + clientOptions := MQTT.NewClientOptions() |
| 73 | + broker := opts.Protocol + "://" + opts.Host + ":" + strconv.Itoa(opts.Port) |
| 74 | + if strings.EqualFold(opts.Protocol, "tcp") || strings.EqualFold(opts.Protocol, "ssl") { |
| 75 | + clientOptions.AddBroker(broker) |
| 76 | + } |
| 77 | + if strings.EqualFold(opts.Protocol, "ws") || strings.EqualFold(opts.Protocol, "wss") { |
| 78 | + clientOptions.AddBroker(broker + "/mqtt") |
| 79 | + } |
| 80 | + clientOptions.SetUsername(opts.UserName) |
| 81 | + clientOptions.SetPassword(opts.Password) |
| 82 | + if !strings.EqualFold(opts.ClientId, "") { |
| 83 | + clientOptions.SetClientID(opts.ClientId) |
| 84 | + } else { |
| 85 | + clientId := utils.GetRandomString(6, "string") |
| 86 | + clientOptions.SetClientID(utils.GetRandomString(6, "string")) |
| 87 | + opts.ClientId = clientId |
| 88 | + } |
| 89 | + clientOptions.SetConnectTimeout(time.Millisecond * 5000) |
| 90 | + clientOptions.SetOnConnectHandler(connectHandler) |
| 91 | + clientOptions.SetConnectionLostHandler(connectLostHandler) |
| 92 | + tlsConfig := tls.Config{ |
| 93 | + InsecureSkipVerify: true, |
| 94 | + VerifyPeerCertificate: verifyPeerCertificateHandler, |
| 95 | + VerifyConnection: verifyConnectionHandler, |
| 96 | + } |
| 97 | + clientOptions.SetTLSConfig(&tlsConfig) |
| 98 | + client := MQTT.NewClient(clientOptions) |
| 99 | + return &Client{ |
| 100 | + CurrentClient: client, |
| 101 | + ClientOptions: clientOptions, |
| 102 | + ClientLocker: &sync.Mutex{}, |
| 103 | + } |
| 104 | +} |
| 105 | + |
| 106 | +func (client *Client) Connect() error { |
| 107 | + if !client.CurrentClient.IsConnected() { |
| 108 | + client.ClientLocker.Lock() |
| 109 | + defer client.ClientLocker.Unlock() |
| 110 | + if !client.CurrentClient.IsConnected() { |
| 111 | + if token := client.CurrentClient.Connect(); token.Wait() && token.Error() != nil { |
| 112 | + client.saveCertificate(currentCertificate().Certificate) |
| 113 | + return token.Error() |
| 114 | + } else { |
| 115 | + client.saveCertificate(currentCertificate().Certificate) |
| 116 | + } |
| 117 | + } |
| 118 | + } |
| 119 | + return nil |
| 120 | +} |
| 121 | + |
| 122 | +func defaultMessageHandler(c *Client, message *Message) { |
| 123 | + fmt.Println(message.Msg) |
| 124 | +} |
| 125 | + |
| 126 | +func (client *Client) messageHandler(c MQTT.Client, message MQTT.Message) { |
| 127 | + if client.MessageHandler == nil { |
| 128 | + //utils.OutputErrorMessage("Not subscribe message") |
| 129 | + return |
| 130 | + } |
| 131 | + msg := &Message{ |
| 132 | + Topic: message.Topic(), |
| 133 | + Msg: string(message.Payload()), |
| 134 | + } |
| 135 | + client.MessageHandler(client, msg) |
| 136 | +} |
| 137 | + |
| 138 | +func (client *Client) Subscribe(handler func(c *Client, message *Message), qos byte, topics ...string) error { |
| 139 | + if client.MessageHandler != nil { |
| 140 | + return errors.New("messageHandler has been bound, have to clear messageHandler first") |
| 141 | + } |
| 142 | + |
| 143 | + if len(topics) == 0 { |
| 144 | + return errors.New("subscribe method must set topic") |
| 145 | + } |
| 146 | + |
| 147 | + if handler != nil { |
| 148 | + client.MessageHandler = handler |
| 149 | + } else { |
| 150 | + client.MessageHandler = defaultMessageHandler |
| 151 | + } |
| 152 | + |
| 153 | + filters := make(map[string]byte) |
| 154 | + for _, topic := range topics { |
| 155 | + filters[topic] = qos |
| 156 | + } |
| 157 | + client.CurrentClient.SubscribeMultiple(filters, client.messageHandler) |
| 158 | + return nil |
| 159 | +} |
| 160 | + |
| 161 | +func (client *Client) Unsubscribe(topics ...string) { |
| 162 | + client.MessageHandler = nil |
| 163 | + client.CurrentClient.Unsubscribe(topics...) |
| 164 | +} |
| 165 | + |
| 166 | +func (client *Client) saveCertificate(certificate x509.Certificate) { |
| 167 | + client.Certificate = certificate |
| 168 | +} |
| 169 | + |
| 170 | +func currentCertificate() *Client { |
| 171 | + tmpClientLock.Lock() |
| 172 | + defer tmpClientLock.Unlock() |
| 173 | + return tmpClient |
| 174 | +} |
| 175 | + |
| 176 | +func setCertificate(c *Client) { |
| 177 | + tmpClientLock.Lock() |
| 178 | + tmpClient = c |
| 179 | + tmpClientLock.Unlock() |
| 180 | +} |
0 commit comments