diff --git a/WebContent/WEB-INF/jsp/dataSourceEdit/editSnmp.jsp b/WebContent/WEB-INF/jsp/dataSourceEdit/editSnmp.jsp
index 689aa3ed11..49b03f393d 100644
--- a/WebContent/WEB-INF/jsp/dataSourceEdit/editSnmp.jsp
+++ b/WebContent/WEB-INF/jsp/dataSourceEdit/editSnmp.jsp
@@ -27,31 +27,74 @@
var version = $get("snmpVersion");
if (version == ) {
show("version3Fields");
+ show("trapSection");
hide("version12Fields");
- }
- else {
+ } else if (version == ) {
+ hide("version3Fields");
+ show("version12Fields");
+ hide("trapSection");
+ } else {
hide("version3Fields");
show("version12Fields");
+ show("trapSection");
}
+
}
-
+
+ function securityLevelChange() {
+ var securityLevel = $get("securityLevel");
+ if (securityLevel === "1") {
+ hide("authFieldsProtocol")
+ hide("authFieldsPassphrase")
+ hide("privFieldsProtocol")
+ hide("privFieldsPassphrase")
+ } else if (securityLevel === "2") {
+ show("authFieldsProtocol")
+ show("authFieldsPassphrase")
+ hide("privFieldsProtocol")
+ hide("privFieldsPassphrase")
+ } else if (securityLevel === "3") {
+ show("authFieldsProtocol")
+ show("authFieldsPassphrase")
+ show("privFieldsProtocol")
+ show("privFieldsPassphrase")
+ }
+ }
+
function snmpTest() {
$set("snmpTestMessage", "");
snmpTestButton(true);
- DataSourceEditDwr.snmpGetOid($get("snmpTestOid"), $get("host"), $get("port"), $get("snmpVersion"),
- $get("community"), $get("securityName"), $get("authProtocol"), $get("authPassphrase"),
- $get("privProtocol"), $get("privPassphrase"), $get("engineId"), $get("contextEngineId"),
+ DataSourceEditDwr.snmpGetOid($get("snmpTestOid"), $get("host"), $get("port"), $get("snmpVersion"),
+ $get("community"), $get("securityName"), $get("authProtocol"), $get("authPassphrase"),
+ $get("privProtocol"), $get("privPassphrase"), $get("securityLevel"),
$get("contextName"), $get("retries"), $get("timeout"), snmpTestCB);
}
-
+
+ function snmpWalk() {
+ $set("snmpTestMessage", "");
+ snmpWalkButton(true);
+ DataSourceEditDwr.snmpWalkOid($get("snmpWalkOid"), $get("host"), $get("port"), $get("snmpVersion"),
+ $get("community"), $get("securityName"), $get("authProtocol"), $get("authPassphrase"),
+ $get("privProtocol"), $get("privPassphrase"), $get("securityLevel"),
+ $get("contextName"), $get("retries"), $get("timeout"), snmpWalkCB);
+ }
+
function snmpTestCB() {
setTimeout(snmpTestUpdate, 1000);
}
-
+
+ function snmpWalkCB() {
+ setTimeout(snmpWalkUpdate, 1000);
+ }
+
function snmpTestUpdate() {
DataSourceEditDwr.snmpGetOidUpdate(snmpTestUpdateCB);
}
-
+
+ function snmpWalkUpdate() {
+ DataSourceEditDwr.snmpGetWalkUpdate(snmpWalkUpdateCB);
+ }
+
function snmpTestUpdateCB(result) {
if (result) {
$set("snmpTestMessage", result);
@@ -60,29 +103,55 @@
else
snmpTestCB();
}
-
+
+ function snmpWalkUpdateCB(result) {
+ if (result) {
+ $set("snmpWalkMessage", result);
+ snmpWalkButton(false);
+ }
+ else
+ snmpWalkCB();
+ }
+
function snmpTestButton(testing) {
setDisabled($("snmpTestBtn"), testing);
}
+ function snmpWalkButton(testing) {
+ setDisabled($("snmpWalkBtn"), testing);
+ }
+
function initImpl() {
versionChange();
+ securityLevelChange();
snmpTestButton(false);
+ toggleTrapSetting();
}
-
+
+ function toggleTrapSetting() {
+ var checkbox = document.getElementById("trapEnabled");
+ if(checkbox.checked) {
+ show("trapSectionPort")
+ show("trapSectionAddress")
+ } else {
+ hide("trapSectionPort")
+ hide("trapSectionAddress")
+ }
+ }
+
function saveDataSourceImpl() {
DataSourceEditDwr.saveSnmpDataSource($get("dataSourceName"), $get("dataSourceXid"), $get("updatePeriods"),
$get("updatePeriodType"), $get("host"), $get("port"), $get("snmpVersion"), $get("community"),
$get("securityName"), $get("authProtocol"), $get("authPassphrase"), $get("privProtocol"),
- $get("privPassphrase"), $get("engineId"), $get("contextEngineId"), $get("contextName"), $get("retries"),
- $get("timeout"), $get("trapPort"), $get("localAddress"), saveDataSourceCB);
+ $get("privPassphrase"), $get("securityLevel"), $get("contextName"), $get("retries"),
+ $get("timeout"), $get("trapEnabled"), $get("trapPort"), $get("localAddress"), saveDataSourceCB);
}
-
+
function appendPointListColumnFunctions(pointListColumnHeaders, pointListColumnFunctions) {
pointListColumnHeaders[pointListColumnHeaders.length] = "";
pointListColumnFunctions[pointListColumnFunctions.length] = function(p) { return p.pointLocator.oid; };
}
-
+
function editPointCBImpl(locator) {
$set("oid", locator.oid);
$set("dataTypeId", locator.dataTypeId);
@@ -91,19 +160,19 @@
$set("trapOnly", locator.trapOnly ? "true" : "false");
dataTypeChanged();
}
-
+
function savePointImpl(locator) {
delete locator.settable;
-
+
locator.oid = $get("oid");
locator.dataTypeId = $get("dataTypeId");
locator.binary0Value = $get("binary0Value");
locator.setType = $get("setType");
locator.trapOnly = $get("trapOnly") == "true";
-
+
DataSourceEditDwr.saveSnmpPointLocator(currentPoint.id, $get("xid"), $get("name"), locator, savePointCB);
}
-
+
function dataTypeChanged() {
display("binary0ValueRow", $get("dataTypeId") == );
}
@@ -121,17 +190,27 @@
-
+
|
|
-
+
|
|
-
+
+
+ |
+ |
+
+
+
+ |
+ |
+
+
|
@@ -142,37 +221,53 @@
|
-
+
|
|
-
+
+
|
|
-
+
+ |
+
+
+
+
+
+
+ |
+
+
+
|
MD5
SHA
+ HMAC128 SHA224
+ HMAC192 SHA256
+ HMAC256 SHA384
+ HMAC384 SHA512
|
-
-
+
+
|
|
-
-
+
+
|
@@ -181,72 +276,83 @@
AES128
AES192
AES256
+
+ 3DES
+ AES192With3DES
+ AES256With3DES
|
-
-
+
+
|
|
-
-
- |
- |
-
-
-
- |
- |
-
-
+
|
|
-
-
-
- |
- |
-
-
-
- |
- |
+
+
+
+
+ |
+ |
-
-
- |
+
+
+ |
|
-
-
- |
+
+
+ |
|
-
+
|
-
+
|
|
-
+
" onclick="snmpTest();"/>
|
-
+
|
+
+
+
<%@ include file="/WEB-INF/jsp/dataSourceEdit/dsFoot.jspf" %>
diff --git a/WebContent/WEB-INF/lib/SNMP4J.jar b/WebContent/WEB-INF/lib/SNMP4J.jar
deleted file mode 100644
index 0c6c1b063b..0000000000
Binary files a/WebContent/WEB-INF/lib/SNMP4J.jar and /dev/null differ
diff --git a/WebContent/WEB-INF/lib/snmp4j-2.8.6.jar b/WebContent/WEB-INF/lib/snmp4j-2.8.6.jar
new file mode 100644
index 0000000000..2f3c6c6cb0
Binary files /dev/null and b/WebContent/WEB-INF/lib/snmp4j-2.8.6.jar differ
diff --git a/build.xml b/build.xml
index e1cc2a4cf7..c7095889b8 100644
--- a/build.xml
+++ b/build.xml
@@ -82,7 +82,7 @@
-
+
diff --git a/src/com/serotonin/mango/rt/dataSource/snmp/SnmpDataSourceRT.java b/src/com/serotonin/mango/rt/dataSource/snmp/SnmpDataSourceRT.java
index 0f6bc262e4..1de498569a 100644
--- a/src/com/serotonin/mango/rt/dataSource/snmp/SnmpDataSourceRT.java
+++ b/src/com/serotonin/mango/rt/dataSource/snmp/SnmpDataSourceRT.java
@@ -1,34 +1,23 @@
-/*
- Mango - Open Source M2M - http://mango.serotoninsoftware.com
- Copyright (C) 2006-2011 Serotonin Software Technologies Inc.
- @author Matthew Lohbihler
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see .
- */
package com.serotonin.mango.rt.dataSource.snmp;
import java.io.IOException;
-import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
+import com.serotonin.mango.vo.dataSource.snmp.SnmpDataSourceVO;
+import com.serotonin.mango.vo.dataSource.snmp.SnmpPointLocatorVO;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.Target;
+import org.snmp4j.event.ResponseEvent;
+import org.snmp4j.mp.MPv3;
+import org.snmp4j.security.SecurityModels;
+import org.snmp4j.security.SecurityProtocols;
+import org.snmp4j.security.USM;
import org.snmp4j.smi.OID;
+import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.Variable;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
@@ -39,271 +28,394 @@
import com.serotonin.mango.rt.dataImage.SetPointSource;
import com.serotonin.mango.rt.dataSource.DataSourceRT;
import com.serotonin.mango.rt.dataSource.PollingDataSource;
-import com.serotonin.mango.vo.dataSource.snmp.SnmpDataSourceVO;
-import com.serotonin.mango.vo.dataSource.snmp.SnmpPointLocatorVO;
+
import com.serotonin.web.i18n.LocalizableMessage;
/**
* @author Matthew Lohbihler
- *
+ *
*/
public class SnmpDataSourceRT extends PollingDataSource {
- public static final int DATA_SOURCE_EXCEPTION_EVENT = 1;
- public static final int PDU_EXCEPTION_EVENT = 2;
-
- private final Log log = LogFactory.getLog(SnmpDataSourceRT.class);
-
- private final SnmpDataSourceVO vo;
- private final Version version;
- private String address;
- private Target target;
- private Snmp snmp;
-
- public SnmpDataSourceRT(SnmpDataSourceVO vo) {
- super(vo);
- setPollingPeriod(vo.getUpdatePeriodType(), vo.getUpdatePeriods(), false);
- this.vo = vo;
- version = Version.getVersion(vo.getSnmpVersion(), vo.getCommunity(),
- vo.getSecurityName(), vo.getAuthProtocol(),
- vo.getAuthPassphrase(), vo.getPrivProtocol(),
- vo.getPrivPassphrase(), vo.getEngineId(),
- vo.getContextEngineId(), vo.getContextName());
- }
-
- @Override
- public void setPointValue(DataPointRT dataPoint, PointValueTime valueTime,
- SetPointSource source) {
- PDU request = version.createPDU();
- SnmpPointLocatorRT locator = dataPoint.getPointLocator();
- request.add(new VariableBinding(getOid(dataPoint), locator
- .valueToVariable(valueTime.getValue())));
- PDU response;
- try {
- response = snmp.set(request, target).getResponse();
- } catch (Exception ex) {
- // TODO add error handling
- response = null;
- }
-
- LocalizableMessage message = validatePdu(response);
- if (message != null)
- raiseEvent(PDU_EXCEPTION_EVENT, valueTime.getTime(), false, message);
- else
- dataPoint.setPointValue(valueTime, source);
- }
-
- @Override
- protected void doPoll(long time) {
- try {
- doPollImpl(time);
- } catch (Exception e) {
- raiseEvent(PDU_EXCEPTION_EVENT, time, true,
- DataSourceRT.getExceptionMessage(e));
- }
- }
-
- private void doPollImpl(long time) throws IOException {
- PDU request = version.createPDU();
- PDU response = null;
- VariableBinding vb;
-
- // Make a copy of the oids so that we can check if we got everything we
- // asked for, and
- // only what we asked for.
- List requestPoints = new ArrayList();
-
- // Add OID to send in the PDU.
- for (DataPointRT dp : dataPoints) {
- if (!getLocatorVO(dp).isTrapOnly()) {
- request.add(new VariableBinding(getOid(dp)));
- requestPoints.add(dp);
- }
- }
-
- if (request.getVariableBindings().size() == 0) {
- // Nothing to send, so don't bother.
- returnToNormal(PDU_EXCEPTION_EVENT, time);
- return;
- }
-
- // Get the response.
- long responseTime = System.currentTimeMillis();
- response = snmp.get(request, target).getResponse();
- responseTime = System.currentTimeMillis() - responseTime;
- log.debug("Snmp request/response time: " + responseTime);
-
- // Take a look at the response.
- LocalizableMessage message = validatePdu(response);
- if (message != null)
- raiseEvent(PDU_EXCEPTION_EVENT, time, true, message);
- else {
- boolean error = false;
-
- DataPointRT dp;
- for (int i = 0; i < response.size(); i++) {
- vb = response.get(i);
-
- // Find the command for this binding.
- dp = null;
- for (DataPointRT requestPoint : requestPoints) {
- if (getOid(requestPoint).equals(vb.getOid())) {
- dp = requestPoint;
- break;
- }
- }
-
- if (dp != null) {
- requestPoints.remove(dp);
-
- // Check if this is an error.
- Variable variable = vb.getVariable();
- if (vb.getVariable().isException()) {
- error = true;
- raiseEvent(
- PDU_EXCEPTION_EVENT,
- time,
- true,
- new LocalizableMessage("event.snmp.oidError",
- address, getOid(dp), variable
- .toString()));
- } else
- updatePoint(dp, variable, time);
- } else {
- error = true;
- raiseEvent(
- PDU_EXCEPTION_EVENT,
- time,
- true,
- new LocalizableMessage("event.snmp.unknownOid", vb
- .getOid(), address));
- }
- }
-
- for (DataPointRT requestPoint : requestPoints) {
- error = true;
- raiseEvent(PDU_EXCEPTION_EVENT, time, true,
- new LocalizableMessage("event.snmp.noBinding",
- getOid(requestPoint), address));
- }
-
- if (!error)
- // Deactivate any existing event.
- returnToNormal(PDU_EXCEPTION_EVENT, time);
- }
- }
-
- private LocalizableMessage validatePdu(PDU pdu) {
- if (pdu == null)
- return new LocalizableMessage("event.snmp.noResponse");
-
- if (pdu.getErrorIndex() != 0)
- return new LocalizableMessage("event.snmp.pduOidError", pdu.get(
- pdu.getErrorIndex() - 1).getOid(), pdu.getErrorStatusText());
-
- if (pdu.getErrorStatus() != 0)
- return new LocalizableMessage("event.snmp.pduErrorStatus",
- pdu.getErrorStatus(), pdu.getErrorStatusText());
-
- return null;
- }
-
- private OID getOid(DataPointRT dp) {
- return ((SnmpPointLocatorRT) dp.getPointLocator()).getOid();
- }
-
- private SnmpPointLocatorVO getLocatorVO(DataPointRT dp) {
- return ((SnmpPointLocatorRT) dp.getPointLocator()).getVO();
- }
-
- int getTrapPort() {
- return vo.getTrapPort();
- }
-
- String getLocalAddress() {
- return vo.getLocalAddress();
- }
-
- String getAddress() {
- return address;
- }
-
- void receivedTrap(PDU trap) {
- long time = System.currentTimeMillis();
- VariableBinding vb;
-
- // Take a look at the response.
- LocalizableMessage message = validatePdu(trap);
- if (message != null)
- raiseEvent(PDU_EXCEPTION_EVENT, time, false, message);
- else {
- synchronized (pointListChangeLock) {
- updateChangedPoints();
-
- for (int i = 0; i < trap.size(); i++) {
- vb = trap.get(i);
- boolean found = false;
-
- // Find the command for this binding.
- for (DataPointRT dp : dataPoints) {
- if (getOid(dp).equals(vb.getOid())) {
- updatePoint(dp, vb.getVariable(), time);
- found = true;
- }
- }
-
- if (!found)
- log.warn("Trap not handled: " + vb);
- }
- }
- }
- }
-
- private void updatePoint(DataPointRT dp, Variable variable, long time) {
- SnmpPointLocatorRT locator = dp.getPointLocator();
- dp.updatePointValue(new PointValueTime(locator
- .variableToValue(variable), time));
- }
-
- //
- // /
- // / Lifecycle
- // /
- //
- @Override
- public void initialize() {
- try {
- address = InetAddress.getByName(vo.getHost()).getHostAddress();
- target = version.getTarget(vo.getHost(), vo.getPort(),
- vo.getRetries(), vo.getTimeout());
- snmp = new Snmp(new DefaultUdpTransportMapping());
- snmp.listen();
-
- SnmpTrapRouter.addDataSource(this);
-
- // Deactivate any existing event.
- returnToNormal(DATA_SOURCE_EXCEPTION_EVENT,
- System.currentTimeMillis());
- } catch (Exception e) {
- raiseEvent(DATA_SOURCE_EXCEPTION_EVENT, System.currentTimeMillis(),
- true, DataSourceRT.getExceptionMessage(e));
- log.debug("Error while initializing data source", e);
- return;
- }
-
- super.initialize();
- }
-
- @Override
- public void terminate() {
- super.terminate();
-
- SnmpTrapRouter.removeDataSource(this);
-
- try {
- if (snmp != null)
- snmp.close();
- } catch (IOException e) {
- throw new ShouldNeverHappenException(e);
- }
- }
-}
+
+ enum MessageType{
+ oidError,
+ unknownOid,
+ undefined
+
+ }
+ class SnmpResponses {
+ PDU request = null;
+ PDU response = null;
+ long responseTime;
+
+ SnmpResponses(){}
+
+ public void setRequest(PDU request){
+
+ this.request = request;
+ }
+ public PDU getRequest(){
+
+ return this.request;
+ }
+ public PDU getResponseByGet() {
+
+ try {
+ startTime();
+ response = getResponse(true);
+ finishTime();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return response;
+ }
+ public PDU getResponseBySet(){
+ PDU response = null;
+ try {
+ startTime();
+ response = getResponse(false);
+ finishTime();
+ } catch (Exception ex) {
+ // TODO add error handling
+ response = null;
+ }
+ return response;
+ }
+ private PDU getResponse(boolean setOrGet) throws IOException {
+
+ return setOrGet?snmp.get(request, target).getResponse():snmp.set(request, target).getResponse();
+
+ }
+ private void startTime(){
+
+ responseTime = System.currentTimeMillis();
+
+ }
+ private void finishTime(){
+
+ responseTime = System.currentTimeMillis() - responseTime;
+ log.debug("Snmp request/response time: " + responseTime);
+
+ }
+ }
+
+ public static final int DATA_SOURCE_EXCEPTION_EVENT = 1;
+ public static final int PDU_EXCEPTION_EVENT = 2;
+ public static final int TRAP_NOT_HANDLED_EVENT = 3;
+
+ private final Log log = LogFactory.getLog(SnmpDataSourceRT.class);
+
+ private final SnmpDataSourceVO vo;
+ private final Version version;
+ private String address;
+ private Target target;
+ private Snmp snmp;
+ private int counterEmptyResponsesOrResponsesWithError;
+ private boolean deviceDidNotRespondDespiteTheCounterOfRetries = Boolean.FALSE;
+ private SnmpResponses snmpRequests;
+
+ public Snmp getSnmp() {
+ return snmp;
+ }
+
+ public SnmpDataSourceRT(SnmpDataSourceVO vo) {
+ super(vo);
+ setPollingPeriod(vo.getUpdatePeriodType(), vo.getUpdatePeriods(), false);
+ this.vo = vo;
+ version = Version.getVersion(vo.getSnmpVersion(), vo.getCommunity(),
+ vo.getSecurityName(), vo.getAuthProtocol(),
+ vo.getAuthPassphrase(), vo.getPrivProtocol(),
+ vo.getPrivPassphrase(), vo.getSecurityLevel(),
+ vo.getContextName());
+ snmpRequests = new SnmpResponses();
+ }
+
+ @Override
+ public void setPointValue(DataPointRT dataPoint, PointValueTime valueTime,
+ SetPointSource source) {
+ PDU request = version.createPDU();
+ SnmpPointLocatorRT locator = dataPoint.getPointLocator();
+ request.add(new VariableBinding(getOid(dataPoint), locator
+ .valueToVariable(valueTime.getValue())));
+ snmpRequests.setRequest(request);
+ PDU response = snmpRequests.getResponseBySet();
+
+ LocalizableMessage message = validatePdu(response);
+ if (message != null)
+ raiseEvent(PDU_EXCEPTION_EVENT, valueTime.getTime(), false, message);
+ else
+ dataPoint.setPointValue(valueTime, source);
+ }
+ public void setDeviceDidNotRespondDespiteTheCounterOfRetries(boolean deviceDidNotRespondDespiteTheCounterOfRetries) {
+ this.deviceDidNotRespondDespiteTheCounterOfRetries = deviceDidNotRespondDespiteTheCounterOfRetries;
+ log.info("Device did not respond despite the counter of retries.");
+ }
+ public void createSnmpAndStartListening(){
+ try {
+ initializeComponents();
+
+ } catch (Exception e) {
+ log.info(e.getMessage());
+ }
+ }
+ public boolean isSnmpConnectionIsAlive(){
+ if (target.getRetries() == counterEmptyResponsesOrResponsesWithError) {
+ setDeviceDidNotRespondDespiteTheCounterOfRetries(Boolean.TRUE);
+ return Boolean.FALSE;
+ }
+ else
+ return Boolean.TRUE;
+
+ }
+
+ @Override
+ protected void doPoll(long time) {
+ try {
+ doPollImpl(time);
+ } catch (Exception e) {
+ raiseEvent(PDU_EXCEPTION_EVENT, time, true,
+ DataSourceRT.getExceptionMessage(e));
+ }
+ }
+
+ private void doPollImpl(long time) throws IOException {
+ snmpRequests.setRequest(version.createPDU());
+ PDU request = snmpRequests.getRequest();
+ PDU response = null;
+ request.setType(PDU.GET);
+
+ VariableBinding vb;
+
+ // Make a copy of the oids so that we can check if we got everything we
+ // asked for, and
+ // only what we asked for.
+ List requestPoints = new ArrayList();
+
+ // Add OID to send in the PDU.
+ for (DataPointRT dp : dataPoints) {
+ if (!getLocatorVO(dp).isTrapOnly()) {
+ request.add(new VariableBinding(getOid(dp)));
+ requestPoints.add(dp);
+ }
+ }
+
+ ResponseEvent event = snmp.send(request, target);
+ if(event != null) {
+ response = event.getResponse();
+ LocalizableMessage message = validateResponseAndValidateStateOfConnection(response);
+ if (time == -1) {
+ if (!isSnmpConnectionIsAlive()) {
+ snmp.close();
+ }
+ } else {
+ if (!isSnmpConnectionIsAlive()) {
+// Common.ctx.getRuntimeManager().stopDataSourceAndDontJoinTermination(vo.getId());
+ } else if (message != null) {
+ raiseEvent(PDU_EXCEPTION_EVENT, time, true, message);
+ }
+ }
+ if (response.getErrorStatus() == PDU.noError) {
+ DataPointRT dp;
+ for (int i = 0; i < response.size(); i++) {
+ vb = response.get(i);
+ dp = setDataPoint(vb,requestPoints);
+ if (dp != null) {
+ requestPoints.remove(dp);
+ updatePoint(dp, vb.getVariable(), time);
+ }
+ }
+ } else {
+ raiseEvent(PDU_EXCEPTION_EVENT, time, true, validatePdu(response));
+
+ }
+ }
+
+ }
+ private DataPointRT setDataPoint(VariableBinding vb, List requestPoints){
+ for (DataPointRT requestPoint : requestPoints) {
+ if (getOid(requestPoint).equals(vb.getOid())) {
+ return requestPoint;
+ }
+ }
+ return null;
+ }
+ public LocalizableMessage validateResponseAndValidateStateOfConnection(PDU response){
+ LocalizableMessage message = validatePdu(response);
+
+ increaseCounterIfErrorExistOrNoResponseAppear(response);
+
+ return message;
+ }
+
+ /**
+ * if messageType is different that value 0 or 1
+ * then LocalizableMessage is created and is gived to raiseEvent method.
+ * Then result of this is true,otherwise (messageType == -1) is false.
+ *
+ * @param messageType
+ * @param vb
+ * @param dp
+ * @param time
+ * @return boolean
+ */
+ private boolean logEventsDependsOnMessageType(MessageType messageType, VariableBinding vb, DataPointRT dp, long time){
+ LocalizableMessage message=null;
+ switch(messageType) {
+ case oidError:
+ message=new LocalizableMessage(
+ "event.snmp.oidError",
+ address, getOid(dp), vb.getVariable());
+ break;
+ case unknownOid:
+ message=new LocalizableMessage(
+ "event.snmp.unknownOid",
+ vb.getOid(), address);
+ break;
+ }
+
+ if(messageType!=MessageType.undefined)
+ raiseEvent(PDU_EXCEPTION_EVENT,time,true,message);
+
+ return messageType!=MessageType.undefined;
+ }
+ private LocalizableMessage validatePdu(PDU pdu) {
+ if (pdu == null)
+ return new LocalizableMessage("event.snmp.noResponse");
+
+ if (pdu.getErrorIndex() != 0)
+ return new LocalizableMessage("event.snmp.pduOidError", pdu.get(
+ pdu.getErrorIndex() - 1).getOid(), pdu.getErrorStatusText());
+
+ if (pdu.getErrorStatus() != 0)
+ return new LocalizableMessage("event.snmp.pduErrorStatus",
+ pdu.getErrorStatus(), pdu.getErrorStatusText());
+
+ return null;
+ }
+
+ private void increaseCounterIfErrorExistOrNoResponseAppear(PDU pdu) {
+ if ((pdu == null) || (pdu.getErrorIndex() != 0) || (pdu.getErrorStatus() != 0)) {
+ ++counterEmptyResponsesOrResponsesWithError;
+ log.info("Counter Empty Responses Or Responses With Error: "+counterEmptyResponsesOrResponsesWithError);
+ }
+ }
+
+
+
+ private OID getOid(DataPointRT dp) {
+ return ((SnmpPointLocatorRT) dp.getPointLocator()).getOid();
+ }
+
+ private SnmpPointLocatorVO getLocatorVO(DataPointRT dp) {
+ return ((SnmpPointLocatorRT) dp.getPointLocator()).getVO();
+ }
+
+ int getTrapPort() {
+ return vo.getTrapPort();
+ }
+
+ boolean isTrapEnabled() {
+ return vo.isTrapEnabled();
+ }
+
+ String getLocalAddress() {
+ return vo.getLocalAddress();
+ }
+
+ String getAddress() {
+ return address;
+ }
+
+ Version getVersion() { return this.version; }
+
+ void receivedTrap(PDU trap) {
+ long time = System.currentTimeMillis();
+ VariableBinding vb;
+
+ // Take a look at the response.
+ LocalizableMessage message = validatePdu(trap);
+ if (message != null)
+ raiseEvent(PDU_EXCEPTION_EVENT, time, false, message);
+ else {
+ synchronized (pointListChangeLock) {
+ updateChangedPoints();
+
+ for (int i = 0; i < trap.getVariableBindings().size(); i++) {
+ vb = trap.get(i);
+ boolean found = false;
+
+ // Find the command for this binding.
+ for (DataPointRT dp : dataPoints) {
+ if (getOid(dp).equals(vb.getOid())) {
+ updatePoint(dp, vb.getVariable(), time);
+ found = true;
+ }
+ }
+
+ if (!found)
+ raiseEvent(TRAP_NOT_HANDLED_EVENT, time, false, new LocalizableMessage("event.snmp.trapNotHandled", vb));
+ log.warn("Trap not handled: " + vb);
+ }
+ }
+ }
+ }
+
+ private void updatePoint(DataPointRT dp, Variable variable, long time) {
+ SnmpPointLocatorRT locator = dp.getPointLocator();
+ dp.updatePointValue(new PointValueTime(locator
+ .variableToValue(variable), time));
+ }
+
+ //
+ // /
+ // / Lifecycle
+ // /
+ //
+ @Override
+ public void initialize() {
+ try {
+ initializeComponents();
+ counterEmptyResponsesOrResponsesWithError=0;
+ log.info("Counter Empty Responses Or Responses With Error is set 0.");
+
+ SnmpTrapRouter.addDataSource(this);
+
+ // Deactivate any existing event.
+ returnToNormal(DATA_SOURCE_EXCEPTION_EVENT,
+ System.currentTimeMillis());
+ } catch (Exception e) {
+ raiseEvent(DATA_SOURCE_EXCEPTION_EVENT, System.currentTimeMillis(),
+ true, DataSourceRT.getExceptionMessage(e));
+ log.debug("Error while initializing data source", e);
+ return;
+ }
+
+ super.initialize();
+ }
+ private void initializeComponents() throws IOException {
+ snmp = new Snmp(new DefaultUdpTransportMapping());
+
+ OctetString localEngineId = new OctetString(MPv3.createLocalEngineID()).substring(0,9);
+ USM usm = new USM(SecurityProtocols.getInstance(), localEngineId, 0);
+ SecurityModels.getInstance().addSecurityModel(usm);
+
+ version.addUser(snmp);
+ target = version.getTarget(vo.getHost(), vo.getPort(), vo.getRetries(), vo.getTimeout());
+
+ snmp.listen();
+
+ }
+ @Override
+ public void terminate() {
+ super.terminate();
+
+ SnmpTrapRouter.removeDataSource(this);
+
+ try {
+ if (snmp != null)
+ snmp.close();
+ } catch (IOException e) {
+ throw new ShouldNeverHappenException(e);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/com/serotonin/mango/rt/dataSource/snmp/SnmpPointLocatorRT.java b/src/com/serotonin/mango/rt/dataSource/snmp/SnmpPointLocatorRT.java
index 1ab9a64316..42e9179d40 100644
--- a/src/com/serotonin/mango/rt/dataSource/snmp/SnmpPointLocatorRT.java
+++ b/src/com/serotonin/mango/rt/dataSource/snmp/SnmpPointLocatorRT.java
@@ -2,7 +2,7 @@
Mango - Open Source M2M - http://mango.serotoninsoftware.com
Copyright (C) 2006-2011 Serotonin Software Technologies Inc.
@author Matthew Lohbihler
-
+
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
@@ -44,7 +44,7 @@
/**
* @author Matthew Lohbihler
- *
+ *
*/
public class SnmpPointLocatorRT extends PointLocatorRT {
private static final Log LOG = LogFactory.getLog(SnmpPointLocatorRT.class);
@@ -72,25 +72,25 @@ public SnmpPointLocatorVO getVO() {
public MangoValue variableToValue(Variable variable) {
switch (vo.getDataTypeId()) {
- case DataTypes.BINARY:
- return new BinaryValue(StringUtils.isEqual(variable.toString(), vo.getBinary0Value()));
-
- case DataTypes.MULTISTATE:
- return new MultistateValue(variable.toInt());
-
- case DataTypes.NUMERIC:
- if (variable instanceof OctetString) {
- try {
- return NumericValue.parseNumeric(variable.toString());
- }
- catch (NumberFormatException e) {
- // no op
+ case DataTypes.BINARY:
+ return new BinaryValue(StringUtils.isEqual(variable.toString(), vo.getBinary0Value()));
+
+ case DataTypes.MULTISTATE:
+ return new MultistateValue(variable.toInt());
+
+ case DataTypes.NUMERIC:
+ if (variable instanceof OctetString) {
+ try {
+ return NumericValue.parseNumeric(variable.toString());
+ }
+ catch (NumberFormatException e) {
+ // no op
+ }
}
- }
- return new NumericValue(variable.toInt());
+ return new NumericValue(variable.toInt());
- case DataTypes.ALPHANUMERIC:
- return new AlphanumericValue(variable.toString());
+ case DataTypes.ALPHANUMERIC:
+ return new AlphanumericValue(variable.toString());
}
@@ -103,40 +103,40 @@ public Variable valueToVariable(MangoValue value) {
public static Variable valueToVariableImpl(MangoValue value, int setType) {
switch (setType) {
- case SnmpPointLocatorVO.SetTypes.INTEGER_32:
- if (value instanceof NumericValue)
- return new Integer32(value.getIntegerValue());
- if (value instanceof BinaryValue)
- return new Integer32(value.getBooleanValue() ? 1 : 0);
+ case SnmpPointLocatorVO.SetTypes.INTEGER_32:
+ if (value instanceof NumericValue)
+ return new Integer32(value.getIntegerValue());
+ if (value instanceof BinaryValue)
+ return new Integer32(value.getBooleanValue() ? 1 : 0);
- LOG.warn("Can't convert value '" + value + "' (" + value.getDataType() + ") to Integer32");
- return new Integer32(0);
+ LOG.warn("Can't convert value '" + value + "' (" + value.getDataType() + ") to Integer32");
+ return new Integer32(0);
- case SnmpPointLocatorVO.SetTypes.OCTET_STRING:
- return new OctetString(DataTypes.valueToString(value));
+ case SnmpPointLocatorVO.SetTypes.OCTET_STRING:
+ return new OctetString(DataTypes.valueToString(value));
- case SnmpPointLocatorVO.SetTypes.OID:
- return new OID(DataTypes.valueToString(value));
+ case SnmpPointLocatorVO.SetTypes.OID:
+ return new OID(DataTypes.valueToString(value));
- case SnmpPointLocatorVO.SetTypes.IP_ADDRESS:
- return new IpAddress(DataTypes.valueToString(value));
+ case SnmpPointLocatorVO.SetTypes.IP_ADDRESS:
+ return new IpAddress(DataTypes.valueToString(value));
- case SnmpPointLocatorVO.SetTypes.COUNTER_32:
- return new Counter32((long) value.getDoubleValue());
+ case SnmpPointLocatorVO.SetTypes.COUNTER_32:
+ return new Counter32((long) value.getDoubleValue());
- case SnmpPointLocatorVO.SetTypes.GAUGE_32:
- return new Gauge32((long) value.getDoubleValue());
+ case SnmpPointLocatorVO.SetTypes.GAUGE_32:
+ return new Gauge32((long) value.getDoubleValue());
- case SnmpPointLocatorVO.SetTypes.TIME_TICKS:
- return new TimeTicks((long) value.getDoubleValue());
+ case SnmpPointLocatorVO.SetTypes.TIME_TICKS:
+ return new TimeTicks((long) value.getDoubleValue());
- case SnmpPointLocatorVO.SetTypes.OPAQUE:
- return new Opaque(DataTypes.valueToString(value).getBytes());
+ case SnmpPointLocatorVO.SetTypes.OPAQUE:
+ return new Opaque(DataTypes.valueToString(value).getBytes());
- case SnmpPointLocatorVO.SetTypes.COUNTER_64:
- return new Counter64((long) value.getDoubleValue());
+ case SnmpPointLocatorVO.SetTypes.COUNTER_64:
+ return new Counter64((long) value.getDoubleValue());
}
throw new ShouldNeverHappenException("Unknown set type id: " + setType);
}
-}
+}
\ No newline at end of file
diff --git a/src/com/serotonin/mango/rt/dataSource/snmp/SnmpTrapRouter.java b/src/com/serotonin/mango/rt/dataSource/snmp/SnmpTrapRouter.java
index e0911e43e4..8ed323951d 100644
--- a/src/com/serotonin/mango/rt/dataSource/snmp/SnmpTrapRouter.java
+++ b/src/com/serotonin/mango/rt/dataSource/snmp/SnmpTrapRouter.java
@@ -25,7 +25,6 @@
import org.snmp4j.CommandResponder;
import org.snmp4j.CommandResponderEvent;
import org.snmp4j.PDU;
-import org.snmp4j.PDUv1;
import org.snmp4j.Snmp;
import org.snmp4j.mp.CounterSupport;
import org.snmp4j.mp.DefaultCounterListener;
@@ -33,7 +32,6 @@
import org.snmp4j.transport.DefaultUdpTransportMapping;
import com.serotonin.ShouldNeverHappenException;
-import com.serotonin.util.StringUtils;
/**
* @author Matthew Lohbihler
@@ -42,11 +40,13 @@ public class SnmpTrapRouter {
private static SnmpTrapRouter instance;
public synchronized static void addDataSource(SnmpDataSourceRT ds) throws IOException {
- if (instance == null) {
- CounterSupport.getInstance().addCounterListener(new DefaultCounterListener());
- instance = new SnmpTrapRouter();
+ if(ds.isTrapEnabled()) {
+ if (instance == null) {
+ CounterSupport.getInstance().addCounterListener(new DefaultCounterListener());
+ instance = new SnmpTrapRouter();
+ }
+ instance.addDataSourceImpl(ds);
}
- instance.addDataSourceImpl(ds);
}
public synchronized static void removeDataSource(SnmpDataSourceRT ds) {
@@ -59,7 +59,9 @@ public synchronized static void removeDataSource(SnmpDataSourceRT ds) {
private void addDataSourceImpl(SnmpDataSourceRT ds) throws IOException {
PortListener l = getPortListener(ds.getTrapPort());
if (l == null) {
- l = new PortListener(ds.getTrapPort());
+ String localAddress = ds.getLocalAddress() != null && !ds.getLocalAddress().isEmpty()
+ ? ds.getLocalAddress() : "0.0.0.0";
+ l = new PortListener(ds.getTrapPort(), localAddress);
portListeners.add(l);
}
l.addDataSource(ds);
@@ -89,10 +91,10 @@ private class PortListener implements CommandResponder {
final int port;
final List dataSources = new LinkedList();
- PortListener(int port) throws IOException {
+ PortListener(int port, String localAddress) throws IOException {
this.port = port;
- snmp = new Snmp(new DefaultUdpTransportMapping(new UdpAddress("0.0.0.0/" + port)));
+ snmp = new Snmp(new DefaultUdpTransportMapping(new UdpAddress(localAddress + "/" + port)));
snmp.addCommandResponder(this);
snmp.listen();
}
@@ -100,22 +102,10 @@ private class PortListener implements CommandResponder {
public synchronized void processPdu(CommandResponderEvent evt) {
PDU command = evt.getPDU();
if (command != null) {
- // Get the peer address
- String peer = evt.getPeerAddress().toString();
- int slash = peer.indexOf('/');
- if (slash > 0)
- peer = peer.substring(0, slash);
-
- String localAddress = "";
- if (command instanceof PDUv1)
- localAddress = ((PDUv1) command).getAgentAddress().toString();
// Look for the peer in the data source list.
for (SnmpDataSourceRT ds : dataSources) {
- if (ds.getAddress().equals(peer)) {
- if (StringUtils.isEmpty(ds.getLocalAddress()) || localAddress.equals(ds.getLocalAddress()))
- ds.receivedTrap(command);
- }
+ ds.receivedTrap(command);
}
}
}
diff --git a/src/com/serotonin/mango/rt/dataSource/snmp/Version.java b/src/com/serotonin/mango/rt/dataSource/snmp/Version.java
index 89c679199b..a821181193 100644
--- a/src/com/serotonin/mango/rt/dataSource/snmp/Version.java
+++ b/src/com/serotonin/mango/rt/dataSource/snmp/Version.java
@@ -34,15 +34,14 @@
*/
abstract public class Version {
public static Version getVersion(int version, String community, String securityName, String authProtocol,
- String authPassphrase, String privProtocol, String privPassphrase, String engineId, String contextEngineId,
+ String authPassphrase, String privProtocol, String privPassphrase, int securityLevel,
String contextName) {
if (version == SnmpConstants.version1)
return new Version1(community);
else if (version == SnmpConstants.version2c)
return new Version2c(community);
else if (version == SnmpConstants.version3)
- return new Version3(securityName, authProtocol, authPassphrase, privProtocol, privPassphrase, engineId,
- contextEngineId, contextName);
+ return new Version3(securityName, authProtocol, authPassphrase, privProtocol, privPassphrase, securityLevel, contextName);
else
throw new IllegalArgumentException("Invalid version value: " + version);
}
@@ -59,6 +58,7 @@ public Target getTarget(String host, int port, int retries, int timeout) throws
Target target = getTarget();
Address address = new UdpAddress(InetAddress.getByName(host), port);
+ target.setVersion(getVersionId());
target.setAddress(address);
target.setRetries(retries);
target.setTimeout(timeout);
diff --git a/src/com/serotonin/mango/rt/dataSource/snmp/Version3.java b/src/com/serotonin/mango/rt/dataSource/snmp/Version3.java
index c2bccb13dd..5891f4c4b7 100644
--- a/src/com/serotonin/mango/rt/dataSource/snmp/Version3.java
+++ b/src/com/serotonin/mango/rt/dataSource/snmp/Version3.java
@@ -1,21 +1,3 @@
-/*
- Mango - Open Source M2M - http://mango.serotoninsoftware.com
- Copyright (C) 2006-2011 Serotonin Software Technologies Inc.
- @author Matthew Lohbihler
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see .
- */
package com.serotonin.mango.rt.dataSource.snmp;
import org.snmp4j.PDU;
@@ -23,19 +5,10 @@
import org.snmp4j.Snmp;
import org.snmp4j.Target;
import org.snmp4j.UserTarget;
-import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
-import org.snmp4j.security.AuthMD5;
-import org.snmp4j.security.AuthSHA;
-import org.snmp4j.security.PrivAES128;
-import org.snmp4j.security.PrivAES192;
-import org.snmp4j.security.PrivAES256;
-import org.snmp4j.security.PrivDES;
-import org.snmp4j.security.SecurityLevel;
-import org.snmp4j.security.SecurityModels;
-import org.snmp4j.security.SecurityProtocols;
-import org.snmp4j.security.USM;
-import org.snmp4j.security.UsmUser;
+import org.snmp4j.security.*;
+import org.snmp4j.security.nonstandard.PrivAES192With3DESKeyExtension;
+import org.snmp4j.security.nonstandard.PrivAES256With3DESKeyExtension;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
@@ -43,32 +16,42 @@
/**
* @author Matthew Lohbihler
- *
+ *
*/
public class Version3 extends Version {
+
+ private final int securityLevel;
+ private final OctetString contextName;
private final OctetString securityName;
private OID authProtocol;
private final OctetString authPassphrase;
private OID privProtocol;
private final OctetString privPassphrase;
- private final OctetString engineId;
- private final OctetString contextEngineId;
- private final OctetString contextName;
public Version3(String securityName, String authProtocol, String authPassphrase, String privProtocol,
- String privPassphrase, String engineId, String contextEngineId, String contextName) {
- this.securityName = SnmpUtils.createOctetString(securityName);
+ String privPassphrase, int securityLevel, String contextName) {
+
+ this.securityName = new OctetString(securityName);
+ this.securityLevel = securityLevel;
if (!StringUtils.isEmpty(authProtocol)) {
if (authProtocol.equals("MD5"))
this.authProtocol = AuthMD5.ID;
else if (authProtocol.equals("SHA"))
this.authProtocol = AuthSHA.ID;
+ else if (authProtocol.equals("HMAC128SHA224"))
+ this.authProtocol = AuthHMAC128SHA224.ID;
+ else if (authProtocol.equals("HMAC192SHA256"))
+ this.authProtocol = AuthHMAC192SHA256.ID;
+ else if (authProtocol.equals("HMAC256SHA384"))
+ this.authProtocol = AuthHMAC256SHA384.ID;
+ else if (authProtocol.equals("HMAC384SHA512"))
+ this.authProtocol = AuthHMAC384SHA512.ID;
else
throw new IllegalArgumentException("Authentication protocol unsupported: " + authProtocol);
}
- this.authPassphrase = SnmpUtils.createOctetString(authPassphrase);
+ this.authPassphrase = new OctetString(authPassphrase);
if (!StringUtils.isEmpty(privProtocol)) {
if (privProtocol.equals("DES"))
@@ -79,14 +62,18 @@ else if (privProtocol.equals("AES192"))
this.privProtocol = PrivAES192.ID;
else if (privProtocol.equals("AES256"))
this.privProtocol = PrivAES256.ID;
+ else if (privProtocol.equals("3DES"))
+ this.privProtocol = Priv3DES.ID;
+ else if (privProtocol.equals("AES192With3DES"))
+ this.privProtocol = PrivAES192With3DESKeyExtension.ID;
+ else if (privProtocol.equals("AES256With3DES"))
+ this.privProtocol = PrivAES256With3DESKeyExtension.ID;
else
throw new IllegalArgumentException("Privacy protocol " + privProtocol + " not supported");
}
- this.privPassphrase = SnmpUtils.createOctetString(privPassphrase);
- this.engineId = SnmpUtils.createOctetString(engineId);
- this.contextEngineId = SnmpUtils.createOctetString(contextEngineId);
- this.contextName = SnmpUtils.createOctetString(contextName);
+ this.privPassphrase = new OctetString(privPassphrase);
+ this.contextName = new OctetString(contextName);
}
@Override
@@ -96,10 +83,6 @@ public int getVersionId() {
@Override
public void addUser(Snmp snmp) {
- USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
- SecurityModels.getInstance().addSecurityModel(usm);
- if (engineId != null)
- snmp.setLocalEngine(engineId.getValue(), 0, 0);
snmp.getUSM().addUser(securityName,
new UsmUser(securityName, authProtocol, authPassphrase, privProtocol, privPassphrase));
}
@@ -107,15 +90,7 @@ public void addUser(Snmp snmp) {
@Override
public Target getTarget() {
UserTarget target = new UserTarget();
- if (authPassphrase != null) {
- if (privPassphrase != null)
- target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
- else
- target.setSecurityLevel(SecurityLevel.AUTH_NOPRIV);
- }
- else
- target.setSecurityLevel(SecurityLevel.NOAUTH_NOPRIV);
-
+ target.setSecurityLevel(securityLevel);
target.setSecurityName(securityName);
return target;
}
@@ -123,10 +98,9 @@ public Target getTarget() {
@Override
public PDU createPDU() {
ScopedPDU scopedPDU = new ScopedPDU();
- if (contextEngineId != null)
- scopedPDU.setContextEngineID(contextEngineId);
if (contextName != null)
scopedPDU.setContextName(contextName);
return scopedPDU;
}
-}
+
+}
\ No newline at end of file
diff --git a/src/com/serotonin/mango/vo/dataSource/snmp/SnmpDataSourceVO.java b/src/com/serotonin/mango/vo/dataSource/snmp/SnmpDataSourceVO.java
index bb5d45fd1d..c837174aba 100644
--- a/src/com/serotonin/mango/vo/dataSource/snmp/SnmpDataSourceVO.java
+++ b/src/com/serotonin/mango/vo/dataSource/snmp/SnmpDataSourceVO.java
@@ -2,7 +2,7 @@
Mango - Open Source M2M - http://mango.serotoninsoftware.com
Copyright (C) 2006-2011 Serotonin Software Technologies Inc.
@author Matthew Lohbihler
-
+
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
@@ -47,7 +47,7 @@
/**
* @author Matthew Lohbihler
- *
+ *
*/
@JsonRemoteEntity
public class SnmpDataSourceVO extends DataSourceVO {
@@ -57,6 +57,10 @@ public interface AuthProtocols {
String NONE = "";
String MD5 = "MD5";
String SHA = "SHA";
+ String HMAC128SHA224 = "HMAC128SHA224";
+ String HMAC192SHA256 = "HMAC192SHA256";
+ String HMAC256SHA384 = "HMAC256SHA384";
+ String HMAC384SHA512 = "HMAC384SHA512";
}
public interface PrivProtocols {
@@ -65,6 +69,9 @@ public interface PrivProtocols {
String AES128 = "AES128";
String AES192 = "AES192";
String AES256 = "AES256";
+ String DES3 = "3DES";
+ String AES192With3DES = "AES192With3DES";
+ String AES256With3DES = "AES256With3DES";
}
@Override
@@ -130,6 +137,8 @@ public SnmpPointLocatorVO createPointLocator() {
@JsonRemoteProperty
private String privPassphrase;
@JsonRemoteProperty
+ private int securityLevel;
+ @JsonRemoteProperty
private int retries = 2;
@JsonRemoteProperty
private int timeout = 1000;
@@ -137,6 +146,8 @@ public SnmpPointLocatorVO createPointLocator() {
@JsonRemoteProperty
private int updatePeriods = 5;
@JsonRemoteProperty
+ private boolean trapEnabled;
+ @JsonRemoteProperty
private int trapPort = SnmpConstants.DEFAULT_NOTIFICATION_RECEIVER_PORT;
@JsonRemoteProperty
private String localAddress;
@@ -165,14 +176,6 @@ public void setCommunity(String community) {
this.community = community;
}
- public String getContextEngineId() {
- return contextEngineId;
- }
-
- public void setContextEngineId(String contextEngineId) {
- this.contextEngineId = contextEngineId;
- }
-
public String getContextName() {
return contextName;
}
@@ -181,14 +184,6 @@ public void setContextName(String contextName) {
this.contextName = contextName;
}
- public String getEngineId() {
- return engineId;
- }
-
- public void setEngineId(String engineId) {
- this.engineId = engineId;
- }
-
public String getHost() {
return host;
}
@@ -269,6 +264,14 @@ public void setTimeout(int timeout) {
this.timeout = timeout;
}
+ public boolean isTrapEnabled() {
+ return trapEnabled;
+ }
+
+ public void setTrapEnabled(boolean trapEnabled) {
+ this.trapEnabled = trapEnabled;
+ }
+
public int getTrapPort() {
return trapPort;
}
@@ -285,6 +288,14 @@ public void setLocalAddress(String localAddress) {
this.localAddress = localAddress;
}
+ public int getSecurityLevel() {
+ return securityLevel;
+ }
+
+ public void setSecurityLevel(int securityLevel) {
+ this.securityLevel = securityLevel;
+ }
+
@Override
public void validate(DwrResponseI18n response) {
super.validate(response);
@@ -330,11 +341,11 @@ protected void addPropertiesImpl(List list) {
AuditEventType.addPropertyMessage(list, "dsEdit.snmp.authPassphrase", authPassphrase);
AuditEventType.addPropertyMessage(list, "dsEdit.snmp.privProtocol", privProtocol);
AuditEventType.addPropertyMessage(list, "dsEdit.snmp.privPassphrase", privPassphrase);
- AuditEventType.addPropertyMessage(list, "dsEdit.snmp.engineId", engineId);
- AuditEventType.addPropertyMessage(list, "dsEdit.snmp.contextEngine", contextEngineId);
AuditEventType.addPropertyMessage(list, "dsEdit.snmp.contextName", contextName);
+ AuditEventType.addPropertyMessage(list, "dsEdit.snmp.sl.label", securityLevel);
AuditEventType.addPropertyMessage(list, "dsEdit.snmp.retries", retries);
AuditEventType.addPropertyMessage(list, "dsEdit.snmp.timeout", timeout);
+ AuditEventType.addPropertyMessage(list, "dsEdit.snmp.trapEnabled", trapEnabled);
AuditEventType.addPropertyMessage(list, "dsEdit.snmp.trapPort", trapPort);
AuditEventType.addPropertyMessage(list, "dsEdit.snmp.localAddress", localAddress);
}
@@ -354,12 +365,11 @@ protected void addPropertyChangesImpl(List list, SnmpDataSou
AuditEventType.maybeAddPropertyChangeMessage(list, "dsEdit.snmp.privProtocol", from.privProtocol, privProtocol);
AuditEventType.maybeAddPropertyChangeMessage(list, "dsEdit.snmp.privPassphrase", from.privPassphrase,
privPassphrase);
- AuditEventType.maybeAddPropertyChangeMessage(list, "dsEdit.snmp.engineId", from.engineId, engineId);
- AuditEventType.maybeAddPropertyChangeMessage(list, "dsEdit.snmp.contextEngine", from.contextEngineId,
- contextEngineId);
AuditEventType.maybeAddPropertyChangeMessage(list, "dsEdit.snmp.contextName", from.contextName, contextName);
+ AuditEventType.maybeAddPropertyChangeMessage(list, "dsEdit.snmp.sl.label", from.securityLevel, securityLevel);
AuditEventType.maybeAddPropertyChangeMessage(list, "dsEdit.snmp.retries", from.retries, retries);
AuditEventType.maybeAddPropertyChangeMessage(list, "dsEdit.snmp.timeout", from.timeout, timeout);
+ AuditEventType.maybeAddPropertyChangeMessage(list, "dsEdit.snmp.trapEnabled", from.trapEnabled, trapEnabled);
AuditEventType.maybeAddPropertyChangeMessage(list, "dsEdit.snmp.trapPort", from.trapPort, trapPort);
AuditEventType.maybeAddPropertyChangeMessage(list, "dsEdit.snmp.localAddress", from.localAddress, localAddress);
}
@@ -370,7 +380,7 @@ protected void addPropertyChangesImpl(List list, SnmpDataSou
// /
//
private static final long serialVersionUID = -1;
- private static final int version = 2;
+ private static final int version = 3;
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeInt(version);
@@ -378,18 +388,18 @@ private void writeObject(ObjectOutputStream out) throws IOException {
out.writeInt(port);
out.writeInt(snmpVersion);
SerializationHelper.writeSafeUTF(out, community);
- SerializationHelper.writeSafeUTF(out, engineId);
- SerializationHelper.writeSafeUTF(out, contextEngineId);
SerializationHelper.writeSafeUTF(out, contextName);
SerializationHelper.writeSafeUTF(out, securityName);
SerializationHelper.writeSafeUTF(out, authProtocol);
SerializationHelper.writeSafeUTF(out, authPassphrase);
SerializationHelper.writeSafeUTF(out, privProtocol);
SerializationHelper.writeSafeUTF(out, privPassphrase);
+ out.writeInt(securityLevel);
out.writeInt(retries);
out.writeInt(timeout);
out.writeInt(updatePeriodType);
out.writeInt(updatePeriods);
+ out.writeBoolean(trapEnabled);
out.writeInt(trapPort);
SerializationHelper.writeSafeUTF(out, localAddress);
}
@@ -437,6 +447,25 @@ else if (ver == 2) {
updatePeriods = in.readInt();
trapPort = in.readInt();
localAddress = SerializationHelper.readSafeUTF(in);
+ } else if (ver == 3) {
+ host = SerializationHelper.readSafeUTF(in);
+ port = in.readInt();
+ snmpVersion = in.readInt();
+ community = SerializationHelper.readSafeUTF(in);
+ contextName = SerializationHelper.readSafeUTF(in);
+ securityName = SerializationHelper.readSafeUTF(in);
+ authProtocol = SerializationHelper.readSafeUTF(in);
+ authPassphrase = SerializationHelper.readSafeUTF(in);
+ privProtocol = SerializationHelper.readSafeUTF(in);
+ privPassphrase = SerializationHelper.readSafeUTF(in);
+ securityLevel = in.readInt();
+ retries = in.readInt();
+ timeout = in.readInt();
+ updatePeriodType = in.readInt();
+ updatePeriods = in.readInt();
+ trapEnabled = in.readBoolean();
+ trapPort = in.readInt();
+ localAddress = SerializationHelper.readSafeUTF(in);
}
}
@@ -453,4 +482,4 @@ public void jsonSerialize(Map map) {
super.jsonSerialize(map);
serializeUpdatePeriodType(map, updatePeriodType);
}
-}
+}
\ No newline at end of file
diff --git a/src/com/serotonin/mango/vo/dataSource/snmp/SnmpPointLocatorVO.java b/src/com/serotonin/mango/vo/dataSource/snmp/SnmpPointLocatorVO.java
index 8c0c07871f..ae5fd91920 100644
--- a/src/com/serotonin/mango/vo/dataSource/snmp/SnmpPointLocatorVO.java
+++ b/src/com/serotonin/mango/vo/dataSource/snmp/SnmpPointLocatorVO.java
@@ -2,7 +2,7 @@
Mango - Open Source M2M - http://mango.serotoninsoftware.com
Copyright (C) 2006-2011 Serotonin Software Technologies Inc.
@author Matthew Lohbihler
-
+
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
@@ -44,7 +44,7 @@
/**
* @author Matthew Lohbihler
- *
+ *
*/
@JsonRemoteEntity
public class SnmpPointLocatorVO extends AbstractPointLocatorVO implements JsonSerializable {
@@ -214,4 +214,4 @@ public void jsonDeserialize(JsonReader reader, JsonObject json) throws JsonExcep
public void jsonSerialize(Map map) {
serializeDataType(map);
}
-}
+}
\ No newline at end of file
diff --git a/src/com/serotonin/mango/web/dwr/DataSourceEditDwr.java b/src/com/serotonin/mango/web/dwr/DataSourceEditDwr.java
index 59d944e1ab..f111e897b8 100644
--- a/src/com/serotonin/mango/web/dwr/DataSourceEditDwr.java
+++ b/src/com/serotonin/mango/web/dwr/DataSourceEditDwr.java
@@ -42,6 +42,7 @@
import javax.management.remote.JMXServiceURL;
import javax.script.ScriptException;
+import com.serotonin.mango.web.dwr.beans.*;
import net.sf.mbus4j.Connection;
import net.sf.mbus4j.MBusAddressing;
import net.sf.mbus4j.TcpIpConnection;
@@ -246,2548 +247,2573 @@ private DwrResponseI18n tryDataSourceSave(DataSourceVO> ds) {
LOG.debug("Response: " + response.toString());
}
- return response;
- }
-
- @MethodFilter
- public void cancelTestingUtility() {
- Common.getUser().cancelTestingUtility();
- }
-
- @MethodFilter
- public List enableAllPoints() {
- User user = Common.getUser();
- if (user == null)
- return null;
-
- DataSourceVO> ds = user.getEditDataSource();
- if (ds.getId() == Common.NEW_ID)
- return null;
-
- List points = new DataPointDao().getDataPoints(ds.getId(),
- DataPointNameComparator.instance);
- for (DataPointVO dataPointVO : points) {
- if (!dataPointVO.isEnabled()) {
- Permissions.ensureDataSourcePermission(Common.getUser(),
- dataPointVO.getDataSourceId());
-
- RuntimeManager runtimeManager = Common.ctx.getRuntimeManager();
- dataPointVO.setEnabled(true);
- runtimeManager.saveDataPoint(dataPointVO);
- }
- }
- return points;
- }
-
- @MethodFilter
- public List getPoints() {
- User user = Common.getUser();
- if (user == null)
- return null;
-
- DataSourceVO> ds = user.getEditDataSource();
- if (ds.getId() == Common.NEW_ID)
- return null;
-
- List points = new DataPointDao().getDataPoints(ds.getId(),
- DataPointNameComparator.instance);
- return points;
- }
-
- @MethodFilter
- public DataPointVO getPoint(int pointId) {
- return getPoint(pointId, null);
- }
-
- private DataPointVO getPoint(int pointId, DataPointDefaulter defaulter) {
- DataSourceVO> ds = Common.getUser().getEditDataSource();
-
- DataPointVO dp;
- if (pointId == Common.NEW_ID) {
- dp = new DataPointVO();
- dp.setXid(new DataPointDao().generateUniqueXid());
- dp.setDataSourceId(ds.getId());
- dp.setPointLocator(ds.createPointLocator());
- dp.setEventDetectors(new ArrayList(0));
- if (defaulter != null)
- defaulter.setDefaultValues(dp);
- } else {
- dp = new DataPointDao().getDataPoint(pointId);
- if (dp != null && dp.getDataSourceId() != ds.getId())
- throw new RuntimeException("Data source id mismatch");
- }
-
- return dp;
- }
-
- private DwrResponseI18n validatePoint(int id, String xid, String name,
- PointLocatorVO locator, DataPointDefaulter defaulter) {
- DwrResponseI18n response = new DwrResponseI18n();
-
- DataPointVO dp = getPoint(id, defaulter);
- dp.setXid(xid);
- dp.setName(name);
- dp.setPointLocator(locator);
-
- if (StringUtils.isEmpty(xid))
- response.addContextualMessage("xid", "validate.required");
- else if (!new DataPointDao().isXidUnique(xid, id))
- response.addContextualMessage("xid", "validate.xidUsed");
- else if (StringUtils.isLengthGreaterThan(xid, 50))
- response.addContextualMessage("xid", "validate.notLongerThan", 50);
-
- if (StringUtils.isEmpty(name))
- response.addContextualMessage("name", "dsEdit.validate.required");
-
- locator.validate(response);
-
- if (!response.getHasMessages()) {
- Common.ctx.getRuntimeManager().saveDataPoint(dp);
- response.addData("id", dp.getId());
- response.addData("points", getPoints());
- }
-
- return response;
- }
-
- @MethodFilter
- public List deletePoint(int id) {
- DataPointVO dp = getPoint(id, null);
- if (dp != null)
- Common.ctx.getRuntimeManager().deleteDataPoint(dp);
-
- return getPoints();
- }
-
- @MethodFilter
- public Map toggleEditDataSource() {
- DataSourceVO> ds = Common.getUser().getEditDataSource();
- return super.toggleDataSource(ds.getId());
- }
-
- @MethodFilter
- public DwrResponseI18n togglePoint(int dataPointId) {
- DwrResponseI18n response = super.toggleDataPoint(dataPointId);
- response.addData("points", getPoints());
- return response;
- }
-
- @MethodFilter
- public List getAlarms() {
- DataSourceVO> ds = Common.getUser().getEditDataSource();
- List events = new EventDao()
- .getPendingEventsForDataSource(ds.getId(), Common.getUser()
- .getId());
- Collections.sort(events, new Comparator() {
- @Override
- public int compare(EventInstance lhs, EventInstance rhs) {
- // -1 - less than, 1 - greater than, 0 - equal, all inversed for descending
- return lhs.getActiveTimestamp() > rhs.getActiveTimestamp() ? -1 : (lhs.getActiveTimestamp() < rhs.getActiveTimestamp()) ? 1 : 0;
- }
- });
- List beans = new ArrayList();
- if (events != null) {
- for (EventInstance event : events)
- beans.add(new EventInstanceBean(event.isActive(), event
- .getAlarmLevel(), DateFunctions.getTime(event
- .getActiveTimestamp()), getMessage(event.getMessage())));
- }
- return beans;
- }
-
- @MethodFilter
- public void updateEventAlarmLevel(int eventId, int alarmLevel) {
- DataSourceVO> ds = Common.getUser().getEditDataSource();
- ds.setAlarmLevel(eventId, alarmLevel);
- }
-
- //
- //
- // Virtual stuff
- //
- @MethodFilter
- public DwrResponseI18n saveVirtualDataSource(String name, String xid,
- int updatePeriods, int updatePeriodType) {
- VirtualDataSourceVO ds = (VirtualDataSourceVO) Common.getUser()
- .getEditDataSource();
-
- ds.setXid(xid);
- ds.setName(name);
- ds.setUpdatePeriods(updatePeriods);
- ds.setUpdatePeriodType(updatePeriodType);
-
- return tryDataSourceSave(ds);
- }
-
- @MethodFilter
- public IntMessagePair[] getChangeTypes(int dataTypeId) {
- return ChangeTypeVO.getChangeTypes(dataTypeId);
- }
-
- @MethodFilter
- public DwrResponseI18n saveVirtualPointLocator(int id, String xid,
- String name, VirtualPointLocatorVO locator) {
- return validatePoint(id, xid, name, locator, null);
- }
-
- //
- //
- // Modbus common stuff
- //
- @MethodFilter
- public Map modbusScanUpdate() {
- Map result = new HashMap();
- ModbusNodeScanListener scan = Common.getUser().getTestingUtility(
- ModbusNodeScanListener.class);
- if (scan == null)
- return null;
-
- result.put("nodes", scan.getNodesFound());
- result.put("message", scan.getMessage());
- result.put("finished", scan.isFinished());
-
- return result;
- }
-
- @MethodFilter
- public DwrResponseI18n saveModbusPointLocator(int id, String xid,
- String name, ModbusPointLocatorVO locator) {
- return validatePoint(id, xid, name, locator, null);
- }
-
- private void testModbusPointLocator(ModbusMaster modbusMaster,
- ModbusPointLocatorVO locator, boolean serial,
- DwrResponseI18n response) {
- locator.validate(response);
- if (response.getHasMessages())
- return;
-
- try {
- BaseLocator> bl = ModbusDataSource.createModbusLocator(locator);
- modbusMaster.init();
- Object result = modbusMaster.getValue(bl);
- response.addData("result", new LocalizableMessage(
- "dsEdit.modbus.locatorTest.result", result));
- } catch (ModbusInitException e) {
- if (serial)
- response.addMessage(new LocalizableMessage(
- "dsEdit.modbus.locatorTestIp.startError", e
- .getMessage()));
- else
- response.addMessage(new LocalizableMessage(
- "dsEdit.modbus.locatorTestSerial.startError", e
- .getMessage()));
- } catch (ErrorResponseException e) {
- response.addMessage(new LocalizableMessage("common.default", e
- .getErrorResponse().getExceptionMessage()));
- } catch (ModbusTransportException e) {
- response.addMessage(ModbusDataSource.localExceptionMessage(e));
- } catch (IllegalCharsetNameException e) {
- response.addMessage(new LocalizableMessage(
- "validate.invalidCharset"));
- } finally {
- modbusMaster.destroy();
- }
- }
-
- private void testModbusData(ModbusMaster modbusMaster, int slaveId,
- int range, int offset, int length, boolean serial,
- DwrResponseI18n response) {
- boolean binary = range == RegisterRange.COIL_STATUS
- || range == RegisterRange.INPUT_STATUS;
- if (length > modbusMaster.getMaxReadCount(range))
- length = modbusMaster.getMaxReadCount(range);
- if (offset + length > 65536)
- length = 65536 - offset;
- response.addData("length", length);
-
- try {
- ModbusRequest mreq = new ModbusFactory().createReadRequest(slaveId,
- range, offset, length);
-
- modbusMaster.init();
- ReadResponse mres = (ReadResponse) modbusMaster.send(mreq);
- if (mres.isException())
- response.addMessage(new LocalizableMessage("common.default",
- mres.getExceptionMessage()));
- else {
- List results = new ArrayList();
- if (binary) {
- boolean[] data = mres.getBooleanData();
- for (int i = 0; i < length; i++)
- results.add(Integer.toString(offset + i) + " ==> "
- + Boolean.toString(data[i]));
- } else {
- short[] data = mres.getShortData();
- for (int i = 0; i < length; i++)
- results.add(Integer.toString(offset + i) + " ==> "
- + StreamUtils.toHex(data[i]));
- }
- response.addData("results", results);
- }
- } catch (ModbusIdException e) {
- response.addMessage(ModbusDataSource.localExceptionMessage(e));
- } catch (ModbusInitException e) {
- if (serial)
- response.addMessage(new LocalizableMessage(
- "dsEdit.modbus.locatorTestIp.startError", e
- .getMessage()));
- else
- response.addMessage(new LocalizableMessage(
- "dsEdit.modbus.locatorTestSerial.startError", e
- .getMessage()));
- } catch (ModbusTransportException e) {
- response.addMessage(ModbusDataSource.localExceptionMessage(e));
- } finally {
- modbusMaster.destroy();
- }
- }
-
- //
- //
- // Modbus serial stuff
- //
- @MethodFilter
- public DwrResponseI18n saveModbusSerialDataSource(String name, String xid,
- int updatePeriods, int updatePeriodType, boolean quantize,
- int timeout, int retries, boolean contiguousBatches,
- boolean createSlaveMonitorPoints, int maxReadBitCount,
- int maxReadRegisterCount, int maxWriteRegisterCount,
- String commPortId, int baudRate, int flowControlIn,
- int flowControlOut, int dataBits, int stopBits, int parity,
- String encoding, boolean echo, int concurrency) {
- ModbusSerialDataSourceVO ds = (ModbusSerialDataSourceVO) Common
- .getUser().getEditDataSource();
-
- ds.setXid(xid);
- ds.setName(name);
- ds.setUpdatePeriods(updatePeriods);
- ds.setUpdatePeriodType(updatePeriodType);
- ds.setQuantize(quantize);
- ds.setTimeout(timeout);
- ds.setRetries(retries);
- ds.setContiguousBatches(contiguousBatches);
- ds.setCreateSlaveMonitorPoints(createSlaveMonitorPoints);
- ds.setMaxReadBitCount(maxReadBitCount);
- ds.setMaxReadRegisterCount(maxReadRegisterCount);
- ds.setMaxWriteRegisterCount(maxWriteRegisterCount);
- ds.setCommPortId(commPortId);
- ds.setBaudRate(baudRate);
- ds.setFlowControlIn(flowControlIn);
- ds.setFlowControlOut(flowControlOut);
- ds.setDataBits(dataBits);
- ds.setStopBits(stopBits);
- ds.setParity(parity);
- ds.setEncodingStr(encoding);
- ds.setEcho(echo);
- ds.setConcurrency(concurrency);
-
- return tryDataSourceSave(ds);
- }
-
- @MethodFilter
- public String modbusSerialScan(int timeout, int retries, String commPortId,
- int baudRate, int flowControlIn, int flowControlOut, int dataBits,
- int stopBits, int parity, String encoding, int concurrency) {
- ModbusMaster modbusMaster;
- try {
- modbusMaster = createModbusSerialMaster(timeout, retries,
- commPortId, baudRate, flowControlIn, flowControlOut,
- dataBits, stopBits, parity, encoding, concurrency);
- } catch (Exception e) {
- return getMessage("dsEdit.modbus.scanError");
- }
- ModbusNodeScanListener scan = new ModbusNodeScanListener(
- getResourceBundle(), modbusMaster, true);
- Common.getUser().setTestingUtility(scan);
- return null;
- }
-
- @MethodFilter
- public DwrResponseI18n testModbusSerialLocator(int timeout, int retries,
- String commPortId, int baudRate, int flowControlIn,
- int flowControlOut, int dataBits, int stopBits, int parity,
- String encoding, int concurrency, ModbusPointLocatorVO locator) {
- DwrResponseI18n response = new DwrResponseI18n();
- ModbusMaster modbusMaster;
- try {
- modbusMaster = createModbusSerialMaster(timeout, retries,
- commPortId, baudRate, flowControlIn, flowControlOut,
- dataBits, stopBits, parity, encoding, concurrency);
- testModbusPointLocator(modbusMaster, locator, true, response);
- } catch (Exception e) {
- response.addMessage(new LocalizableMessage(
- "dsEdit.modbus.scanError"));
- }
- return response;
- }
-
- @MethodFilter
- public DwrResponseI18n testModbusSerialData(int timeout, int retries,
- String commPortId, int baudRate, int flowControlIn,
- int flowControlOut, int dataBits, int stopBits, int parity,
- String encoding, int concurrency, int slaveId, int range,
- int offset, int length) {
- DwrResponseI18n response = new DwrResponseI18n();
- ModbusMaster modbusMaster;
- try {
- modbusMaster = createModbusSerialMaster(timeout, retries,
- commPortId, baudRate, flowControlIn, flowControlOut,
- dataBits, stopBits, parity, encoding, concurrency);
- testModbusData(modbusMaster, slaveId, range, offset, length, true,
- response);
- } catch (Exception e) {
- response.addMessage(new LocalizableMessage(
- "dsEdit.modbus.scanError"));
- }
- return response;
- }
-
- private ModbusMaster createModbusSerialMaster(int timeout, int retries,
- String commPortId, int baudRate, int flowControlIn,
- int flowControlOut, int dataBits, int stopBits, int parity,
- String encoding, int concurrency) throws Exception {
- User user = Common.getUser();
- Permissions.ensureDataSourcePermission(user);
-
- if (StringUtils.isEmpty(commPortId))
- throw new Exception();
-
- SerialParameters params = new SerialParameters();
- params.setCommPortId(commPortId);
- params.setPortOwnerName("Modbus Serial Data Source Scan");
- params.setBaudRate(baudRate);
- params.setFlowControlIn(flowControlIn);
- params.setFlowControlOut(flowControlOut);
- params.setDataBits(dataBits);
- params.setStopBits(stopBits);
- params.setParity(parity);
-
- EncodingType encodingType = EncodingType.valueOf(encoding);
-
- ModbusMaster modbusMaster;
- if (encodingType == EncodingType.ASCII)
- modbusMaster = new ModbusFactory().createAsciiMaster(params);
- else
- modbusMaster = new ModbusFactory().createRtuMaster(params);
- modbusMaster.setTimeout(timeout);
- modbusMaster.setRetries(retries);
-
- return modbusMaster;
- }
-
- //
- //
- // Modbus IP stuff
- //
- @MethodFilter
- public DwrResponseI18n saveModbusIpDataSource(String name, String xid,
- int updatePeriods, int updatePeriodType, boolean quantize,
- int timeout, int retries, boolean contiguousBatches,
- boolean createSlaveMonitorPoints, int maxReadBitCount,
- int maxReadRegisterCount, int maxWriteRegisterCount,
- String transportType, String host, int port, boolean encapsulated,
- boolean createSocketMonitorPoint) {
- ModbusIpDataSourceVO ds = (ModbusIpDataSourceVO) Common.getUser()
- .getEditDataSource();
-
- ds.setXid(xid);
- ds.setName(name);
- ds.setUpdatePeriods(updatePeriods);
- ds.setUpdatePeriodType(updatePeriodType);
- ds.setQuantize(quantize);
- ds.setTimeout(timeout);
- ds.setRetries(retries);
- ds.setContiguousBatches(contiguousBatches);
- ds.setCreateSlaveMonitorPoints(createSlaveMonitorPoints);
- ds.setMaxReadBitCount(maxReadBitCount);
- ds.setMaxReadRegisterCount(maxReadRegisterCount);
- ds.setMaxWriteRegisterCount(maxWriteRegisterCount);
- ds.setTransportTypeStr(transportType);
- ds.setHost(host);
- ds.setPort(port);
- ds.setEncapsulated(encapsulated);
- ds.setCreateSocketMonitorPoint(createSocketMonitorPoint);
-
- return tryDataSourceSave(ds);
- }
-
- @MethodFilter
- public String modbusIpScan(int timeout, int retries, String transport,
- String host, int port, boolean encapsulated) {
- ModbusMaster modbusMaster = createModbusIpMaster(timeout, retries,
- transport, host, port, encapsulated);
- ModbusNodeScanListener scan = new ModbusNodeScanListener(
- getResourceBundle(), modbusMaster, false);
- Common.getUser().setTestingUtility(scan);
- return null;
- }
-
- @MethodFilter
- public DwrResponseI18n testModbusIpLocator(int timeout, int retries,
- String transport, String host, int port, boolean encapsulated,
- ModbusPointLocatorVO locator) {
- DwrResponseI18n response = new DwrResponseI18n();
- ModbusMaster modbusMaster = createModbusIpMaster(timeout, retries,
- transport, host, port, encapsulated);
- testModbusPointLocator(modbusMaster, locator, false, response);
- return response;
- }
-
- @MethodFilter
- public DwrResponseI18n testModbusIpData(int timeout, int retries,
- String transport, String host, int port, boolean encapsulated,
- int slaveId, int range, int offset, int length) {
- DwrResponseI18n response = new DwrResponseI18n();
- ModbusMaster modbusMaster = createModbusIpMaster(timeout, retries,
- transport, host, port, encapsulated);
- testModbusData(modbusMaster, slaveId, range, offset, length, false,
- response);
- return response;
- }
-
- private ModbusMaster createModbusIpMaster(int timeout, int retries,
- String transport, String host, int port, boolean encapsulated) {
- User user = Common.getUser();
- Permissions.ensureDataSourcePermission(user);
-
- IpParameters params = new IpParameters();
- params.setHost(host);
- params.setPort(port);
- params.setEncapsulated(encapsulated);
-
- TransportType transportType = TransportType.valueOf(transport);
-
- ModbusMaster modbusMaster;
- if (transportType == TransportType.TCP_LISTENER)
- modbusMaster = new ModbusFactory().createTcpListener(params);
- else if (transportType == TransportType.UDP)
- modbusMaster = new ModbusFactory().createUdpMaster(params);
- else
- modbusMaster = new ModbusFactory().createTcpMaster(params,
- transportType == TransportType.TCP_KEEP_ALIVE);
- modbusMaster.setTimeout(timeout);
- modbusMaster.setRetries(retries);
-
- return modbusMaster;
- }
-
- //
- //
- // SNMP stuff
- //
- @MethodFilter
- public DwrResponseI18n saveSnmpDataSource(String name, String xid,
- int updatePeriods, int updatePeriodType, String host, int port,
- int snmpVersion, String community, String securityName,
- String authProtocol, String authPassphrase, String privProtocol,
- String privPassphrase, String engineId, String contextEngineId,
- String contextName, int retries, int timeout, int trapPort,
- String localAddress) {
- SnmpDataSourceVO ds = (SnmpDataSourceVO) Common.getUser()
- .getEditDataSource();
-
- ds.setXid(xid);
- ds.setName(name);
- ds.setUpdatePeriods(updatePeriods);
- ds.setUpdatePeriodType(updatePeriodType);
- ds.setHost(host);
- ds.setPort(port);
- ds.setSnmpVersion(snmpVersion);
- ds.setCommunity(community);
- ds.setSecurityName(securityName);
- ds.setAuthProtocol(authProtocol);
- ds.setAuthPassphrase(authPassphrase);
- ds.setPrivProtocol(privProtocol);
- ds.setPrivPassphrase(privPassphrase);
- ds.setEngineId(engineId);
- ds.setContextEngineId(contextEngineId);
- ds.setContextName(contextName);
- ds.setRetries(retries);
- ds.setTimeout(timeout);
- ds.setTrapPort(trapPort);
- ds.setLocalAddress(localAddress);
-
- return tryDataSourceSave(ds);
- }
-
- @MethodFilter
- public DwrResponseI18n saveSnmpPointLocator(int id, String xid,
- String name, SnmpPointLocatorVO locator) {
- return validatePoint(id, xid, name, locator, null);
- }
-
- @MethodFilter
- public void snmpGetOid(String oid, String host, int port, int snmpVersion,
- String community, String securityName, String authProtocol,
- String authPassphrase, String privProtocol, String privPassphrase,
- String engineId, String contextEngineId, String contextName,
- int retries, int timeout) {
- User user = Common.getUser();
- Permissions.ensureDataSourcePermission(user);
-
- Version version = Version.getVersion(snmpVersion, community,
- securityName, authProtocol, authPassphrase, privProtocol,
- privPassphrase, engineId, contextEngineId, contextName);
- user.setTestingUtility(new SnmpOidGet(getResourceBundle(), host, port,
- version, oid, retries, timeout));
- }
-
- @MethodFilter
- public String snmpGetOidUpdate() {
- SnmpOidGet snmpOidGet = Common.getUser().getTestingUtility(
- SnmpOidGet.class);
- if (snmpOidGet == null)
- return null;
- return snmpOidGet.getResult();
- }
-
- //
- //
- // SQL stuff
- //
- @MethodFilter
- public DwrResponseI18n saveSqlDataSource(String name, String xid,
- int updatePeriods, int updatePeriodType, String driverClassname,
- String connectionUrl, String username, String password,
- String selectStatement, boolean rowBasedQuery) {
- SqlDataSourceVO ds = (SqlDataSourceVO) Common.getUser()
- .getEditDataSource();
-
- ds.setXid(xid);
- ds.setName(name);
- ds.setUpdatePeriods(updatePeriods);
- ds.setUpdatePeriodType(updatePeriodType);
- ds.setDriverClassname(driverClassname);
- ds.setConnectionUrl(connectionUrl);
- ds.setUsername(username);
- ds.setPassword(password);
- ds.setSelectStatement(selectStatement);
- ds.setRowBasedQuery(rowBasedQuery);
-
- return tryDataSourceSave(ds);
- }
-
- @MethodFilter
- public DwrResponseI18n saveSqlPointLocator(int id, String xid, String name,
- SqlPointLocatorVO locator) {
- return validatePoint(id, xid, name, locator, null);
- }
-
- @MethodFilter
- public void sqlTestStatement(String driverClassname, String connectionUrl,
- String username, String password, String selectStatement,
- boolean rowBasedQuery) {
- User user = Common.getUser();
- Permissions.ensureDataSourcePermission(user);
- user.setTestingUtility(new SqlStatementTester(getResourceBundle(),
- driverClassname, connectionUrl, username, password,
- selectStatement, rowBasedQuery));
- }
-
- @MethodFilter
- public Map sqlTestStatementUpdate() {
- Map result = new HashMap();
- SqlStatementTester statementTester = Common.getUser()
- .getTestingUtility(SqlStatementTester.class);
- if (statementTester == null)
- return null;
- if (!statementTester.isDone())
- return null;
-
- if (statementTester.getErrorMessage() != null)
- result.put("error", statementTester.getErrorMessage());
- else
- result.put("resultTable", statementTester.getResultTable());
- return result;
- }
-
- //
- //
- // HTTP receiver stuff
- //
- @MethodFilter
- public DwrResponseI18n saveHttpReceiverDataSource(String name, String xid,
- String[] ipWhiteList, String[] deviceIdWhiteList) {
- HttpReceiverDataSourceVO ds = (HttpReceiverDataSourceVO) Common
- .getUser().getEditDataSource();
-
- ds.setXid(xid);
- ds.setName(name);
- ds.setIpWhiteList(ipWhiteList);
- ds.setDeviceIdWhiteList(deviceIdWhiteList);
-
- return tryDataSourceSave(ds);
- }
-
- @MethodFilter
- public DwrResponseI18n saveHttpReceiverPointLocator(int id, String xid,
- String name, HttpReceiverPointLocatorVO locator) {
- return validatePoint(id, xid, name, locator, null);
- }
-
- @MethodFilter
- public void httpReceiverListenForData(String[] ipWhiteList,
- String[] deviceIdWhiteList) {
- User user = Common.getUser();
- Permissions.ensureDataSourcePermission(user);
- user.setTestingUtility(new HttpReceiverDataListener(
- getResourceBundle(), ipWhiteList, deviceIdWhiteList));
- }
-
- @MethodFilter
- public Map httpReceiverListenerUpdate() {
- Map result = new HashMap();
- HttpReceiverDataListener l = Common.getUser().getTestingUtility(
- HttpReceiverDataListener.class);
- if (l == null)
- return null;
-
- HttpReceiverData data = l.getData();
- if (data != null) {
- result.put("remoteIp", data.getRemoteIp());
- result.put("deviceId", data.getDeviceId());
- result.put("time", DateFunctions.getTime(data.getTime()));
- result.put("data", data.getData());
- }
- result.put("message", l.getMessage());
-
- return result;
- }
-
- @MethodFilter
- public String validateIpMask(String ipMask) {
- return IpAddressUtils.checkIpMask(ipMask);
- }
-
- //
- //
- // OneWire stuff
- //
- @MethodFilter
- public DwrResponseI18n saveOneWireDataSource(String name, String xid,
- String commPortId, int updatePeriodType, int updatePeriods,
- int rescanPeriodType, int rescanPeriods) {
- OneWireDataSourceVO ds = (OneWireDataSourceVO) Common.getUser()
- .getEditDataSource();
-
- ds.setXid(xid);
- ds.setName(name);
- ds.setCommPortId(commPortId);
- ds.setUpdatePeriodType(updatePeriodType);
- ds.setUpdatePeriods(updatePeriods);
- ds.setRescanPeriodType(rescanPeriodType);
- ds.setRescanPeriods(rescanPeriods);
-
- return tryDataSourceSave(ds);
- }
-
- @MethodFilter
- public DwrResponseI18n saveOneWirePointLocator(int id, String xid,
- String name, OneWirePointLocatorVO locator) {
- return validatePoint(id, xid, name, locator, null);
- }
-
- @MethodFilter
- public DwrResponseI18n readOneWireNetwork(String commPointId) {
- DwrResponseI18n response = new DwrResponseI18n();
-
- Network network = null;
- try {
- // Check for an RT that already has a network.
- OneWireDataSourceVO ds = (OneWireDataSourceVO) Common.getUser()
- .getEditDataSource();
- OneWireDataSourceRT rt = (OneWireDataSourceRT) Common.ctx
- .getRuntimeManager().getRunningDataSource(ds.getId());
- if (rt != null)
- // Use the existing one if it exists (i.e. initialized properly)
- network = rt.getNetwork();
-
- if (network == null)
- // Create a new one.
- network = new Network(commPointId);
-
- try {
- network.lock();
- network.quickInitialize();
-
- List addresses = network.getAddresses();
- List devices = new ArrayList();
- for (Long address : addresses) {
- NetworkPath path = network.getNetworkPath(address);
- if (!path.isCoupler())
- devices.add(path.getTargetInfo());
- }
-
- response.addData("devices", devices);
- } finally {
- network.unlock();
- }
- } catch (Exception e) {
- response.addGenericMessage("common.default", e.getMessage());
- } finally {
- try {
- if (network != null)
- network.terminate();
- } catch (OneWireException e) {
- // no op
- }
- }
-
- return response;
- }
-
- @MethodFilter
- public DataPointVO addOneWirePoint(String address) {
- DataPointVO dp = getPoint(Common.NEW_ID, null);
- OneWirePointLocatorVO locator = dp.getPointLocator();
- locator.setAddress(address);
- return dp;
- }
-
- //
- //
- // Meta stuff
- //
- @MethodFilter
- public DwrResponseI18n saveMetaDataSource(String name, String xid) {
- MetaDataSourceVO ds = (MetaDataSourceVO) Common.getUser()
- .getEditDataSource();
- ds.setXid(xid);
- ds.setName(name);
- return tryDataSourceSave(ds);
- }
-
- @MethodFilter
- public DwrResponseI18n saveMetaPointLocator(int id, String xid,
- String name, MetaPointLocatorVO locator) {
- return validatePoint(id, xid, name, locator, null);
- }
-
- @MethodFilter
- public DwrResponseI18n validateScript(String script,
- List context, int dataTypeId) {
- DwrResponseI18n response = new DwrResponseI18n();
-
- ScriptExecutor executor = new ScriptExecutor();
- try {
- Map convertedContext = executor
- .convertContext(context);
- PointValueTime pvt = executor.execute(script, convertedContext,
- System.currentTimeMillis(), dataTypeId, -1);
- if (pvt.getTime() == -1)
- response.addContextualMessage("script",
- "dsEdit.meta.test.success", pvt.getValue());
- else
- response.addContextualMessage("script",
- "dsEdit.meta.test.successTs", pvt.getValue(),
- DateFunctions.getTime(pvt.getTime()));
- } catch (DataPointStateException e) {
- response.addMessage("context", e.getLocalizableMessage());
- } catch (ScriptException e) {
- response.addContextualMessage("script",
- "dsEdit.meta.test.scriptError", e.getMessage());
- } catch (ResultTypeException e) {
- response.addMessage("script", e.getLocalizableMessage());
- }
-
- return response;
- }
-
- //
- //
- // BACnet I/P stuff
- //
- @MethodFilter
- public DwrResponseI18n saveBACnetIpDataSource(String name, String xid,
- int updatePeriods, int updatePeriodType, int deviceId,
- String broadcastAddress, int port, int timeout, int segTimeout,
- int segWindow, int retries, int covSubscriptionTimeoutMinutes,
- int maxReadMultipleReferencesSegmented,
- int maxReadMultipleReferencesNonsegmented) {
- BACnetIPDataSourceVO ds = (BACnetIPDataSourceVO) Common.getUser()
- .getEditDataSource();
-
- ds.setXid(xid);
- ds.setName(name);
- ds.setUpdatePeriods(updatePeriods);
- ds.setUpdatePeriodType(updatePeriodType);
- ds.setDeviceId(deviceId);
- ds.setBroadcastAddress(broadcastAddress);
- ds.setPort(port);
- ds.setTimeout(timeout);
- ds.setSegTimeout(segTimeout);
- ds.setSegWindow(segWindow);
- ds.setRetries(retries);
- ds.setCovSubscriptionTimeoutMinutes(covSubscriptionTimeoutMinutes);
- ds.setMaxReadMultipleReferencesSegmented(maxReadMultipleReferencesSegmented);
- ds.setMaxReadMultipleReferencesNonsegmented(maxReadMultipleReferencesNonsegmented);
-
- return tryDataSourceSave(ds);
- }
-
- @MethodFilter
- public DwrResponseI18n saveBACnetIPPointLocator(int id, String xid,
- String name, BACnetIPPointLocatorVO locator) {
- return validatePoint(id, xid, name, locator, null);
- }
-
- @MethodFilter
- public void sendBACnetWhoIs(int deviceId, String broadcastAddress,
- int port, int timeout, int segTimeout, int segWindow, int retries,
- int whoIsPort, int maxReadMultipleReferencesSegmented,
- int maxReadMultipleReferencesNonsegmented) {
- User user = Common.getUser();
- Permissions.ensureDataSourcePermission(user);
-
- BACnetDiscovery whoIs = new BACnetDiscovery(getResourceBundle(),
- deviceId, broadcastAddress, port, timeout, segTimeout,
- segWindow, retries, whoIsPort,
- maxReadMultipleReferencesSegmented,
- maxReadMultipleReferencesNonsegmented);
- user.setTestingUtility(whoIs);
- }
-
- @MethodFilter
- public Map bacnetWhoIsUpdate() {
- Map result = new HashMap();
- BACnetDiscovery test = Common.getUser().getTestingUtility(
- BACnetDiscovery.class);
- if (test == null)
- return null;
-
- test.addUpdateInfo(result);
-
- return result;
- }
-
- @MethodFilter
- public int getBACnetDeviceDetails(int index) {
- BACnetDiscovery test = Common.getUser().getTestingUtility(
- BACnetDiscovery.class);
- if (test == null)
- return index;
- test.getDeviceDetails(index);
- return -1;
- }
-
- @MethodFilter
- public DwrResponseI18n sendObjectListRequest(int deviceId,
- String broadcastAddress, int port, int timeout, int segTimeout,
- int segWindow, int retries, int maxReadMultipleReferencesSegmented,
- int maxReadMultipleReferencesNonsegmented, String remoteIp,
- int remotePort, int networkNumber, String networkAddress,
- int remoteDeviceId) {
- LocalDevice localDevice = new LocalDevice(deviceId, broadcastAddress);
- localDevice.setPort(port);
- localDevice.setTimeout(timeout);
- localDevice.setSegTimeout(segTimeout);
- localDevice.setSegWindow(segWindow);
- localDevice.setRetries(retries);
- localDevice
- .setMaxReadMultipleReferencesSegmented(maxReadMultipleReferencesSegmented);
- localDevice
- .setMaxReadMultipleReferencesNonsegmented(maxReadMultipleReferencesNonsegmented);
-
- DwrResponseI18n result = new DwrResponseI18n();
- try {
- localDevice.initialize();
-
- Address address = new Address(InetAddress.getByName(remoteIp)
- .getAddress(), remotePort);
- com.serotonin.bacnet4j.Network network = null;
- if (!StringUtils.isEmpty(networkAddress))
- network = new com.serotonin.bacnet4j.Network(networkNumber,
- networkAddress);
- RemoteDevice d = localDevice.findRemoteDevice(address, network,
- remoteDeviceId);
-
- List details = BACnetDiscovery.getDetails(
- localDevice, d);
-
- result.addData("deviceAddress", d.getAddress().toIpString());
- result.addData("deviceName", d.getName());
- result.addData("deviceIp", d.getAddress().toIpString());
- result.addData("devicePort", d.getAddress().getPort());
- network = d.getNetwork();
- if (network != null) {
- result.addData("deviceNetworkNumber",
- network.getNetworkNumber());
- result.addData("deviceNetworkAddress",
- network.getNetworkAddressDottedString());
- }
- result.addData("deviceInstanceNumber", d.getObjectIdentifier()
- .getInstanceNumber());
- result.addData("deviceDescription",
- BACnetDiscovery.getDeviceDescription(d));
- result.addData("deviceDetails", details);
- } catch (Exception e) {
- result.addData("error", e.getMessage());
- } finally {
- localDevice.terminate();
- }
-
- return result;
- }
-
- @MethodFilter
- public DataPointVO addBacnetPoint(String ip, int port, int networkNumber,
- String networkAddress, int deviceInstanceNumber,
- BACnetObjectBean bean) {
- DataPointVO dp = getPoint(Common.NEW_ID, null);
- BACnetIPPointLocatorVO locator = dp.getPointLocator();
-
- dp.setName(bean.getObjectName());
-
- // Default some of the locator values.
- locator.setRemoteDeviceIp(ip);
- locator.setRemoteDevicePort(port);
- locator.setNetworkNumber(networkNumber);
- locator.setNetworkAddress(networkAddress);
- locator.setRemoteDeviceInstanceNumber(deviceInstanceNumber);
- locator.setObjectTypeId(bean.getObjectTypeId());
- locator.setObjectInstanceNumber(bean.getInstanceNumber());
- locator.setPropertyIdentifierId(PropertyIdentifier.presentValue
- .intValue());
- locator.setDataTypeId(bean.getDataTypeId());
- locator.setUseCovSubscription(bean.isCov());
-
- // We would like to default text renderer values too, but it's rather
- // inconvenient to do.
-
- return dp;
- }
-
- //
- //
- // HTTP Retriever stuff
- //
- @MethodFilter
- public DwrResponseI18n saveHttpRetrieverDataSource(String name, String xid,
- int updatePeriods, int updatePeriodType, String url,
- int timeoutSeconds, int retries, boolean stop) {
- HttpRetrieverDataSourceVO ds = (HttpRetrieverDataSourceVO) Common
- .getUser().getEditDataSource();
-
- ds.setXid(xid);
- ds.setName(name);
- ds.setUpdatePeriods(updatePeriods);
- ds.setUpdatePeriodType(updatePeriodType);
- ds.setUrl(url);
- ds.setTimeoutSeconds(timeoutSeconds);
- ds.setRetries(retries);
- ds.setStop(stop);
-
- return tryDataSourceSave(ds);
- }
-
- @MethodFilter
- public DwrResponseI18n saveHttpRetrieverDataSourceWithReactivationOptions(String name, String xid,
- int updatePeriods, int updatePeriodType, String url,
- int timeoutSeconds, int retries, boolean stop, boolean sleep, short typeReactivation, short valueReactivation) {
- HttpRetrieverDataSourceVO ds = (HttpRetrieverDataSourceVO) Common
- .getUser().getEditDataSource();
-
- ds.setXid(xid);
- ds.setName(name);
- ds.setUpdatePeriods(updatePeriods);
- ds.setUpdatePeriodType(updatePeriodType);
- ds.setUrl(url);
- ds.setTimeoutSeconds(timeoutSeconds);
- ds.setRetries(retries);
- ds.setStop(stop);
- ReactivationDs rDs = new ReactivationDs(sleep, typeReactivation, valueReactivation);
- ds.setReactivation(rDs);
-
- DwrResponseI18n result;
-
- if (ds.getId() > 0) {
- ReactivationManager.getInstance().stopReactivation(ds.getId());
- }
- result = tryDataSourceSave(ds);
-
- if (sleep) {
- ReactivationManager.getInstance().startReactivation(ds.getId());
- }
-
- return result;
- }
-
-
- @MethodFilter
- public DwrResponseI18n saveHttpRetrieverPointLocator(int id, String xid,
- String name, HttpRetrieverPointLocatorVO locator) {
- return validatePoint(id, xid, name, locator, null);
- }
-
- @MethodFilter
- public String testHttpRetrieverValueParams(String url, int timeoutSeconds,
- int retries, String valueRegex, int dataTypeId, String valueFormat) {
- try {
- String data = HttpRetrieverDataSourceRT.getData(url,
- timeoutSeconds, retries);
-
- Pattern valuePattern = Pattern.compile(valueRegex);
- DecimalFormat decimalFormat = null;
- if (dataTypeId == DataTypes.NUMERIC
- && !StringUtils.isEmpty(valueFormat))
- decimalFormat = new DecimalFormat(valueFormat);
- MangoValue value = DataSourceUtils.getValue(valuePattern, data,
- dataTypeId, valueFormat, null, decimalFormat, null);
- return getMessage("common.result") + ": " + value.toString();
- } catch (LocalizableException e) {
- return getMessage(e.getLocalizableMessage());
- } catch (Exception e) {
- return e.getMessage();
- }
- }
-
- @MethodFilter
- public String testHttpRetrieverTimeParams(String url, int timeoutSeconds,
- int retries, String timeRegex, String timeFormat) {
- try {
- String data = HttpRetrieverDataSourceRT.getData(url,
- timeoutSeconds, retries);
-
- Pattern timePattern = Pattern.compile(timeRegex);
- DateFormat dateFormat = new SimpleDateFormat(timeFormat);
- long time = DataSourceUtils.getValueTime(
- System.currentTimeMillis(), timePattern, data, dateFormat,
- null);
- return DateFunctions.getTime(time);
- } catch (LocalizableException e) {
- return getMessage(e.getLocalizableMessage());
- } catch (Exception e) {
- return e.getMessage();
- }
- }
-
- //
- //
- // HTTP Image stuff
- //
- @MethodFilter
- public DwrResponseI18n saveHttpImageDataSource(String name, String xid,
- int updatePeriods, int updatePeriodType) {
- HttpImageDataSourceVO ds = (HttpImageDataSourceVO) Common.getUser()
- .getEditDataSource();
-
- ds.setXid(xid);
- ds.setName(name);
- ds.setUpdatePeriods(updatePeriods);
- ds.setUpdatePeriodType(updatePeriodType);
-
- return tryDataSourceSave(ds);
- }
-
- @MethodFilter
- public DwrResponseI18n saveHttpImagePointLocator(int id, String xid,
- String name, HttpImagePointLocatorVO locator) {
- return validatePoint(id, xid, name, locator, new DataPointDefaulter() {
- @Override
- public void setDefaultValues(DataPointVO dp) {
- if (dp.isNew())
- dp.setLoggingType(DataPointVO.LoggingTypes.NONE);
- }
- });
- }
-
- //
- //
- // POP3 Email stuff
- //
- @MethodFilter
- public DwrResponseI18n savePop3DataSource(String name, String xid,
- int updatePeriods, int updatePeriodType, String pop3Server,
- String username, String password) {
- Pop3DataSourceVO ds = (Pop3DataSourceVO) Common.getUser()
- .getEditDataSource();
-
- ds.setXid(xid);
- ds.setName(name);
- ds.setUpdatePeriods(updatePeriods);
- ds.setUpdatePeriodType(updatePeriodType);
- ds.setPop3Server(pop3Server);
- ds.setUsername(username);
- ds.setPassword(password);
-
- return tryDataSourceSave(ds);
- }
-
- @MethodFilter
- public DwrResponseI18n savePop3PointLocator(int id, String xid,
- String name, Pop3PointLocatorVO locator) {
- return validatePoint(id, xid, name, locator, null);
- }
-
- @MethodFilter
- public String testPop3ValueParams(String testData, String valueRegex,
- int dataTypeId, String valueFormat) {
- try {
- Pattern valuePattern = Pattern.compile(valueRegex);
- DecimalFormat decimalFormat = null;
- if (dataTypeId == DataTypes.NUMERIC
- && !StringUtils.isEmpty(valueFormat))
- decimalFormat = new DecimalFormat(valueFormat);
- MangoValue value = DataSourceUtils.getValue(valuePattern, testData,
- dataTypeId, valueFormat, null, decimalFormat, null);
- return getMessage("common.result") + ": " + value.toString();
- } catch (LocalizableException e) {
- return getMessage(e.getLocalizableMessage());
- } catch (Exception e) {
- return e.getMessage();
- }
- }
-
- @MethodFilter
- public String testPop3TimeParams(String testData, String timeRegex,
- String timeFormat) {
- try {
- Pattern timePattern = Pattern.compile(timeRegex);
- DateFormat dateFormat = new SimpleDateFormat(timeFormat);
- long time = DataSourceUtils.getValueTime(
- System.currentTimeMillis(), timePattern, testData,
- dateFormat, null);
- return DateFunctions.getTime(time);
- } catch (Exception e) {
- return e.getMessage();
- }
- }
-
- //
- //
- // NMEA stuff
- //
- @MethodFilter
- public DwrResponseI18n saveNmeaDataSource(String name, String xid,
- String commPortId, int baudRate, int resetTimeout) {
- NmeaDataSourceVO ds = (NmeaDataSourceVO) Common.getUser()
- .getEditDataSource();
-
- ds.setXid(xid);
- ds.setName(name);
- ds.setCommPortId(commPortId);
- ds.setBaudRate(baudRate);
- ds.setResetTimeout(resetTimeout);
-
- return tryDataSourceSave(ds);
- }
-
- @MethodFilter
- public DwrResponseI18n saveNmeaPointLocator(int id, String xid,
- String name, NmeaPointLocatorVO locator) {
- return validatePoint(id, xid, name, locator, null);
- }
-
- @MethodFilter
- public void nmeaListenForMessages(String commPortId, int baudRate) {
- User user = Common.getUser();
- Permissions.ensureDataSourcePermission(user);
- user.setTestingUtility(new NmeaUtilListener(getResourceBundle(),
- commPortId, baudRate));
- }
-
- @MethodFilter
- public Map nmeaListenerUpdate() {
- NmeaUtilListener l = Common.getUser().getTestingUtility(
- NmeaUtilListener.class);
- if (l == null)
- return null;
-
- Map result = new HashMap();
- result.put("messages", l.getMessages());
- result.put("message", l.getMessage());
-
- return result;
- }
-
- //
- //
- // Galil stuff
- //
- @MethodFilter
- public DwrResponseI18n saveGalilDataSource(String name, String xid,
- String host, int port, int timeout, int retries, int updatePeriods,
- int updatePeriodType) {
- GalilDataSourceVO ds = (GalilDataSourceVO) Common.getUser()
- .getEditDataSource();
-
- ds.setXid(xid);
- ds.setName(name);
- ds.setHost(host);
- ds.setPort(port);
- ds.setTimeout(timeout);
- ds.setRetries(retries);
- ds.setUpdatePeriods(updatePeriods);
- ds.setUpdatePeriodType(updatePeriodType);
-
- return tryDataSourceSave(ds);
- }
-
- @MethodFilter
- public DwrResponseI18n saveGalilPointLocator(int id, String xid,
- String name, GalilPointLocatorVO locator) {
- return validatePoint(id, xid, name, locator, null);
- }
-
- @MethodFilter
- public String galilTestCommand(String host, int port, int timeout,
- String command) {
- User user = Common.getUser();
- Permissions.ensureDataSourcePermission(user);
-
- try {
- GalilCommandTester tester = new GalilCommandTester(
- getResourceBundle(), host, port, timeout, command);
- try {
- tester.join();
- return tester.getResult();
- } catch (InterruptedException e) {
- return e.getMessage();
- }
- } catch (IOException e) {
- return e.getMessage();
- }
- }
-
- //
- //
- // EBI25 stuff
- //
- @MethodFilter
- public DwrResponseI18n saveEBI25DataSource(String name, String xid,
- int updatePeriods, int updatePeriodType, int timeout, int retries,
- String host, int port, boolean keepAlive) {
- EBI25DataSourceVO ds = (EBI25DataSourceVO) Common.getUser()
- .getEditDataSource();
-
- ds.setXid(xid);
- ds.setName(name);
- ds.setUpdatePeriods(updatePeriods);
- ds.setUpdatePeriodType(updatePeriodType);
- ds.setTimeout(timeout);
- ds.setRetries(retries);
- ds.setHost(host);
- ds.setPort(port);
- ds.setKeepAlive(keepAlive);
-
- return tryDataSourceSave(ds);
- }
-
- @MethodFilter
- public EBI25InterfaceReader ebi25ReadInterface(String host, int port,
- boolean keepAlive, int timeout, int retries) {
- User user = Common.getUser();
- Permissions.ensureDataSourcePermission(user);
- EBI25DataSourceVO ds = (EBI25DataSourceVO) Common.getUser()
- .getEditDataSource();
-
- EBI25InterfaceReader reader = new EBI25InterfaceReader(
- getResourceBundle(), ds, host, port, keepAlive, timeout,
- retries);
-
- if (reader.getErrorMessage() == null) {
- tryDataSourceSave(ds);
- reader.setPoints(getPoints());
- }
-
- return reader;
- }
-
- @MethodFilter
- public LocalizableMessage ebi25SyncTime(String host, int port, int timeout,
- int retries) {
- return new EBI25InterfaceUpdater().updateSysTime(host, port, timeout,
- retries);
- }
-
- @MethodFilter
- public DwrResponseI18n saveEBI25PointLocator(int id, String xid,
- String name, final EBI25PointLocatorVO locator) {
- DwrResponseI18n response = new DwrResponseI18n();
-
- if (locator.getType() == EBI25PointLocatorVO.TYPE_VALUE) {
- EBI25DataSourceVO ds = (EBI25DataSourceVO) Common.getUser()
- .getEditDataSource();
-
- if (locator.getSampleRate() < 1)
- response.addContextualMessage("sampleRate",
- "validate.greaterThanZero");
- else {
- // Try to update the EBI25 interface
- LocalizableMessage errorMessage = new EBI25InterfaceUpdater()
- .updateLogger(ds.getHost(), ds.getPort(),
- ds.getTimeout(), ds.getRetries(), locator);
-
- if (errorMessage == null) {
- response = validatePoint(id, xid, name, locator,
- new DataPointDefaulter() {
- @Override
- public void setDefaultValues(DataPointVO dp) {
- // Update the point's high/low detectors
- // with the locator values.
- PointEventDetectorVO high = EBI25Constants
- .findDetector(
- dp.getEventDetectors(),
- true);
- if (high != null)
- high.setLimit(locator.getHighLimit());
-
- PointEventDetectorVO low = EBI25Constants
- .findDetector(
- dp.getEventDetectors(),
- false);
- if (low != null)
- low.setLimit(locator.getLowLimit());
- }
- });
- } else
- response.addMessage("sampleRate", errorMessage);
- }
- } else
- response = validatePoint(id, xid, name, locator, null);
-
- return response;
- }
-
- //
- //
- // VMStat stuff
- //
- @MethodFilter
- public DwrResponseI18n saveVMStatDataSource(String name, String xid,
- int pollSeconds, int outputScale) {
- VMStatDataSourceVO ds = (VMStatDataSourceVO) Common.getUser()
- .getEditDataSource();
-
- ds.setXid(xid);
- ds.setName(name);
- ds.setPollSeconds(pollSeconds);
- ds.setOutputScale(outputScale);
-
- return tryDataSourceSave(ds);
- }
-
- @MethodFilter
- public DwrResponseI18n saveVMStatPointLocator(int id, String xid,
- String name, VMStatPointLocatorVO locator) {
- return validatePoint(id, xid, name, locator, null);
- }
-
- //
- //
- // Viconics stuff
- //
- @MethodFilter
- public DwrResponseI18n saveViconicsDataSource(String name, String xid,
- String commPortId, int panId, int channel, int timeout,
- int retries, int networkTimeoutSeconds,
- int deviceWarningTimeoutSeconds, int deviceRemoveTimeoutSeconds,
- int pointValueMinimumFreshnessSeconds, boolean convertToCelsius) {
- ViconicsDataSourceVO ds = (ViconicsDataSourceVO) Common.getUser()
- .getEditDataSource();
-
- ds.setXid(xid);
- ds.setName(name);
- ds.setCommPortId(commPortId);
- ds.setPanId(panId);
- ds.setChannel(channel);
- ds.setTimeout(timeout);
- ds.setRetries(retries);
- ds.setNetworkTimeoutSeconds(networkTimeoutSeconds);
- ds.setDeviceWarningTimeoutSeconds(deviceWarningTimeoutSeconds);
- ds.setDeviceRemoveTimeoutSeconds(deviceRemoveTimeoutSeconds);
- ds.setPointValueMinimumFreshnessSeconds(pointValueMinimumFreshnessSeconds);
- ds.setConvertToCelsius(convertToCelsius);
-
- return tryDataSourceSave(ds);
- }
-
- @MethodFilter
- public DwrResponseI18n saveViconicsPointLocator(int id, String xid,
- String name, ViconicsPointLocatorVO locator) {
- return validatePoint(id, xid, name, locator, null);
- }
-
- @MethodFilter
- public DwrResponseI18n getRfModuleInfo() {
- ViconicsDataSourceVO ds = (ViconicsDataSourceVO) Common.getUser()
- .getEditDataSource();
-
- ViconicsDataSourceRT rt = (ViconicsDataSourceRT) Common.ctx
- .getRuntimeManager().getRunningDataSource(ds.getId());
- DwrResponseI18n response = new DwrResponseI18n();
-
- if (rt == null)
- response.addGenericMessage("dsEdit.viconics.dataSourceNotStarted");
- else {
- try {
- NetworkIdentifyResponse res = rt
- .send(new NetworkIdentifyRequest());
-
- Map rfm = new HashMap();
- rfm.put("firmware", ViconicsNetwork.getRevisionString(res
- .getZigbeeFirmwareRevision()));
- rfm.put("networkAddr",
- Integer.toString(res.getZigbeeNetworkAddress()));
- rfm.put("ieee", ViconicsNetwork.getIeeeString(res.getIeee()));
- rfm.put("chipRevision", Integer.toString(res.getChipRevision()));
- response.addData("rfm", rfm);
-
- List |