ModbusMaster.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. /*
  2. * ============================================================================
  3. * GNU General Public License
  4. * ============================================================================
  5. *
  6. * Copyright (C) 2006-2011 Serotonin Software Technologies Inc. http://serotoninsoftware.com
  7. * @author Matthew Lohbihler
  8. *
  9. * This program is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation, either version 3 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. */
  21. package com.serotonin.cdc.modbus4j;
  22. import java.util.ArrayList;
  23. import java.util.HashMap;
  24. import java.util.Iterator;
  25. import java.util.List;
  26. import java.util.Map;
  27. import com.serotonin.cdc.messaging.MessageControl;
  28. import com.serotonin.cdc.modbus4j.base.KeyedModbusLocator;
  29. import com.serotonin.cdc.modbus4j.base.ReadFunctionGroup;
  30. import com.serotonin.cdc.modbus4j.base.SlaveProfile;
  31. import com.serotonin.cdc.modbus4j.code.DataType;
  32. import com.serotonin.cdc.modbus4j.code.ExceptionCode;
  33. import com.serotonin.cdc.modbus4j.code.FunctionCode;
  34. import com.serotonin.cdc.modbus4j.code.RegisterRange;
  35. import com.serotonin.cdc.modbus4j.exception.ErrorResponseException;
  36. import com.serotonin.cdc.modbus4j.exception.InvalidDataConversionException;
  37. import com.serotonin.cdc.modbus4j.exception.ModbusInitException;
  38. import com.serotonin.cdc.modbus4j.exception.ModbusTransportException;
  39. import com.serotonin.cdc.modbus4j.locator.BaseLocator;
  40. import com.serotonin.cdc.modbus4j.locator.BinaryLocator;
  41. import com.serotonin.cdc.modbus4j.locator.NumericLocator;
  42. import com.serotonin.cdc.modbus4j.msg.ModbusRequest;
  43. import com.serotonin.cdc.modbus4j.msg.ModbusResponse;
  44. import com.serotonin.cdc.modbus4j.msg.ReadCoilsRequest;
  45. import com.serotonin.cdc.modbus4j.msg.ReadDiscreteInputsRequest;
  46. import com.serotonin.cdc.modbus4j.msg.ReadHoldingRegistersRequest;
  47. import com.serotonin.cdc.modbus4j.msg.ReadInputRegistersRequest;
  48. import com.serotonin.cdc.modbus4j.msg.ReadResponse;
  49. import com.serotonin.cdc.modbus4j.msg.WriteCoilRequest;
  50. import com.serotonin.cdc.modbus4j.msg.WriteMaskRegisterRequest;
  51. import com.serotonin.cdc.modbus4j.msg.WriteRegisterRequest;
  52. import com.serotonin.cdc.modbus4j.msg.WriteRegistersRequest;
  53. import com.serotonin.cdc.util.ArrayUtils;
  54. import com.serotonin.cdc.util.ProgressiveTask;
  55. abstract public class ModbusMaster extends Modbus {
  56. private int timeout = 500;
  57. private int retries = 2;
  58. private int discardDataDelay = 0;
  59. private final Map slaveProfiles = new HashMap();
  60. protected boolean initialized;
  61. abstract public void init() throws ModbusInitException;
  62. public boolean isInitialized() {
  63. return initialized;
  64. }
  65. abstract public void destroy();
  66. public final ModbusResponse send(ModbusRequest request) throws ModbusTransportException {
  67. request.validate(this);
  68. return sendImpl(request);
  69. }
  70. abstract public ModbusResponse sendImpl(ModbusRequest request) throws ModbusTransportException;
  71. /**
  72. * Returns a value from the modbus network according to the given locator information. Various data types are
  73. * allowed to be requested including multi-word types. The determination of the correct request message to send is
  74. * handled automatically.
  75. *
  76. * @param locator
  77. * the information required to locate the value in the modbus network.
  78. * @return an object representing the value found. This will be one of Boolean, Short, Integer, Long, BigInteger,
  79. * Float, or Double. See the DataType enumeration for details on which type to expect.
  80. * @throws ModbusTransportException
  81. * if there was an IO error or other technical failure while sending the message
  82. * @throws ErrorResponseException
  83. * if the response returned from the slave was an exception.
  84. */
  85. //SuppressWarnings("unchecked")
  86. public Object getValue(BaseLocator locator) throws ModbusTransportException, ErrorResponseException {
  87. BatchRead batch = new BatchRead();
  88. batch.addLocator("", locator);
  89. BatchResults result = send(batch);
  90. return result.getValue("");
  91. }
  92. /**
  93. * Sets the given value in the modbus network according to the given locator information. Various data types are
  94. * allowed to be set including including multi-word types. The determination of the correct write message to send is
  95. * handled automatically.
  96. *
  97. * @param locator
  98. * the information required to locate the value in the modbus network.
  99. * @value an object representing the value to be set. This will be one of Boolean, Short, Integer, Long, BigInteger,
  100. * Float, or Double. See the DataType enumeration for details on which type to expect.
  101. * @throws ModbusTransportException
  102. * if there was an IO error or other technical failure while sending the message
  103. * @throws ErrorResponseException
  104. * if the response returned from the slave was an exception.
  105. */
  106. public void setValue(BaseLocator locator, Object value) throws ModbusTransportException, ErrorResponseException {
  107. int slaveId = locator.getSlaveId();
  108. int registerRange = locator.getRange();
  109. int writeOffset = locator.getOffset();
  110. // Determine the request type that we will use
  111. if (registerRange == RegisterRange.INPUT_STATUS || registerRange == RegisterRange.INPUT_REGISTER)
  112. throw new RuntimeException("Cannot write to input status or input register ranges");
  113. if (registerRange == RegisterRange.COIL_STATUS) {
  114. if (!(value instanceof Boolean))
  115. throw new InvalidDataConversionException("Only boolean values can be written to coils");
  116. setValue(new WriteCoilRequest(slaveId, writeOffset, ((Boolean) value).booleanValue()));
  117. }
  118. else {
  119. // Writing to holding registers.
  120. if (locator.getDataType() == DataType.BINARY) {
  121. if (!(value instanceof Boolean))
  122. throw new InvalidDataConversionException("Only boolean values can be written to coils");
  123. setHoldingRegisterBit(slaveId, writeOffset, ((BinaryLocator) locator).getBit(),
  124. ((Boolean) value).booleanValue());
  125. }
  126. else {
  127. // Writing some kind of value to a holding register.
  128. //SuppressWarnings("unchecked")
  129. short[] data = locator.valueToShorts(value);
  130. if (data.length == 1)
  131. setValue(new WriteRegisterRequest(slaveId, writeOffset, data[0]));
  132. else
  133. setValue(new WriteRegistersRequest(slaveId, writeOffset, data));
  134. }
  135. }
  136. }
  137. /**
  138. * Node scanning. Returns a list of slave nodes that respond to a read exception status request (perhaps with an
  139. * error, but respond nonetheless).
  140. *
  141. * Note: a similar scan could be done for registers in nodes, but, for one thing, it would take some time to run,
  142. * and in any case the results would not be meaningful since there would be no semantic information accompanying the
  143. * results.
  144. */
  145. public List scanForSlaveNodes() {
  146. List result = new ArrayList();
  147. for (int i = 1; i <= 240; i++) {
  148. if (testSlaveNode(i))
  149. result.add(new Integer(i));
  150. }
  151. return result;
  152. }
  153. public ProgressiveTask scanForSlaveNodes(final NodeScanListener l) {
  154. l.progressUpdate(0);
  155. ProgressiveTask task = new ProgressiveTask(l) {
  156. private int node = 1;
  157. //Override
  158. protected void runImpl() {
  159. if (testSlaveNode(node))
  160. l.nodeFound(node);
  161. declareProgress(((float) node) / 240);
  162. node++;
  163. if (node > 240)
  164. completed = true;
  165. }
  166. };
  167. new Thread(task).start();
  168. return task;
  169. }
  170. public boolean testSlaveNode(int node) {
  171. try {
  172. send(new ReadHoldingRegistersRequest(node, 0, 1));
  173. }
  174. catch (ModbusTransportException e) {
  175. // If there was a transport exception, there's no node there.
  176. return false;
  177. }
  178. return true;
  179. }
  180. public int getRetries() {
  181. return retries;
  182. }
  183. public void setRetries(int retries) {
  184. if (retries < 0)
  185. this.retries = 0;
  186. else
  187. this.retries = retries;
  188. }
  189. public int getTimeout() {
  190. return timeout;
  191. }
  192. public void setTimeout(int timeout) {
  193. if (timeout < 1)
  194. this.timeout = 1;
  195. else
  196. this.timeout = timeout;
  197. }
  198. public int getDiscardDataDelay() {
  199. return discardDataDelay;
  200. }
  201. public void setDiscardDataDelay(int discardDataDelay) {
  202. if (discardDataDelay < 0)
  203. this.discardDataDelay = 0;
  204. else
  205. this.discardDataDelay = discardDataDelay;
  206. }
  207. /**
  208. * Useful for sending a number of polling commands at once, or at least in as optimal a batch as possible.
  209. */
  210. public BatchResults send(BatchRead batch) throws ModbusTransportException, ErrorResponseException {
  211. if (!initialized)
  212. throw new ModbusTransportException("not initialized");
  213. BatchResults results = new BatchResults();
  214. List functionGroups = batch.getReadFunctionGroups(this);
  215. // Execute each read function and process the results.
  216. for (Iterator iter = functionGroups.iterator(); iter.hasNext();) {
  217. ReadFunctionGroup functionGroup = (ReadFunctionGroup) iter.next();
  218. sendFunctionGroup(functionGroup, results, batch.isErrorsInResults(), batch.isExceptionsInResults());
  219. }
  220. return results;
  221. }
  222. //
  223. //
  224. // Protected methods
  225. //
  226. protected MessageControl getMessageControl() {
  227. MessageControl conn = new MessageControl();
  228. conn.setRetries(getRetries());
  229. conn.setTimeout(getTimeout());
  230. conn.setDiscardDataDelay(getDiscardDataDelay());
  231. conn.setExceptionHandler(getExceptionHandler());
  232. return conn;
  233. }
  234. protected void closeMessageControl(MessageControl conn) {
  235. if (conn != null)
  236. conn.close();
  237. }
  238. //
  239. //
  240. // Private stuff
  241. //
  242. /**
  243. * This method assumes that all locators have already been pre-sorted and grouped into valid requests, say, by the
  244. * createRequestGroups method.
  245. */
  246. private void sendFunctionGroup(ReadFunctionGroup functionGroup, BatchResults results, boolean errorsInResults,
  247. boolean exceptionsInResults) throws ModbusTransportException, ErrorResponseException {
  248. int slaveId = functionGroup.getSlaveAndRange().getSlaveId();
  249. int startOffset = functionGroup.getStartOffset();
  250. int length = functionGroup.getLength();
  251. // Inspect the function group for data required to create the request.
  252. ModbusRequest request;
  253. if (functionGroup.getFunctionCode() == FunctionCode.READ_COILS)
  254. request = new ReadCoilsRequest(slaveId, startOffset, length);
  255. else if (functionGroup.getFunctionCode() == FunctionCode.READ_DISCRETE_INPUTS)
  256. request = new ReadDiscreteInputsRequest(slaveId, startOffset, length);
  257. else if (functionGroup.getFunctionCode() == FunctionCode.READ_HOLDING_REGISTERS)
  258. request = new ReadHoldingRegistersRequest(slaveId, startOffset, length);
  259. else if (functionGroup.getFunctionCode() == FunctionCode.READ_INPUT_REGISTERS)
  260. request = new ReadInputRegistersRequest(slaveId, startOffset, length);
  261. else
  262. throw new RuntimeException("Unsupported function");
  263. ReadResponse response;
  264. try {
  265. response = (ReadResponse) send(request);
  266. }
  267. catch (ModbusTransportException e) {
  268. if (!exceptionsInResults)
  269. throw e;
  270. for (Iterator iter = functionGroup.getLocators().iterator(); iter.hasNext();) {
  271. KeyedModbusLocator locator = (KeyedModbusLocator) iter.next();
  272. results.addResult(locator.getKey(), e);
  273. }
  274. return;
  275. }
  276. byte[] data = null;
  277. if (!errorsInResults && response.isException())
  278. throw new ErrorResponseException(request, response);
  279. else if (!response.isException())
  280. data = response.getData();
  281. for (Iterator iter = functionGroup.getLocators().iterator(); iter.hasNext();) {
  282. KeyedModbusLocator locator = (KeyedModbusLocator) iter.next();
  283. if (errorsInResults && response.isException())
  284. results.addResult(locator.getKey(), new ExceptionResult(response.getExceptionCode()));
  285. else {
  286. try {
  287. results.addResult(locator.getKey(), locator.bytesToValue(data, startOffset));
  288. }
  289. catch (RuntimeException e) {
  290. throw new RuntimeException("Result conversion exception. data=" + ArrayUtils.toHexString(data)
  291. + ", startOffset=" + startOffset + ", locator=" + locator + ", functionGroup.functionCode="
  292. + functionGroup.getFunctionCode() + ", functionGroup.startOffset=" + startOffset
  293. + ", functionGroup.length=" + length, e);
  294. }
  295. }
  296. }
  297. }
  298. private void setValue(ModbusRequest request) throws ModbusTransportException, ErrorResponseException {
  299. ModbusResponse response = send(request);
  300. if (response == null)
  301. // This should only happen if the request was a broadcast
  302. return;
  303. if (response.isException())
  304. throw new ErrorResponseException(request, response);
  305. }
  306. private void setHoldingRegisterBit(int slaveId, int writeOffset, int bit, boolean value)
  307. throws ModbusTransportException, ErrorResponseException {
  308. // Writing a bit in a holding register field. There are two ways to do this. The easy way is to
  309. // use a write mask request, but it is not always supported. The hard way is to read the value, change
  310. // the appropriate bit, and then write it back again (so as not to overwrite the other bits in the
  311. // value). However, since the hard way is not atomic, it is not fail-safe either, but it should be
  312. // at least possible.
  313. SlaveProfile sp = getSlaveProfile(slaveId);
  314. if (sp.getWriteMaskRegister()) {
  315. // Give the write mask a try.
  316. WriteMaskRegisterRequest request = new WriteMaskRegisterRequest(slaveId, writeOffset);
  317. request.setBit(bit, value);
  318. ModbusResponse response = send(request);
  319. if (response == null)
  320. // This should only happen if the request was a broadcast
  321. return;
  322. if (!response.isException())
  323. // Hey, cool, it worked.
  324. return;
  325. if (response.getExceptionCode() == ExceptionCode.ILLEGAL_FUNCTION)
  326. // The function is probably not supported. Fail-over to the two step.
  327. sp.setWriteMaskRegister(false);
  328. else
  329. throw new ErrorResponseException(request, response);
  330. }
  331. // Do it the hard way. Get the register's current value.
  332. int regValue = ((Integer) getValue(new NumericLocator(slaveId, RegisterRange.HOLDING_REGISTER, writeOffset,
  333. DataType.TWO_BYTE_INT_UNSIGNED))).intValue();
  334. // Modify the value according to the given bit and value.
  335. if (value)
  336. regValue = regValue | 1 << bit;
  337. else
  338. regValue = regValue & ~(1 << bit);
  339. // Write the new register value.
  340. setValue(new WriteRegisterRequest(slaveId, writeOffset, regValue));
  341. }
  342. private SlaveProfile getSlaveProfile(int slaveId) {
  343. SlaveProfile sp = (SlaveProfile) slaveProfiles.get(new Integer(slaveId));
  344. if (sp == null) {
  345. sp = new SlaveProfile();
  346. slaveProfiles.put(new Integer(slaveId), sp);
  347. }
  348. return sp;
  349. }
  350. }