jl-iot/main.go

126 lines
3.1 KiB
Go

package main
import (
"fmt"
"log/slog"
"os"
"time"
"github.com/eclipse/paho.golang/autopaho"
"github.com/eclipse/paho.golang/paho"
"google.golang.org/protobuf/proto"
"joylink.club/iot/config"
"joylink.club/iot/mqtt"
mproto "joylink.club/iot/mqtt/proto"
)
func main() {
slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{
Level: slog.LevelDebug,
AddSource: false,
})))
config.LoadConfig()
mqttcfg := config.Cfg.Mqtt
mqtt.BuildTopics(mqttcfg.Topic.App, mqttcfg.ClientId)
cmc := &mqtt.ClientManageConfig{
BrokerUrl: mqttcfg.Address,
ClientId: mqttcfg.ClientId,
Username: mqttcfg.Username,
Password: mqttcfg.Password,
KeepAlive: mqttcfg.KeepAlive,
ConnectRetryDelay: mqttcfg.ConnectRetryDelay,
ConnectTimeout: mqttcfg.ConnectTimeout,
OnConnectionUp: func(*autopaho.ConnectionManager, *paho.Connack) {
slog.Info("MQTT连接成功")
// err := mqtt.SubIotServiceState(mqtt.GetIotServiceStateTopic())
// if err != nil {
// slog.Error("订阅IotServiceState失败", "error", err)
// os.Exit(1)
// }
},
}
err := mqtt.Start(cmc)
if err != nil {
slog.Error("启动MQTT客户端失败", "error", err)
os.Exit(1)
}
time.Sleep(time.Second * 3)
err = mqtt.SubIotServiceState(mqtt.GetIotServiceStateTopic())
if err != nil {
slog.Error("订阅IotServiceState失败", "error", err)
os.Exit(1)
}
i := 0
mqtt.RegisterHandler(mqtt.GetIotServiceStateTopic(), func(m *paho.Publish) {
iss := &mproto.IotServiceState{}
err := proto.Unmarshal(m.Payload, iss)
if err != nil {
slog.Error("SubIotServiceState proto.Unmarshal异常", "error", err)
return
}
slog.Debug("收到IotServiceState发布消息", "state", iss)
i++
fmt.Printf("%v次处理IotServiceState: %v\n", i, iss)
})
go func() {
for {
time.Sleep(time.Second)
mqtt.PubIotServiceState(&mproto.IotServiceState{
Code: config.Cfg.Mqtt.ClientId,
State: mproto.ServiceState_Normal,
})
}
}()
time.Sleep(time.Minute)
// dc := model.NewDC(make([]byte, 2), make([]byte, 2))
// mds, err := service.NewModbusQcService(&proto.ModbusConfig{
// Url: "tcp://127.0.0.1:502",
// UnitId: 2,
// Timeout: 500,
// Interval: 1000,
// Mapping: []*proto.ModbusDcMapping{
// {
// // Function: proto.Modbus_ReadHoldingRegister,
// Function: proto.Modbus_ReadCoil,
// Addr: 0,
// Quantity: 16,
// Type: proto.DataType_CollectTable,
// Start: 0,
// },
// {
// Function: proto.Modbus_WriteCoils,
// Addr: 16,
// Quantity: 16,
// Type: proto.DataType_DriveTable,
// WriteStrategy: proto.Modbus_OnUpdate,
// Start: 0,
// },
// },
// }, dc)
// if err != nil {
// panic(err)
// }
// go func() {
// i := 0
// for {
// c := dc.GetCollect()
// fmt.Printf("采集数据: %v\n", c)
// i++
// if i%3 == 0 {
// idx := i % 8
// dc.UpdateDriveByBytes(0, []byte{byte(1 << idx)})
// fmt.Printf("设置驱动数据: %v\n", dc.GetDrive())
// }
// time.Sleep(time.Second)
// }
// }()
// time.Sleep(time.Minute * 2)
// mds.Stop()
}