go 链接阿里云mqtt

package services

import (
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"github.com/pelletier/go-toml"
	"strconv"
)

var Config, _ = toml.LoadFile("./config.toml")

type Mqttservices struct {
	
}
func (ctx Mqttservices)MqttClient () {
	conn()
	checkToken()

	client.Subscribe("Test", 1, func(c mqtt.Client, message mqtt.Message) {
		fmt.Printf(message.Payload())
	})
}

var (
	broker           string
	port             int
	AccessKey_ID     string
	AccessKey_Secret string
	InstanceId       string
	client           mqtt.Client
	groupId          string

	clientId string

	connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) {
		fmt.Println("Mqtt Connect success")
	}
	connectLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
		fmt.Printf("Mqtt Connect lost: %v", err)
	}
	messagePubHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
		fmt.Printf("Mqtt Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
	}
)

func init() {
	broker =Config.Get("common.ali_mqtt.broker").(string)
	port, _ = strconv.Atoi(Config.Get("common.ali_mqtt.port").(string))
	AccessKey_ID = Config.Get("common.ali_mqtt.AccessKey_ID").(string)
	AccessKey_Secret = Config.Get("common.ali_mqtt.AccessKey_Secret").(string)
	InstanceId = Config.Get("common.ali_mqtt.InstanceId").(string)
	groupId =Config.Get("common.ali_mqtt.groupId").(string)
	clientId = groupId + "@@@" + Config.Get("common.ali_mqtt.deviceId").(string)
}

func checkToken() {
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		fmt.Println("  -- ")
		fmt.Printf(token.Error().Error())
		panic(token.Error())
	}
}

func conn() {
	opts := mqtt.NewClientOptions()
	opts.AddBroker(fmt.Sprintf("tcp://%s:%d", broker, port))
	userName := "Signature" + "|" + AccessKey_ID + "|" + InstanceId
	password := HmacSha1(AccessKey_Secret, clientId)
	opts.SetClientID(clientId)
	opts.SetUsername(userName)
	opts.SetPassword(string(Decode(password)))
	opts.SetDefaultPublishHandler(messagePubHandler)
	opts.SetAutoReconnect(true)
	opts.SetMaxReconnectInterval(3)
	opts.OnConnect = connectHandler
	opts.OnConnectionLost = connectLostHandler
	client = mqtt.NewClient(opts)
}

config.toml

[common.mqtt]
AccessKey_ID=""
AccessKey_Secret=""
InstanceId=""
broker=""
port="1883"
deviceId="6e9f1aa4195f47428c253740e412187c"
groupId=""

base64

package services

import (
	"crypto/hmac"
	"crypto/sha1"
	"encoding/base64"
	"fmt"
	"io"
)

func Encode(data string) string {

	sEnc := base64.StdEncoding.EncodeToString([]byte(data))
	fmt.Println(sEnc) //
	return sEnc
}

func Decode(data string) []byte {
	sEnc := base64.StdEncoding.EncodeToString([]byte(data))
	sDec, err := base64.StdEncoding.DecodeString(sEnc)
	if err != nil {
		fmt.Printf("Error decoding string: %s ", err.Error())
		return nil
	}
	return sDec
}

func Sha1() {
	h := sha1.New()
	io.WriteString(h, "")
	fmt.Printf("%x\n", h.Sum(nil))

	//hmac ,use sha1
	key := []byte("123456")
	mac := hmac.New(sha1.New, key)
	mac.Write([]byte(""))
	fmt.Printf("%x\n", mac.Sum(nil))
}

func HmacSha1(keyStr, value string) string {

	key := []byte(keyStr)
	mac := hmac.New(sha1.New, key)
	mac.Write([]byte(value))
	//进行base64编码
	res := base64.StdEncoding.EncodeToString(mac.Sum(nil))

	return res
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值