use of net.wimpi.modbus.msg.WriteSingleRegisterRequest 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.WriteSingleRegisterRequest 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.WriteSingleRegisterRequest in project openhab1-addons by openhab.
the class SimultaneousReadWriteTestCase method testSimultaneousReadWrite.
/**
* Testing how binding handles simultaneous read and writes coming in.
*
* Even though the server in this test is able to handle at most one client at a time the binding
* queues requests.
*
* Note higher artificialServerWait in constructor
*
* @throws Exception
*/
@Test
public void testSimultaneousReadWrite() throws Exception {
binding = new ModbusBinding();
binding.updated(addSlave(addSlave(newLongPollBindingConfig(), SLAVE_NAME, type, null, 0, READ_COUNT), SLAVE2_NAME, type, null, 0, READ_COUNT));
configureItems(SLAVE_NAME);
configureItems(SLAVE2_NAME);
/*
* - both slaves read twice -> 4 read requests
* - followed by write (slave1) -> 1 write request
* - both slaves read once -> 2 read requests.
* - Finally three writes (slave2) -> 3 write requets
*/
int expectedRequests = 10;
ExecutorService pool = Executors.newFixedThreadPool(expectedRequests);
binding.execute();
pool.execute(new UpdateThread(binding));
pool.execute(new WriteCommandThread(binding, SLAVE_NAME, command));
pool.execute(new UpdateThread(binding));
pool.execute(new WriteCommandThread(binding, SLAVE2_NAME, command));
pool.execute(new WriteCommandThread(binding, SLAVE2_NAME, command));
pool.execute(new WriteCommandThread(binding, SLAVE2_NAME, command));
pool.shutdown();
pool.awaitTermination(artificialServerWait * 7 + 5000, TimeUnit.MILLISECONDS);
waitForRequests(expectedRequests);
ArrayList<ModbusRequest> values = modbustRequestCaptor.getAllReturnValues();
System.err.println(values);
int readCount = 0;
int writeCount = 0;
for (ModbusRequest request : values) {
if (request instanceof ReadMultipleRegistersRequest) {
readCount++;
} else if (request instanceof WriteSingleRegisterRequest) {
writeCount++;
}
}
Assert.assertEquals(6, readCount);
Assert.assertEquals(4, writeCount);
}
use of net.wimpi.modbus.msg.WriteSingleRegisterRequest in project openhab1-addons by openhab.
the class AIAOTest method main.
public static void main(String[] args) {
InetAddress addr = null;
TCPMasterConnection con = null;
ModbusRequest ai_req = null;
WriteSingleRegisterRequest ao_req = null;
ModbusTransaction ai_trans = null;
ModbusTransaction ao_trans = null;
int ai_ref = 0;
int ao_ref = 0;
int port = Modbus.DEFAULT_PORT;
try {
// 1. Setup the 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);
ai_ref = Integer.parseInt(args[1]);
ao_ref = Integer.parseInt(args[2]);
} 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 requests
ai_req = new ReadInputRegistersRequest(ai_ref, 1);
ao_req = new WriteSingleRegisterRequest();
ao_req.setReference(ao_ref);
ai_req.setUnitID(0);
ao_req.setUnitID(0);
// 4. Prepare the transactions
ai_trans = new ModbusTCPTransaction(con);
ai_trans.setRequest(ai_req);
ao_trans = new ModbusTCPTransaction(con);
ao_trans.setRequest(ao_req);
// 5. Prepare holders to update only on change
SimpleRegister new_out = new SimpleRegister(0);
ao_req.setRegister(new_out);
int last_out = Integer.MIN_VALUE;
// 5. Execute the transaction repeatedly
do {
ai_trans.execute();
int new_in = ((ReadInputRegistersResponse) ai_trans.getResponse()).getRegister(0).getValue();
// write only if differ
if (new_in != last_out) {
// update register
new_out.setValue(new_in);
ao_trans.execute();
last_out = new_in;
if (Modbus.debug) {
System.out.println("Updated Register with value from Input Register.");
}
}
} while (true);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
// 6. Close the connection
con.close();
}
}
use of net.wimpi.modbus.msg.WriteSingleRegisterRequest in project openhab1-addons by openhab.
the class AOTest 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());
}
req = new WriteSingleRegisterRequest(ref, new SimpleRegister(count));
req.setUnitID(0);
if (Modbus.debug) {
System.out.println("Request: " + req.getHexMessage());
}
// 3. Prepare the transaction
trans = new ModbusTCPTransaction(con);
trans.setRequest(req);
// 4. Execute the transaction repeat times
int k = 0;
do {
trans.execute();
if (Modbus.debug) {
System.out.println("Response: " + trans.getResponse().getHexMessage());
}
k++;
} while (k < repeat);
// 5. Close the connection
con.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
Aggregations