2 * Copyright (c) 2010-2020 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.io.transport.modbus;
15 import org.apache.commons.lang.builder.StandardToStringStyle;
16 import org.apache.commons.lang.builder.ToStringBuilder;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
20 * Implementation for writing registers
22 * @author Sami Salonen - Initial contribution
26 public class ModbusWriteRegisterRequestBlueprint extends ModbusWriteRequestBlueprint {
28 private static StandardToStringStyle toStringStyle = new StandardToStringStyle();
31 toStringStyle.setUseShortClassName(true);
34 private final int slaveId;
35 private final int reference;
36 private final ModbusRegisterArray registers;
37 private final boolean writeMultiple;
38 private final int maxTries;
41 * Construct coil write request with many bits of data
43 * @param slaveId slave id to write to
44 * @param reference reference address
45 * @param registers register(s) to write
46 * @param writeMultiple whether to use {@link ModbusWriteFunctionCode.WRITE_MULTIPLE_COILS} over
47 * {@link ModbusWriteFunctionCode.WRITE_COIL}. Useful with single register of data.
48 * @param maxTries maximum number of tries in case of errors, should be at least 1
49 * @throws IllegalArgumentException in case <code>data</code> is empty, <code>writeMultiple</code> is
50 * <code>false</code> but there are many registers to write.
52 public ModbusWriteRegisterRequestBlueprint(int slaveId, int reference, ModbusRegisterArray registers,
53 boolean writeMultiple, int maxTries) throws IllegalArgumentException {
55 this.slaveId = slaveId;
56 this.reference = reference;
57 this.registers = registers;
58 this.writeMultiple = writeMultiple;
59 this.maxTries = maxTries;
61 if (!writeMultiple && registers.size() > 1) {
62 throw new IllegalArgumentException("With multiple registers, writeMultiple must be true");
64 if (registers.size() == 0) {
65 throw new IllegalArgumentException("Must have at least one register");
68 throw new IllegalArgumentException("maxTries should be positive");
73 public int getReference() {
78 public int getUnitID() {
83 public ModbusWriteFunctionCode getFunctionCode() {
84 return writeMultiple ? ModbusWriteFunctionCode.WRITE_MULTIPLE_REGISTERS
85 : ModbusWriteFunctionCode.WRITE_SINGLE_REGISTER;
88 public ModbusRegisterArray getRegisters() {
93 public int getMaxTries() {
98 public String toString() {
99 return new ToStringBuilder(this, toStringStyle).append("slaveId", slaveId).append("reference", reference)
100 .append("functionCode", getFunctionCode()).append("registers", registers).append("maxTries", maxTries)
105 public void accept(ModbusWriteRequestBlueprintVisitor visitor) {