package main import ( "fmt" "log/slog" "time" "joylink.club/iot/dto" "joylink.club/iot/service" ) // 作为依赖包使用例子 func main() { // slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{ // Level: slog.LevelDebug, // AddSource: false, // }))) modbusCfg := &dto.ModbusConfig{ Url: "tcp://127.0.0.1:502", UnitId: 2, Timeout: 500, Interval: 1000, Qdl: 2, // 驱动数据字节数 Cjl: 2, // 采集数据字节数 Mapping: []*dto.ModbusDcMapping{ { // Function: proto.Modbus_ReadHoldingRegister, Function: dto.Modbus_ReadCoil, Addr: 0, Quantity: 16, Type: dto.DataType_CJ, Start: 0, }, { Function: dto.Modbus_RWCoils, Addr: 16, Quantity: 16, Type: dto.DataType_QD, Start: 0, }, }, } mds, err := service.NewModbusQcService(modbusCfg) if err != nil { panic(err) } i := 0 mds.RegisterQcDataHandleScheduleTask(func() { 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.Second) time.Sleep(time.Minute) mds.Stop() }