package main import ( "fmt" "log/slog" "os" "time" "joylink.club/iot/config" "joylink.club/iot/mqtt" mproto "joylink.club/iot/mqtt/proto" "joylink.club/iot/service" "joylink.club/iot/service/proto" ) func main() { // slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{ // Level: slog.LevelDebug, // AddSource: false, // }))) config.LoadConfig() mqttcfg := config.Cfg.Mqtt cmc := &mqtt.IotMqttConfig{ AppId: mqttcfg.Topic.App, BrokerUrl: mqttcfg.Address, ClientId: mqttcfg.ClientId, Username: mqttcfg.Username, Password: mqttcfg.Password, KeepAlive: mqttcfg.KeepAlive, ConnectRetryDelay: mqttcfg.ConnectRetryDelay, ConnectTimeout: mqttcfg.ConnectTimeout, } err := mqtt.Start(cmc) if err != nil { slog.Error("启动MQTT客户端失败", "error", err) os.Exit(1) } time.Sleep(time.Second * 3) go func() { for { time.Sleep(time.Second) mqtt.PubIotServiceState(&mproto.IotServiceState{ Code: config.Cfg.Mqtt.ClientId, State: mproto.ServiceState_Normal, }) } }() mds, err := service.NewModbusQcService(&proto.ModbusConfig{ Url: "tcp://127.0.0.1:502", UnitId: 1, 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, }, }, }, make([]byte, 2), make([]byte, 2)) if err != nil { panic(err) } go func() { i := 0 for { c := mds.GetCjBytes() fmt.Printf("采集数据: %v\n", c) i++ if i%3 == 0 { idx := i % 8 err := mds.WriteQdBytes([]byte{byte(1 << idx), byte(3 << idx)}) if err != nil { slog.Error("设置驱动数据失败", "error", err) } else { fmt.Printf("设置驱动数据成功: %v\n", mds.GetQdBytes()) } } time.Sleep(time.Second) } }() time.Sleep(time.Minute) mds.Stop() }