maskWriteRegister method

  1. @override
Future<void> maskWriteRegister(
  1. int slaveId,
  2. int address,
  3. int andMask,
  4. int orMask,
)
override

Mask write register (FC 22).

Modifies a holding register using AND and OR masks.

Formula: Result = (Current AND andMask) OR (orMask AND NOT andMask)

Parameters:

  • slaveId: The slave device ID (0-247, 0 for broadcast)
  • address: Register address
  • andMask: AND mask (16-bit)
  • orMask: OR mask (16-bit)

Example:

// Set bit 0, clear bit 1, leave others unchanged
await client.maskWriteRegister(1, 0, 0xFFFD, 0x0001);

Implementation

@override
Future<void> maskWriteRegister(
    int slaveId, int address, int andMask, int orMask) async {
  if (slaveId > _addressMax) {
    throw ArgumentError(
        'modbus: slaveId \'$slaveId\' must be between \'$addressBroadCast\' and \'$_addressMax\'');
  }

  final response = await send(
    slaveId,
    ProtocolDataUnit(
      funcCodeMaskWriteRegister,
      uint16ToBytes([address, andMask, orMask]),
    ),
  );

  if (response.data.length != 6) {
    throw Exception(
        'modbus: response data size \'${response.data.length}\' does not match expected \'6\'');
  }

  final rspAddress = bytesToUint16(response.data.sublist(0, 2))[0];
  if (rspAddress != address) {
    throw Exception(
        'modbus: response address \'$rspAddress\' does not match request \'$address\'');
  }

  final rspAndMask = bytesToUint16(response.data.sublist(2, 4))[0];
  if (rspAndMask != andMask) {
    throw Exception(
        'modbus: response AND-mask \'$rspAndMask\' does not match request \'$andMask\'');
  }

  final rspOrMask = bytesToUint16(response.data.sublist(4, 6))[0];
  if (rspOrMask != orMask) {
    throw Exception(
        'modbus: response OR-mask \'$rspOrMask\' does not match request \'$orMask\'');
  }
}