jl-iot/main.go

57 lines
1.4 KiB
Go

package main
import (
"fmt"
"time"
"joylink.club/iot/modbus"
)
func main() {
cli, err := modbus.NewClient("tcp://localhost:502")
if err != nil {
panic(err)
}
cli.Start()
// vb := false
for i := 0; i < 10; i++ {
time.Sleep(time.Second * 2)
// read a single 16-bit holding register at address 100
if i%2 == 0 {
// vb = !vb
// data := []bool{vb, !vb, vb, !vb, vb, !vb, vb, !vb}
// err := cli.WriteCoils(0, data)
// if err != nil {
// // error out
// fmt.Printf("第%d次写错误: %s\n", i, err)
// } else {
// fmt.Printf("第%d次写成功, value: %v\n", i, vb)
// }
data := []uint16{uint16(i + 1), uint16(i + 2), uint16(i + 3), uint16(i + 4), uint16(i + 5), uint16(i + 6), uint16(i + 7), uint16(i + 8)}
err := cli.WriteRegisters(0, data)
if err != nil {
// error out
fmt.Printf("第%d次写错误: %s\n", i, err)
} else {
fmt.Printf("第%d次写成功, value: %v\n", i, data)
}
} else {
// bs, err := cli.ReadCoil(0, 10)
// if err != nil {
// // error out
// fmt.Printf("第%d次读错误: %s\n", i, err)
// } else {
// fmt.Printf("第%d次读成功, value: %v\n", i, bs)
// }
bs, err := cli.ReadHoldingRegister(0, 10)
if err != nil {
// error out
fmt.Printf("第%d次读错误: %s\n", i, err)
} else {
fmt.Printf("第%d次读成功, value: %v\n", i, bs)
}
}
}
}