use of net.wimpi.modbus.msg.ModbusRequest in project openhab1-addons by openhab.
the class WriteCoilsAndDiscreteTestCase method verifyRequests.
private void verifyRequests(boolean readRequestExpected) throws Exception {
try {
ArrayList<ModbusRequest> requests = modbustRequestCaptor.getAllReturnValues();
int expectedDOIndex = nonZeroOffset ? (itemIndex + 1) : itemIndex;
WriteCoilRequest writeRequest;
boolean writeExpected = type == ModbusBindingProvider.TYPE_COIL;
int expectedRequests = (writeExpected ? 1 : 0) + (readRequestExpected ? 1 : 0);
// One connection per request
int expectedConnections = serverType.equals(ServerType.UDP) ? 1 : expectedRequests;
// Give the system 5 seconds to make the expected connections & requests
waitForConnectionsReceived(expectedConnections);
waitForRequests(expectedRequests);
assertThat(requests.size(), is(equalTo(expectedRequests)));
if (readRequestExpected) {
if (type == ModbusBindingProvider.TYPE_DISCRETE) {
assertThat(requests.get(0), is(instanceOf(ReadInputDiscretesRequest.class)));
} else if (type == ModbusBindingProvider.TYPE_COIL) {
assertThat(requests.get(0), is(instanceOf(ReadCoilsRequest.class)));
} else {
throw new RuntimeException();
}
}
if (writeExpected) {
assertThat(requests.get(expectedRequests - 1), is(instanceOf(WriteCoilRequest.class)));
writeRequest = (WriteCoilRequest) requests.get(expectedRequests - 1);
assertThat(writeRequest.getCoil(), is(equalTo(expectedValue)));
assertThat(writeRequest.getReference(), is(equalTo(expectedDOIndex)));
}
} catch (AssertionError e) {
System.err.println(String.format("Unexpected assertion error: discreteInitial=%s, coilInitial=%s, nonZeroOffset=%s, command=%s, itemIndex=%d, type=%s", discreteInitialValue, coilInitialValue, nonZeroOffset, command, itemIndex, type));
throw new AssertionError("Got unexpected assertion error", e);
}
System.err.println(String.format("OK: discreteInitial=%s, coilInitial=%s, nonZeroOffset=%s, command=%s, itemIndex=%d, type=%s", discreteInitialValue, coilInitialValue, nonZeroOffset, command, itemIndex, type));
}
use of net.wimpi.modbus.msg.ModbusRequest in project openhab1-addons by openhab.
the class WriteRegistersTestCase method verifyRequests.
private void verifyRequests(boolean readRequestExpected) throws Exception {
try {
ArrayList<ModbusRequest> requests = modbustRequestCaptor.getAllReturnValues();
int expectedRegisterWriteStartIndex = nonZeroOffset ? (itemIndex + 1) : itemIndex;
boolean writeExpected = type == ModbusBindingProvider.TYPE_HOLDING;
int expectedRequests = (writeExpected ? 1 : 0) + (readRequestExpected ? 1 : 0);
// One connection per request
int expectedConnections = serverType.equals(ServerType.UDP) ? 1 : expectedRequests;
// Give the system 5 seconds to make the expected connections & requests
waitForConnectionsReceived(expectedConnections);
waitForRequests(expectedRequests);
assertThat(requests.size(), is(equalTo(expectedRequests)));
if (readRequestExpected) {
if (type == ModbusBindingProvider.TYPE_INPUT) {
assertThat(requests.get(0), is(instanceOf(ReadInputRegistersRequest.class)));
} else if (type == ModbusBindingProvider.TYPE_HOLDING) {
assertThat(requests.get(0), is(instanceOf(ReadMultipleRegistersRequest.class)));
} else {
throw new RuntimeException();
}
}
if (writeExpected) {
Register[] registers;
if (expectingWriteMultiple(valueType)) {
assertThat(requests.get(expectedRequests - 1), is(instanceOf(WriteMultipleRegistersRequest.class)));
WriteMultipleRegistersRequest writeRequest = (WriteMultipleRegistersRequest) requests.get(expectedRequests - 1);
assertThat(writeRequest.getReference(), is(equalTo(expectedRegisterWriteStartIndex)));
if (expectedValue == null && expectingAssertionError) {
String msg = "Did not receive any AssertionErrors even though expected!";
errPrint(msg);
throw new RuntimeException(msg);
}
registers = writeRequest.getRegisters();
} else {
assertThat(requests.get(expectedRequests - 1), is(instanceOf(WriteSingleRegisterRequest.class)));
WriteSingleRegisterRequest writeRequest = (WriteSingleRegisterRequest) requests.get(expectedRequests - 1);
assertThat(writeRequest.getReference(), is(equalTo(expectedRegisterWriteStartIndex)));
if (expectedValue == null && expectingAssertionError) {
String msg = "Did not receive any AssertionErrors even though expected!";
errPrint(msg);
throw new RuntimeException(msg);
}
registers = new Register[] { writeRequest.getRegister() };
}
short[] registersAsShort = new short[registers.length];
for (int i = 0; i < registers.length; i++) {
registersAsShort[i] = registers[i].toShort();
}
assertThat(registersAsShort, is(equalTo(expectedValue)));
}
} catch (AssertionError e) {
if (expectingAssertionError) {
errPrint("Expected failure");
e.printStackTrace(System.err);
return;
} else {
errPrint("Unexpected assertion error " + e.getMessage());
e.printStackTrace(System.err);
throw e;
}
}
if (expectingAssertionError) {
errPrint("Did not get assertion error (as expected)");
throw new AssertionError("Did not get assertion error (as expected)");
} else {
errPrint("OK");
}
}
use of net.wimpi.modbus.msg.ModbusRequest in project openhab1-addons by openhab.
the class AITest method main.
public static void main(String[] args) {
InetAddress addr = null;
TCPMasterConnection con = null;
ModbusRequest req = null;
ModbusTransaction trans = null;
int ref = 0;
int count = 0;
int repeat = 1;
int port = Modbus.DEFAULT_PORT;
try {
// 1. Setup parameters
if (args.length < 3) {
printUsage();
System.exit(1);
} else {
try {
String astr = args[0];
int idx = astr.indexOf(':');
if (idx > 0) {
port = Integer.parseInt(astr.substring(idx + 1));
astr = astr.substring(0, idx);
}
addr = InetAddress.getByName(astr);
ref = Integer.parseInt(args[1]);
count = Integer.parseInt(args[2]);
if (args.length == 4) {
repeat = Integer.parseInt(args[3]);
}
} catch (Exception ex) {
ex.printStackTrace();
printUsage();
System.exit(1);
}
}
// 2. Open the connection
con = new TCPMasterConnection(addr);
con.setPort(port);
con.connect();
if (Modbus.debug) {
System.out.println("Connected to " + addr.toString() + ":" + con.getPort());
}
// 3. Prepare the request
req = new ReadInputRegistersRequest(ref, count);
req.setUnitID(0);
if (Modbus.debug) {
System.out.println("Request: " + req.getHexMessage());
}
// 4. Prepare the transaction
trans = new ModbusTCPTransaction(con);
trans.setRequest(req);
// 5. Execute the transaction repeat times
int k = 0;
do {
trans.execute();
ReadInputRegistersResponse res = (ReadInputRegistersResponse) trans.getResponse();
if (Modbus.debug) {
System.out.println("Response: " + res.getHexMessage());
}
for (int n = 0; n < res.getWordCount(); n++) {
System.out.println("Word " + n + "=" + res.getRegisterValue(n));
}
k++;
} while (k < repeat);
// 6. Close the connection
con.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
use of net.wimpi.modbus.msg.ModbusRequest in project openhab1-addons by openhab.
the class ModbusSlave method setRegister.
/**
* Performs physical write to device when slave type is "holding" using Modbus FC06 function
*
* @param command command received from OpenHAB
* @param config
* @throws ModbusConnectionException when connection cannot be established
* @throws ModbusException ModbusIOException on IO errors, ModbusSlaveException with protocol level exceptions
* @throws ModbusUnexpectedTransactionIdException when response transaction id does not match the request
*/
protected void setRegister(Command command, ModbusBindingConfig config) throws ModbusConnectionException, ModbusException, ModbusUnexpectedTransactionIdException {
int readIndex = config.readIndex;
int writeRegister = getStart() + config.writeIndex;
Register newValue;
if (command instanceof IncreaseDecreaseType) {
newValue = readCachedRegisterValue(readIndex);
if (newValue == null) {
logger.warn("Not polled value for item {}. Cannot process command {}", config.getItemName(), command);
return;
}
if (command.equals(IncreaseDecreaseType.INCREASE)) {
newValue.setValue(newValue.getValue() + 1);
} else if (command.equals(IncreaseDecreaseType.DECREASE)) {
newValue.setValue(newValue.getValue() - 1);
}
} else if (command instanceof UpDownType) {
newValue = readCachedRegisterValue(readIndex);
if (newValue == null) {
logger.warn("Not polled value for item {}. Cannot process command {}", config.getItemName(), command);
return;
}
if (command.equals(UpDownType.UP)) {
newValue.setValue(newValue.getValue() + 1);
} else if (command.equals(UpDownType.DOWN)) {
newValue.setValue(newValue.getValue() - 1);
}
} else if (command instanceof DecimalType) {
newValue = new SimpleRegister();
newValue.setValue(((DecimalType) command).intValue());
} else if (command instanceof OnOffType) {
newValue = new SimpleRegister();
if (command.equals(OnOffType.ON)) {
newValue.setValue(1);
} else if (command.equals(OnOffType.OFF)) {
newValue.setValue(0);
}
} else if (command instanceof OpenClosedType) {
newValue = new SimpleRegister();
if (command.equals(OpenClosedType.OPEN)) {
newValue.setValue(1);
} else if (command.equals(OpenClosedType.CLOSED)) {
newValue.setValue(0);
}
} else {
logger.warn("Item {} received unsupported command: {}. Not setting register.", config.getItemName(), command);
return;
}
ModbusRequest request = null;
if (writeMultipleRegisters) {
Register[] regs = new Register[1];
regs[0] = newValue;
request = new WriteMultipleRegistersRequest(writeRegister, regs);
} else {
request = new WriteSingleRegisterRequest(writeRegister, newValue);
}
request.setUnitID(getId());
logger.debug("ModbusSlave ({}): FC{} ref={} value={}", name, request.getFunctionCode(), writeRegister, newValue.getValue());
executeWriteRequest(request);
}
use of net.wimpi.modbus.msg.ModbusRequest in project openhab1-addons by openhab.
the class ModbusSlave method doSetCoil.
/**
* Sends boolean (bit) data to the device using Modbus FC05 function
*
* @param writeRegister
* @param b
* @throws ModbusUnexpectedTransactionIdException
* @throws ModbusException
* @throws ModbusConnectionException
*/
public void doSetCoil(int writeRegister, boolean b) throws ModbusConnectionException, ModbusException, ModbusUnexpectedTransactionIdException {
ModbusRequest request = new WriteCoilRequest(writeRegister, b);
request.setUnitID(getId());
logger.debug("ModbusSlave ({}): FC05 ref={} value={}", name, writeRegister, b);
executeWriteRequest(request);
}
Aggregations