func (this ModbusRTUConnection) ReadCoils(slave int8, startAddr int, nb int) ([]bool, 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.uint8_t

	this.ProcessHook(RTU_01_LEN)
	if ressived := C.modbus_read_bits(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([]bool, ressived)
		for i := 0; i < int(ressived); i++ {
			if space[i] != C.FALSE {
				result[i] = true
			}
		}
		return result, nil
	}

	return nil, nil
}
Example #2
0
// The modbus_read_bits() function shall read the status of the nb bits (coils) to the address addr of the remote device. The result of reading is stored in dest array as unsigned bytes (8 bits) set to TRUE or FALSE.
// You must take care to allocate enough memory to store the results in dest (at least nb * sizeof(uint8_t)).
// The function uses the Modbus function code 0x01 (read coil status).
func (this *RtuConnection) Read_bits(addr int, nb int) ([]bool, error) {
	ioresult := make([]C.uint8_t, nb)

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