You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go_mqtt/main_hwy.go

230 lines
7.8 KiB
Go

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package main
import (
"encoding/base64"
"encoding/json"
"fmt"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/google/uuid"
"go_mqtt/models"
"strings"
"time"
)
func timing01(client mqtt.Client) {
//定时器10秒钟执行一次
ticker := time.NewTicker(10 * time.Second)
for {
time := <-ticker.C
fmt.Println("定时器====>", time.String())
if !client.IsConnectionOpen() {
client.Connect()
} else {
fmt.Println("client has connect")
}
}
}
var messagePubHandler01 mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
fmt.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
message := fmt.Sprintf("%s", msg.Payload())
topic := fmt.Sprintf("%s", msg.Topic())
fmt.Println(message)
fmt.Println(topic)
//privatePath := "/Users/edao/GolandProjects/go_mqtt/privateKey.pem"
privateKeyPEM := `-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCYwvInDUICXbmWcOAR5hm86mz7WlKL3dDf12MSeIY2jm5QpUSSoMhrJOWLbOt5fXQepPaNO0M30A+3C4SFZrM/9WA5ehazO1u1m1LAkYzoSDRH3MMJsrJC3lCGDeOROteu+safuP9k/npU1YQu/+Ll2xEJNxyvUx4jLGM4LamiMI6ytM3gdnOAGP4YRQo9Etwo6I986yg/seCQC5rza9M4iBamoin7U8h9yOMKrM6xK/k9CcY/vn5+Uhe3Pvk4qj/2Ff3OXkkc1wfdILqdLwLOKL0Tb3ZciwG0p1CKO80yf5hyYoWjqZk5Rcd07nTo2gqTFGfLl9sqI9/+ipMDtnHlAgMBAAECggEATJd5yCC6lusdMRO5FOBUyUaUi9X2i1AU+RZKAynQySvSnbavU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uDMoYJNI2Cf/cZifsv7vUL8cbLn+lPsKsebiuB0m0g4P2qLwLfegfNGEgA7lA5HIz3SELqbdp3iuqJeQl1fsJqD74
-----END PRIVATE KEY-----`
if topic == "app_push" {
fmt.Println("珠海电厂APP收到mqtt消息")
decodeByte, err := base64.StdEncoding.DecodeString(message)
if err != nil {
fmt.Println(err.Error())
}
//decrptCode := RSA_Decrypts(decodeByte, privatePath)
decrptCode := RSA_DecryptsOne(decodeByte, privateKeyPEM)
fmt.Println("解密后的字符串:")
fmt.Println(string(decrptCode))
fmt.Println("-----user--------")
var user models.User
json.Unmarshal(decrptCode, &user)
fmt.Println(user)
if models.GetUser(&user) {
models.UpdateUser(&user)
} else {
models.SaveUser(&user)
}
} else if topic == "app_push_dyw" {
fmt.Println("大亚湾电厂APP收到mqtt消息")
decodeByte, err := base64.StdEncoding.DecodeString(message)
if err != nil {
fmt.Println(err.Error())
}
decrptCode := RSA_DecryptsOne(decodeByte, privateKeyPEM)
fmt.Println("解密后的字符串:")
fmt.Println(string(decrptCode))
fmt.Println("-----userdyw--------")
var user models.Userdyw
json.Unmarshal(decrptCode, &user)
fmt.Println(user)
if models.GetUserdyw(&user) {
models.UpdateUserdyw(&user)
} else {
models.SaveUserdyw(&user)
}
} else if topic == "app_push_yf" {
fmt.Println("云浮电厂APP收到mqtt消息")
decodeByte, err := base64.StdEncoding.DecodeString(message)
if err != nil {
fmt.Println(err.Error())
}
decrptCode := RSA_DecryptsOne(decodeByte, privateKeyPEM)
fmt.Println("解密后的字符串:")
fmt.Println(string(decrptCode))
fmt.Println("-----userdyw--------")
var user models.Useryf
json.Unmarshal(decrptCode, &user)
fmt.Println(user)
if models.GetUseryf(&user) {
models.UpdateUseryf(&user)
} else {
models.SaveUseryf(&user)
}
} else {
result := strings.Split(message, " ")
fmt.Println(result[0])
fmt.Println(result[1])
now := time.Now()
fmt.Println("---------now--------")
fmt.Println(now)
temperature := new(models.Temperature)
temperature.CreateDate = now
temperature.DataDate = now.Format("2006-01-02")
temperature.DataHour = now.Format("2006-01-02 15")
temperature.DataMinute = now.Format("2006-01-02 15:04")
temperature.Humidity = result[0]
temperature.Temperature = result[1]
temperature.Topic = topic
if topic == "WifiSHT/7C87CE9CA4E6/SHT20" {
temperature.LocationDesc = "广东省珠海市高新区唐家湾镇东岸村水风三街28号501"
}
if topic == "WifiSHT/7C87CE9F5CBF/SHT20" {
temperature.LocationDesc = "广东省珠海市金湾区三灶镇百川路1号1栋1单元1508房"
}
if topic == "WifiSHT/4CEBD686B6AA/SHT20" {
temperature.LocationDesc = "广西壮族自治区崇左市天等县天等镇荣华村弄在屯113号"
}
fmt.Println("测温传感器地点:", temperature.LocationDesc)
models.SaveTemperature(temperature)
}
//uuid := uuid.New()
//models.SaveProduct()
//models.SaveUser(uuid.String())
//models.SaveOrder()
//var users []models.User
//var orders []models.Order
//var user models.User
//mydb.DB.Where("name = ?", "wenfei").First(&user)
//fmt.Println(user)
// 查询多条记录
//mydb.DB.Find(&users) // 查询所有产品信息
//mydb.DB.Order("id desc").Limit(2).Offset(0).Find(&users) // 按价格降序排序,取前 10 条记录
//fmt.Println("users:", users)
// 查询多条记录
//mydb.DB.Find(&users) // 查询所有产品信息
//mydb.DB.Where("id > ? and id < ?", 60,65).Find(&orders)
//fmt.Println("orders:", orders)
// 原生 SQL 查询
//var products []models.Product
//mydb.DB.Raw("SELECT * FROM product WHERE price > ?", 1000).Scan(&products) // 查询价格大于 1000 的产品信息
//fmt.Println("Products:", products)
}
var connectHandler01 mqtt.OnConnectHandler = func(client mqtt.Client) {
fmt.Println("Connected")
subTemperature01(client)
subAppPush01(client)
subAppPushDyw01(client)
subAppPushYf01(client)
}
var connectLostHandler01 mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
fmt.Printf("Connect lost: %v", err)
}
func subTemperature01(client mqtt.Client) {
topic := "WifiSHT/+/SHT20"
token := client.Subscribe(topic, 2, nil)
token.Wait()
fmt.Printf("Subscribed to topic: %s", topic)
}
func subAppPush01(client mqtt.Client) {
topic := "app_push"
token := client.Subscribe(topic, 2, nil)
token.Wait()
fmt.Printf("Subscribed to topic: %s", topic)
}
func subAppPushDyw01(client mqtt.Client) {
topic := "app_push_dyw"
token := client.Subscribe(topic, 2, nil)
token.Wait()
fmt.Printf("Subscribed to topic: %s", topic)
}
func subAppPushYf01(client mqtt.Client) {
topic := "app_push_yf"
token := client.Subscribe(topic, 2, nil)
token.Wait()
fmt.Printf("Subscribed to topic: %s", topic)
}
func main() {
uuid := uuid.New()
fmt.Println("Generated UUID:", uuid)
var broker = "mqtt.fileview123.com"
var port = 1883
opts := mqtt.NewClientOptions()
opts.AddBroker(fmt.Sprintf("tcp://%s:%d", broker, port))
opts.SetClientID(uuid.String())
opts.SetUsername("admin")
opts.SetPassword("publish452131wW452131wW$")
opts.SetDefaultPublishHandler(messagePubHandler01)
opts.OnConnect = connectHandler01
opts.OnConnectionLost = connectLostHandler01
client := mqtt.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
}
go timing01(client)
subTemperature01(client)
subAppPush01(client)
subAppPushDyw01(client)
subAppPushYf01(client)
for true {
time.Sleep(5 * time.Second)
}
}