func (this ModbusRTUConnection) ReadHoldings(slave int8, startAddr int, nb int) ([]uint16, error) {
	if C.modbus_set_slave(this.ctx, C.int(slave)) != 0 {
		return nil, errors.New(fmt.Sprintf("Invalid slave id %d", slave))
	}

	var space [65535]C.uint16_t

	this.ProcessHook(RTU_03_LEN)
	if ressived := C.modbus_read_registers(this.ctx, C.int(startAddr),
		C.int(nb), &(space[0])); int(ressived) != nb {
		if ressived == -1 {
			errno := C.getErrno()
			if errno == C.EMBMDATA {
				return nil, errors.New(C.GoString(C.modbus_strerror(errno)))
			}
			return nil, errors.New(fmt.Sprintf("Unknown modbus error errno=%d", errno))
		} else if ressived == 0 {
			return nil, errors.New("No ansver ressived")
		}
	} else {
		result := make([]uint16, ressived)
		for i := 0; i < int(ressived); i++ {
			result[i] = uint16(space[i])
		}
		return result, nil
	}

	return nil, nil
}
Exemplo n.º 2
0
// The modbus_read_registers() function shall read the content of the nb holding registers to the address addr of the remote device. The result of reading is stored in dest array as word values (16 bits).
// You must take care to allocate enough memory to store the results in dest (at least nb * sizeof(uint16_t)).
// The function uses the Modbus function code 0x03 (read holding registers).
func (this *RtuConnection) Read_registers(addr int, nb int) ([]uint16, error) {
	ioresult := make([]C.uint16_t, nb)

	res, errno := C.modbus_read_registers(this.ctx, C.int(addr), C.int(nb), &ioresult[0])
	if int(res) == nb {
		result := make([]uint16, int(res))
		for i := 0; i < int(res); i++ {
			result[i] = uint16(ioresult[i])
		}
		return result, nil
	} else {
		return nil, errors.New(modbus_strerror(errno))
	}
}