code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
@ArgumentsChecked
@Throws(IllegalNullArgumentException.class)
public static int checkLong(@Nonnull final Number number) {
Check.notNull(number, "number");
if (!isInLongRange(number)) {
throw new IllegalNumberRangeException(number.toString(), LONG_MIN, LONG_MAX);
}
return number.intValue();
} | Checks if a given number is in the range of a long.
@param number
a number which should be in the range of a long (positive or negative)
@see java.lang.Long#MIN_VALUE
@see java.lang.Long#MAX_VALUE
@return number as a long (rounding might occur) |
@ArgumentsChecked
@Throws(IllegalNullArgumentException.class)
public static short checkShort(@Nonnull final Number number) {
Check.notNull(number, "number");
if (!isInShortRange(number)) {
throw new IllegalNumberRangeException(number.toString(), SHORT_MIN, SHORT_MAX);
}
return number.shortValue();
} | Checks if a given number is in the range of a short.
@param number
a number which should be in the range of a short (positive or negative)
@see java.lang.Short#MIN_VALUE
@see java.lang.Short#MAX_VALUE
@return number as a short (rounding might occur) |
@ArgumentsChecked
@Throws(IllegalNullArgumentException.class)
public static boolean isInRange(@Nonnull final Number number, @Nonnull final BigDecimal min, @Nonnull final BigDecimal max) {
Check.notNull(number, "number");
Check.notNull(min, "min");
Check.notNull(max, "max");
BigDecimal bigDecimal = null;
if (number instanceof Byte || number instanceof Short || number instanceof Integer || number instanceof Long) {
bigDecimal = new BigDecimal(number.longValue());
} else if (number instanceof Float || number instanceof Double) {
bigDecimal = new BigDecimal(number.doubleValue());
} else if (number instanceof BigInteger) {
bigDecimal = new BigDecimal((BigInteger) number);
} else if (number instanceof BigDecimal) {
bigDecimal = (BigDecimal) number;
} else {
throw new IllegalNumberArgumentException("Return value is no known subclass of 'java.lang.Number': "
+ number.getClass().getName());
}
return max.compareTo(bigDecimal) >= 0 && min.compareTo(bigDecimal) <= 0;
} | Test if a number is in an arbitrary range.
@param number
a number
@param min
lower boundary of the range
@param max
upper boundary of the range
@return true if the given number is within the range |
@ArgumentsChecked
@Throws(IllegalNullArgumentException.class)
public static boolean isInRange(@Nonnull final Number number, @Nonnull final BigInteger min, @Nonnull final BigInteger max) {
Check.notNull(number, "number");
Check.notNull(min, "min");
Check.notNull(max, "max");
BigInteger bigInteger = null;
if (number instanceof Byte || number instanceof Short || number instanceof Integer || number instanceof Long) {
bigInteger = BigInteger.valueOf(number.longValue());
} else if (number instanceof Float || number instanceof Double) {
bigInteger = new BigDecimal(number.doubleValue()).toBigInteger();
} else if (number instanceof BigInteger) {
bigInteger = (BigInteger) number;
} else if (number instanceof BigDecimal) {
bigInteger = ((BigDecimal) number).toBigInteger();
} else {
throw new IllegalNumberArgumentException("Return value is no known subclass of 'java.lang.Number': "
+ number.getClass().getName());
}
return max.compareTo(bigInteger) >= 0 && min.compareTo(bigInteger) <= 0;
} | Test if a number is in an arbitrary range.
@param number
a number
@param min
lower boundary of the range
@param max
upper boundary of the range
@return true if the given number is within the range |
public void setData(byte[] data, int offset)
{
if (offset < 0 || offset > data.length)
throw new KNXIllegalArgumentException("illegal offset " + offset);
final int size = data.length - offset;
if (size == 0)
throw new KNXIllegalArgumentException("data length " + size
+ " < KNX data type width " + Math.max(1, getTypeSize()));
this.data = new short[size];
for (int i = 0; i < size; ++i)
this.data[i] = ubyte(data[offset + i]);
} | /* (non-Javadoc)
@see tuwien.auto.calimero.dptxlator.DPTXlator#setData(byte[], int) |
public byte[] getData(byte[] dst, int offset)
{
final int end = Math.min(data.length, dst.length - offset);
for (int i = 0; i < end; ++i)
dst[offset + i] = (byte) data[i];
return dst;
}
/* (non-Javadoc)
* @see tuwien.auto.calimero.dptxlator.DPTXlator#getSubTypes()
*/
public final Map getSubTypes()
{
return types;
}
/**
* @return the subtypes of the 8 Bit unsigned translator type
* @see DPTXlator#getSubTypesStatic()
*/
protected static Map getSubTypesStatic()
{
return types;
}
/**
* Sets a new subtype to use for translating items.
* <p>
* The translator is reset into default state, all currently contained items are
* removed (default value is set).
*
* @param dptID new subtype ID to set
* @throws KNXFormatException on wrong formatted or not expected (available)
* <code>dptID</code>
*/
private void setSubType(String dptID) throws KNXFormatException
{
setTypeID(types, dptID);
data = new short[1];
}
private short fromDPT(short data)
{
short value = data;
if (dpt.equals(DPT_SCALING))
value = (short) Math.round(data * 100.0f / 255);
else if (dpt.equals(DPT_ANGLE))
value = (short) Math.round(data * 360.0f / 255);
return value;
}
private String makeString(int index)
{
return appendUnit(Short.toString(fromDPT(data[index])));
}
protected void toDPT(String value, short[] dst, int index) throws KNXFormatException
{
try {
dst[index] = toDPT(Short.decode(removeUnit(value)).shortValue());
}
catch (final NumberFormatException e) {
throw logThrow(LogLevel.WARN, "wrong value format " + value, null, value);
}
}
private short toDPT(int value) throws KNXFormatException
{
int convert = value;
if (dpt.equals(DPT_SCALING))
convert = Math.round(value * 255.0f / 100);
else if (dpt.equals(DPT_ANGLE))
convert = Math.round(value * 255.0f / 360);
if (convert < 0 || convert > 255)
throw logThrow(LogLevel.WARN, "translation error for " + value,
"input value out of range [" + dpt.getLowerValue() + ".."
+ dpt.getUpperValue() + "]", Integer.toString(value));
return (short) convert;
}
} | /* (non-Javadoc)
@see tuwien.auto.calimero.dptxlator.DPTXlator#getData(byte[], int) |
public static boolean algorithmEquals (@Nonnull final String sAlgURI, @Nonnull final String sAlgName)
{
if (sAlgName.equalsIgnoreCase ("DSA"))
{
return sAlgURI.equalsIgnoreCase (XMLSignature.ALGO_ID_SIGNATURE_DSA) ||
sAlgURI.equalsIgnoreCase (XMLSignature.ALGO_ID_SIGNATURE_DSA_SHA256);
}
if (sAlgName.equalsIgnoreCase ("RSA"))
{
return sAlgURI.equalsIgnoreCase (XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1) ||
sAlgURI.equalsIgnoreCase (XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1_MGF1) ||
sAlgURI.equalsIgnoreCase (XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA224) ||
sAlgURI.equalsIgnoreCase (XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA224_MGF1) ||
sAlgURI.equalsIgnoreCase (XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256) ||
sAlgURI.equalsIgnoreCase (XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256_MGF1) ||
sAlgURI.equalsIgnoreCase (XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384) ||
sAlgURI.equalsIgnoreCase (XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384_MGF1) ||
sAlgURI.equalsIgnoreCase (XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512) ||
sAlgURI.equalsIgnoreCase (XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512_MGF1) ||
sAlgURI.equalsIgnoreCase (XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_224_MGF1) ||
sAlgURI.equalsIgnoreCase (XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_256_MGF1) ||
sAlgURI.equalsIgnoreCase (XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_384_MGF1) ||
sAlgURI.equalsIgnoreCase (XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA3_512_MGF1);
}
if (sAlgName.equalsIgnoreCase ("EC"))
{
return sAlgURI.equalsIgnoreCase (XMLSignature.ALGO_ID_SIGNATURE_ECDSA_RIPEMD160) ||
sAlgURI.equalsIgnoreCase (XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA1) ||
sAlgURI.equalsIgnoreCase (XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA224) ||
sAlgURI.equalsIgnoreCase (XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA256) ||
sAlgURI.equalsIgnoreCase (XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA384) ||
sAlgURI.equalsIgnoreCase (XMLSignature.ALGO_ID_SIGNATURE_ECDSA_SHA512);
}
LOGGER.warn ("Algorithm mismatch between JCA/JCE public key algorithm name ('" +
sAlgName +
"') and signature algorithm URI ('" +
sAlgURI +
"')");
return false;
} | Checks if a JCA/JCE public key algorithm name is compatible with the
specified signature algorithm URI.
@param sAlgURI
The requested algorithm URI.
@param sAlgName
The provided algorithm name from a public key.
@return <code>true</code> if the name matches the URI. |
public double estimateExcludedVolumeFraction(){
//Calculate volume/area of the of the scene without obstacles
if(recalculateVolumeFraction){
CentralRandomNumberGenerator r = CentralRandomNumberGenerator.getInstance();
boolean firstRandomDraw = false;
if(randomNumbers==null){
randomNumbers = new double[nRandPoints*dimension];
firstRandomDraw = true;
}
int countCollision = 0;
for(int i = 0; i< nRandPoints; i++){
double[] pos = new double[dimension];
for(int j = 0; j < dimension; j++){
if(firstRandomDraw){
randomNumbers[i*dimension + j] = r.nextDouble();
}
pos[j] = randomNumbers[i*dimension + j]*size[j];
}
if(checkCollision(pos)){
countCollision++;
}
}
fraction = countCollision*1.0/nRandPoints;
recalculateVolumeFraction = false;
}
return fraction;
} | Estimate excluded volume fraction by monte carlo method
@return excluded volume fraction |
private static String determineMessage(@Nullable final String argumentName) {
return argumentName != null && !argumentName.isEmpty() ? format(argumentName) : DEFAULT_MESSAGE;
} | Determines the message to be used, depending on the passed argument name. If if the given argument name is
{@code null} or empty {@code DEFAULT_MESSAGE} will be returned, otherwise a formatted {@code MESSAGE_WITH_NAME}
with the passed name.
@param argumentName
the name of the passed argument
@return {@code DEFAULT_MESSAGE} if the given argument name is {@code null} or empty, otherwise a formatted
{@code MESSAGE_WITH_NAME} |
@Override
public void handleApplicationCommandRequest(SerialMessage serialMessage,
int offset, int endpointId) {
logger.trace("Handle Message Multi-instance/Multi-channel Request");
logger.debug(String.format("Received Multi-instance/Multi-channel Request for Node ID = %d", this.getNode().getNodeId()));
int command = serialMessage.getMessagePayloadByte(offset);
switch (command) {
case MULTI_INSTANCE_GET:
case MULTI_CHANNEL_ENDPOINT_GET:
case MULTI_CHANNEL_CAPABILITY_GET:
case MULTI_CHANNEL_ENDPOINT_FIND:
case MULTI_CHANNEL_ENDPOINT_FIND_REPORT:
logger.warn(String.format("Command 0x%02X not implemented.", command));
return;
case MULTI_INSTANCE_REPORT:
handleMultiInstanceReportResponse(serialMessage, offset + 1);
break;
case MULTI_INSTANCE_ENCAP:
handleMultiInstanceEncapResponse(serialMessage, offset + 1);
break;
case MULTI_CHANNEL_ENDPOINT_REPORT:
handleMultiChannelEndpointReportResponse(serialMessage, offset + 1);
break;
case MULTI_CHANNEL_CAPABILITY_REPORT:
handleMultiChannelCapabilityReportResponse(serialMessage, offset + 1);
break;
case MULTI_CHANNEL_ENCAP:
handleMultiChannelEncapResponse(serialMessage, offset + 1);
break;
default:
logger.warn(String.format("Unsupported Command 0x%02X for command class %s (0x%02X).",
command,
this.getCommandClass().getLabel(),
this.getCommandClass().getKey()));
}
} | {@inheritDoc} |
private void handleMultiInstanceReportResponse(SerialMessage serialMessage,
int offset) {
logger.trace("Process Multi-instance Report");
int commandClassCode = serialMessage.getMessagePayloadByte(offset);
int instances = serialMessage.getMessagePayloadByte(offset + 1);
if (instances == 0) {
setInstances(1);
} else
{
CommandClass commandClass = CommandClass.getCommandClass(commandClassCode);
if (commandClass == null) {
logger.error(String.format("Unsupported command class 0x%02x", commandClassCode));
return;
}
logger.debug(String.format("Node %d Requested Command Class = %s (0x%02x)", this.getNode().getNodeId(), commandClass.getLabel() , commandClassCode));
ZWaveCommandClass zwaveCommandClass = this.getNode().getCommandClass(commandClass);
if (zwaveCommandClass == null) {
logger.error(String.format("Unsupported command class %s (0x%02x)", commandClass.getLabel(), commandClassCode));
return;
}
zwaveCommandClass.setInstances(instances);
logger.debug(String.format("Node %d Instances = %d, number of instances set.", this.getNode().getNodeId(), instances));
}
for (ZWaveCommandClass zwaveCommandClass : this.getNode().getCommandClasses())
if (zwaveCommandClass.getInstances() == 0) // still waiting for an instance report of another command class.
return;
// advance node stage.
this.getNode().advanceNodeStage();
} | Handles Multi Instance Report message. Handles Report on
the number of instances for the command class.
@param serialMessage the serial message to process.
@param offset the offset at which to start procesing. |
private void handleMultiInstanceEncapResponse(
SerialMessage serialMessage, int offset) {
logger.trace("Process Multi-instance Encapsulation");
int instance = serialMessage.getMessagePayloadByte(offset);
int commandClassCode = serialMessage.getMessagePayloadByte(offset + 1);
CommandClass commandClass = CommandClass.getCommandClass(commandClassCode);
if (commandClass == null) {
logger.error(String.format("Unsupported command class 0x%02x", commandClassCode));
return;
}
logger.debug(String.format("Node %d Requested Command Class = %s (0x%02x)", this.getNode().getNodeId(), commandClass.getLabel() , commandClassCode));
ZWaveCommandClass zwaveCommandClass = this.getNode().getCommandClass(commandClass);
if (zwaveCommandClass == null) {
logger.error(String.format("Unsupported command class %s (0x%02x)", commandClass.getLabel(), commandClassCode));
return;
}
logger.debug(String.format("Node %d, Instance = %d, calling handleApplicationCommandRequest.", this.getNode().getNodeId(), instance));
zwaveCommandClass.handleApplicationCommandRequest(serialMessage, offset+ 3, instance);
} | Handles Multi Instance Encapsulation message. Decapsulates
an Application Command message and handles it using the right
instance.
@param serialMessage the serial message to process.
@param offset the offset at which to start procesing. |
private void handleMultiChannelEndpointReportResponse(
SerialMessage serialMessage, int offset) {
logger.debug("Process Multi-channel endpoint Report");
boolean changingNumberOfEndpoints = (serialMessage.getMessagePayloadByte(offset) & 0x80) != 0;
endpointsAreTheSameDeviceClass = (serialMessage.getMessagePayloadByte(offset) & 0x40) != 0;
int endpoints = serialMessage.getMessagePayloadByte(offset + 1) & 0x7F;
logger.debug("Changing number of endpoints = {}", changingNumberOfEndpoints ? "true" : false);
logger.debug("Endpoints are the same device class = {}", endpointsAreTheSameDeviceClass ? "true" : false);
logger.debug("Number of endpoints = {}", endpoints);
// TODO: handle dynamically added endpoints. Have never seen such a device.
if (changingNumberOfEndpoints)
logger.warn("Changing number of endpoints, expect some weird behavior during multi channel handling.");
for (int i=1; i <= endpoints; i++) {
ZWaveEndpoint endpoint = new ZWaveEndpoint(i);
this.endpoints.put(i, endpoint);
if (!endpointsAreTheSameDeviceClass || i == 1)
this.getController().sendData(this.getMultiChannelCapabilityGetMessage(endpoint));
}
} | Handles Multi Channel Endpoint Report message. Handles Report on
the number of endpoints and whether they are dynamic and/or have the
same command classes.
@param serialMessage the serial message to process.
@param offset the offset at which to start processing. |
private void handleMultiChannelCapabilityReportResponse(SerialMessage serialMessage, int offset) {
logger.debug("Process Multi-channel capability Report");
int receivedEndpointId = serialMessage.getMessagePayloadByte(offset) & 0x7F;
boolean dynamic = ((serialMessage.getMessagePayloadByte(offset) & 0x80) != 0);
int genericDeviceClass = serialMessage.getMessagePayloadByte(offset + 1);
int specificDeviceClass = serialMessage.getMessagePayloadByte(offset + 2);
logger.debug("Endpoints are the same device class = {}", endpointsAreTheSameDeviceClass ? "true" : false);
// Loop either all endpoints, or just set command classes on one, depending on whether
// all endpoints have the same device class.
int startId = this.endpointsAreTheSameDeviceClass ? 1 : receivedEndpointId;
int endId = this.endpointsAreTheSameDeviceClass ? this.endpoints.size() : receivedEndpointId;
boolean supportsBasicCommandClass = this.getNode().supportsCommandClass(CommandClass.BASIC);
for (int endpointId = startId; endpointId <= endId; endpointId++) {
ZWaveEndpoint endpoint = this.endpoints.get(endpointId);
if (endpoint == null){
logger.error("Endpoint {} not found on node {}. Cannot set command classes.", endpoint, this.getNode().getNodeId());
continue;
}
ZWaveDeviceClass.Basic basic = this.getNode().getDeviceClass().getBasicDeviceClass();
ZWaveDeviceClass.Generic generic = ZWaveDeviceClass.Generic.getGeneric(genericDeviceClass);
if (generic == null) {
logger.error(String.format("Endpoint %d has invalid device class. generic = 0x%02x, specific = 0x%02x.",
endpoint, genericDeviceClass, specificDeviceClass));
continue;
}
ZWaveDeviceClass.Specific specific = ZWaveDeviceClass.Specific.getSpecific(generic, specificDeviceClass);
if (specific == null) {
logger.error(String.format("Endpoint %d has invalid device class. generic = 0x%02x, specific = 0x%02x.",
endpoint, genericDeviceClass, specificDeviceClass));
continue;
}
logger.debug("Endpoint Id = {}", endpointId);
logger.debug("Endpoints is dynamic = {}", dynamic ? "true" : false);
logger.debug(String.format("Basic = %s 0x%02x", basic.getLabel(), basic.getKey()));
logger.debug(String.format("Generic = %s 0x%02x", generic.getLabel(), generic.getKey()));
logger.debug(String.format("Specific = %s 0x%02x", specific.getLabel(), specific.getKey()));
ZWaveDeviceClass deviceClass = endpoint.getDeviceClass();
deviceClass.setBasicDeviceClass(basic);
deviceClass.setGenericDeviceClass(generic);
deviceClass.setSpecificDeviceClass(specific);
// add basic command class, if it's also supported by the parent node.
if (supportsBasicCommandClass) {
ZWaveCommandClass commandClass = new ZWaveBasicCommandClass(this.getNode(), this.getController(), endpoint);
endpoint.addCommandClass(commandClass);
}
for (int i = 0; i < serialMessage.getMessagePayload().length - offset - 3; i++) {
int data = serialMessage.getMessagePayloadByte(offset + 3 + i);
if(data == 0xef ) {
// TODO: Implement control command classes
break;
}
logger.debug(String.format("Adding command class 0x%02X to the list of supported command classes.", data));
ZWaveCommandClass commandClass = ZWaveCommandClass.getInstance(data, this.getNode(), this.getController(), endpoint);
if (commandClass == null) {
continue;
}
endpoint.addCommandClass(commandClass);
ZWaveCommandClass parentClass = this.getNode().getCommandClass(commandClass.getCommandClass());
// copy version info to endpoint classes.
if (parentClass != null) {
commandClass.setVersion(parentClass.getVersion());
}
}
}
if (this.endpointsAreTheSameDeviceClass)
// advance node stage.
this.getNode().advanceNodeStage();
else {
for (ZWaveEndpoint ep : this.endpoints.values())
{
if (ep.getDeviceClass().getBasicDeviceClass() == ZWaveDeviceClass.Basic.NOT_KNOWN) // only advance node stage when all endpoints are known.
return;
}
// advance node stage.
this.getNode().advanceNodeStage();
}
} | Handles Multi Channel Capability Report message. Handles Report on
an endpoint and adds command classes to the endpoint.
@param serialMessage the serial message to process.
@param offset the offset at which to start processing. |
private void handleMultiChannelEncapResponse(
SerialMessage serialMessage, int offset) {
logger.trace("Process Multi-channel Encapsulation");
CommandClass commandClass;
ZWaveCommandClass zwaveCommandClass;
int endpointId = serialMessage.getMessagePayloadByte(offset);
int commandClassCode = serialMessage.getMessagePayloadByte(offset + 2);
commandClass = CommandClass.getCommandClass(commandClassCode);
if (commandClass == null) {
logger.error(String.format("Unsupported command class 0x%02x", commandClassCode));
return;
}
logger.debug(String.format("Node %d Requested Command Class = %s (0x%02x)", this.getNode().getNodeId(), commandClass.getLabel() , commandClassCode));
ZWaveEndpoint endpoint = this.endpoints.get(endpointId);
if (endpoint == null){
logger.error("Endpoint {} not found on node {}. Cannot set command classes.", endpoint, this.getNode().getNodeId());
return;
}
zwaveCommandClass = endpoint.getCommandClass(commandClass);
if (zwaveCommandClass == null) {
logger.warn(String.format("CommandClass %s (0x%02x) not implemented by endpoint %d, fallback to main node.", commandClass.getLabel(), commandClassCode, endpointId));
zwaveCommandClass = this.getNode().getCommandClass(commandClass);
}
if (zwaveCommandClass == null) {
logger.error(String.format("CommandClass %s (0x%02x) not implemented by node %d.", commandClass.getLabel(), commandClassCode, this.getNode().getNodeId()));
return;
}
logger.debug(String.format("Node %d, Endpoint = %d, calling handleApplicationCommandRequest.", this.getNode().getNodeId(), endpointId));
zwaveCommandClass.handleApplicationCommandRequest(serialMessage, offset + 3, endpointId);
} | Handles Multi Channel Encapsulation message. Decapsulates
an Application Command message and handles it using the right
endpoint.
@param serialMessage the serial message to process.
@param offset the offset at which to start procesing. |
public SerialMessage getMultiInstanceGetMessage(CommandClass commandClass) {
logger.debug("Creating new message for application command MULTI_INSTANCE_GET for node {} and command class {}", this.getNode().getNodeId(), commandClass.getLabel());
SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get);
byte[] newPayload = { (byte) this.getNode().getNodeId(),
3,
(byte) getCommandClass().getKey(),
(byte) MULTI_INSTANCE_GET,
(byte) commandClass.getKey()
};
result.setMessagePayload(newPayload);
return result;
} | Gets a SerialMessage with the MULTI INSTANCE GET command.
Returns the number of instances for this command class.
@param the command class to return the number of instances for.
@return the serial message. |
public SerialMessage getMultiInstanceEncapMessage(SerialMessage serialMessage, int instance) {
logger.debug("Creating new message for application command MULTI_INSTANCE_ENCAP for node {} and instance {}", this.getNode().getNodeId(), instance);
byte[] payload = serialMessage.getMessagePayload();
byte[] newPayload = new byte[payload.length + 3];
System.arraycopy(payload, 0, newPayload, 0, 2);
System.arraycopy(payload, 0, newPayload, 3, payload.length);
newPayload[1] += 3;
newPayload[2] = (byte) this.getCommandClass().getKey();
newPayload[3] = MULTI_INSTANCE_ENCAP;
newPayload[4] = (byte)(instance);
serialMessage.setMessagePayload(newPayload);
return serialMessage;
} | Gets a SerialMessage with the MULTI INSTANCE ENCAP command.
Encapsulates a message for a specific instance.
@param serialMessage the serial message to encapsulate
@param instance the number of the instance to encapsulate the message for.
@return the encapsulated serial message. |
public SerialMessage getMultiChannelCapabilityGetMessage(ZWaveEndpoint endpoint) {
logger.debug("Creating new message for application command MULTI_CHANNEL_CAPABILITY_GET for node {} and endpoint {}", this.getNode().getNodeId(), endpoint.getEndpointId());
SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get);
byte[] newPayload = { (byte) this.getNode().getNodeId(),
3,
(byte) getCommandClass().getKey(),
(byte) MULTI_CHANNEL_CAPABILITY_GET,
(byte) endpoint.getEndpointId() };
result.setMessagePayload(newPayload);
return result;
} | Gets a SerialMessage with the MULTI CHANNEL CAPABILITY GET command.
Gets the capabilities for a specific endpoint.
@param the number of the endpoint to get the
@return the serial message. |
public SerialMessage getMultiChannelEncapMessage(SerialMessage serialMessage, ZWaveEndpoint endpoint) {
logger.debug("Creating new message for application command MULTI_CHANNEL_ENCAP for node {} and endpoint {}", this.getNode().getNodeId(), endpoint.getEndpointId());
byte[] payload = serialMessage.getMessagePayload();
byte[] newPayload = new byte[payload.length + 4];
System.arraycopy(payload, 0, newPayload, 0, 2);
System.arraycopy(payload, 0, newPayload, 4, payload.length);
newPayload[1] += 4;
newPayload[2] = (byte) this.getCommandClass().getKey();
newPayload[3] = MULTI_CHANNEL_ENCAP;
newPayload[4] = 0x01;
newPayload[5] = (byte) endpoint.getEndpointId();
serialMessage.setMessagePayload(newPayload);
return serialMessage;
} | Gets a SerialMessage with the MULTI INSTANCE ENCAP command.
Encapsulates a message for a specific instance.
@param serialMessage the serial message to encapsulate
@param endpoint the endpoint to encapsulate the message for.
@return the encapsulated serial message. |
public void initEndpoints() {
switch (this.getVersion()) {
case 1:
// get number of instances for all command classes on this node.
for (ZWaveCommandClass commandClass : this.getNode().getCommandClasses()) {
if (commandClass.getCommandClass() == CommandClass.NO_OPERATION)
continue;
this.getController().sendData(this.getMultiInstanceGetMessage(commandClass.getCommandClass()));
}
break;
case 2:
this.getController().sendData(this.getMultiChannelEndpointGetMessage());
break;
default:
logger.warn(String.format("Unknown version %d for command class %s (0x%02x)",
this.getVersion(), this.getCommandClass().getLabel(), this.getCommandClass().getKey()));
}
} | Initializes the Multi instance / endpoint command class by setting the number of instances
or getting the endpoints. |
public static <CFG extends AbstractEncryptionConfiguration<CFG>> CFG config(String name, Class<CFG> cryptoConfigurationClass) {
@SuppressWarnings("unchecked")
ConfigurationProvider<? extends AbstractEncryptionConfiguration<CFG>> provider =
(ConfigurationProvider<? extends AbstractEncryptionConfiguration<CFG>>)
configurationProviderMap.get(cryptoConfigurationClass);
if (provider == null) {
throw new IllegalArgumentException("Configuration not registered!");
}
return provider.newConfiguration()
.setName(name)
.addOnEncryptionServiceCreatedListener(onEncryptionServiceCreatedListener);
} | Begins a new fluent configuration stanza.
@param <CFG> the Configuration type.
@param name an identifier which will be used to fetch the AuthenticationModule after
configuration is finished.
@param cryptoConfigurationClass the class of the configuration type.
@return a AuthenticationConfiguration which can be used to build a AuthenticationModule object. |
public synchronized void createImportationDeclaration(String deviceId, String deviceType, String deviceSubType) {
Map<String, Object> metadata = new HashMap<String, Object>();
metadata.put(Constants.DEVICE_ID, deviceId);
metadata.put(Constants.DEVICE_TYPE, deviceType);
metadata.put(Constants.DEVICE_TYPE_SUB, deviceSubType);
metadata.put("scope", "generic");
ImportDeclaration declaration = ImportDeclarationBuilder.fromMetadata(metadata).build();
importDeclarations.put(deviceId, declaration);
registerImportDeclaration(declaration);
} | Create an import declaration and delegates its registration for an upper class. |
public static boolean hasTranslator(int dataType)
{
final DPTID dpt = (DPTID) pt.get(new Integer(dataType));
if (dpt != null)
try {
final MainType t = TranslatorTypes.getMainType(dpt.getMainNumber());
if (t != null)
return t.getSubTypes().get(dpt.getDPT()) != null;
}
catch (final NumberFormatException e) {}
catch (final KNXException e) {}
return false;
} | Does a lookup if the given property data type has an associated translator
available.
<p>
The translator looked for is specified in the property map. An available translator
is implemented and can be used for translation.
@param dataType property data type to lookup
@return <code>true</code> iff translator and its subtype was found,
<code>false</code> otherwise |
public static DPTXlator createTranslator(int dataType) throws KNXException
{
final DPTID dpt = (DPTID) pt.get(new Integer(dataType));
if (dpt == null)
throw new KNXException("PDT not found");
final DPTXlator t =
TranslatorTypes.createTranslator(dpt.getMainNumber(), dpt.getDPT());
t.setAppendUnit(false);
return t;
} | Creates a new DPT translator for the specified property type.
<p>
The translator is initialized with a subtype as specified by the property map.
Also, appending of units is disabled in the returned translator.
@param dataType property data type to get the associated translator for
@return the created DPT translator
@throws KNXException on PDT not found or translator could not be created
@see TranslatorTypes#createTranslator(int, String) |
public static DPTXlator createTranslator(int dataType, byte[] data)
throws KNXException
{
final DPTXlator t = createTranslator(dataType);
t.setData(data);
return t;
} | Utility method, like {@link #createTranslator(int)}, with the additional
capability to set the data to be used by the DPT translator.
<p>
@param dataType property data type to get the associated translator for
@param data array with KNX DPT formatted data, the number of contained items is
determined by the used DPT
@return the created DPT translator with the set data
@throws KNXException on PDT not found or translator could not be created
@see #createTranslator(int) |
public static void main(String[] args)
{
try {
final NetworkMonitor m = new NetworkMonitor(args, null);
// supply a log writer for System.out (console)
m.w = new ConsoleWriter(m.options.containsKey("verbose"));
m.run(m.new MonitorListener());
}
catch (final Throwable t) {
if (t.getMessage() != null)
System.out.println(t.getMessage());
else
System.out.println(t.getClass().getName());
}
} | Entry point for running the NetworkMonitor.
<p>
An IP host or port identifier has to be supplied, specifying the endpoint for the
KNX network access.<br>
To show the usage message of this tool on the console, supply the command line
option -help (or -h).<br>
Command line options are treated case sensitive. Available options for network
monitoring:
<ul>
<li><code>-help -h</code> show help message</li>
<li><code>-version</code> show tool/library version and exit</li>
<li><code>-verbose -v</code> enable verbose status output</li>
<li><code>-localhost</code> <i>id</i> local IP/host name</li>
<li><code>-localport</code> <i>number</i> local UDP port (default system
assigned)</li>
<li><code>-port -p</code> <i>number</i> UDP port on host (default 3671)</li>
<li><code>-nat -n</code> enable Network Address Translation</li>
<li><code>-serial -s</code> use FT1.2 serial communication</li>
<li><code>-medium -m</code> <i>id</i> KNX medium [tp0|tp1|p110|p132|rf]
(defaults to tp1)</li>
</ul>
@param args command line options for network monitoring |
public void run(LinkListener l) throws KNXException
{
createMonitor(l);
final Thread sh = registerShutdownHandler();
// TODO actually, this waiting block is just necessary if we're in console mode
// to keep the current thread alive and for clean up
// when invoked externally by a user, an immediate return could save one
// additional thread (with the requirement to call quit for cleanup)
try {
// just wait for the network monitor to quit
synchronized (this) {
while (m.isOpen())
try {
wait();
}
catch (final InterruptedException e) {}
}
}
finally {
Runtime.getRuntime().removeShutdownHook(sh);
}
} | Runs the network monitor.
<p>
This method returns when the network monitor is closed.
@param l a link listener for monitor events
@throws KNXException on problems on creating monitor or during monitoring |
private void createMonitor(LinkListener l) throws KNXException
{
final KNXMediumSettings medium = (KNXMediumSettings) options.get("medium");
if (options.containsKey("serial")) {
final String p = (String) options.get("serial");
try {
m = new KNXNetworkMonitorFT12(Integer.parseInt(p), medium);
}
catch (final NumberFormatException e) {
m = new KNXNetworkMonitorFT12(p, medium);
}
}
else {
// create local and remote socket address for monitor link
final InetSocketAddress local = createLocalSocket((InetAddress) options
.get("localhost"), (Integer) options.get("localport"));
final InetSocketAddress host = new InetSocketAddress((InetAddress) options
.get("host"), ((Integer) options.get("port")).intValue());
// create the monitor link, based on the KNXnet/IP protocol
// specify whether network address translation shall be used,
// and tell the physical medium of the KNX network
m = new KNXNetworkMonitorIP(local, host, options.containsKey("nat"), medium);
}
// add the log writer for monitor log events
LogManager.getManager().addWriter(m.getName(), w);
// on console we want to have all possible information, so enable
// decoding of a received raw frame by the monitor link
m.setDecodeRawFrames(true);
// listen to monitor link events
m.addMonitorListener(l);
// we always need a link closed notification (even with user supplied listener)
m.addMonitorListener(new LinkListener() {
public void indication(FrameEvent e)
{}
public void linkClosed(CloseEvent e)
{
System.out.println("network monitor exit, " + e.getReason());
synchronized (NetworkMonitor.this) {
NetworkMonitor.this.notify();
}
}
});
} | Creates a new network monitor using the supplied options.
<p>
@throws KNXException on problems on monitor creation |
private static boolean parseOptions(String[] args, Map options)
{
if (args.length == 0) {
System.out.println("A tool for monitoring a KNX network");
showVersion();
System.out.println("type -help for help message");
return false;
}
// add defaults
options.put("port", new Integer(KNXnetIPConnection.IP_PORT));
options.put("medium", TPSettings.TP1);
int i = 0;
for (; i < args.length; i++) {
final String arg = args[i];
if (isOption(arg, "-help", "-h")) {
showUsage();
return false;
}
if (isOption(arg, "-version", null)) {
showVersion();
return false;
}
if (isOption(arg, "-verbose", "-v"))
options.put("verbose", null);
else if (isOption(arg, "-localhost", null))
parseHost(args[++i], true, options);
else if (isOption(arg, "-localport", null))
options.put("localport", Integer.decode(args[++i]));
else if (isOption(arg, "-port", "-p"))
options.put("port", Integer.decode(args[++i]));
else if (isOption(arg, "-nat", "-n"))
options.put("nat", null);
else if (isOption(arg, "-serial", "-s"))
options.put("serial", null);
else if (isOption(arg, "-medium", "-m"))
options.put("medium", getMedium(args[++i]));
else if (options.containsKey("serial"))
// add port number/identifier to serial option
options.put("serial", arg);
else if (!options.containsKey("host"))
parseHost(arg, false, options);
else
throw new IllegalArgumentException("unknown option " + arg);
}
return true;
} | Reads all options in the specified array, and puts relevant options into the
supplied options map.
<p>
On options not relevant for doing network monitoring (like <code>help</code>),
this method will take appropriate action (like showing usage information). On
occurrence of such an option, other options will be ignored. On unknown options, an
IllegalArgumentException is thrown.
@param args array with command line options
@param options map to store options, optionally with its associated value
@return <code>true</code> if the supplied provide enough information to continue
with monitoring, <code>false</code> otherwise or if the options were
handled by this method |
public void init(Configuration c)
{
final DatapointModel m = c.getDatapointModel();
if (m != null)
createReferences(m);
} | /* (non-Javadoc)
@see tuwien.auto.calimero.buffer.Configuration.NetworkFilter#init
(tuwien.auto.calimero.buffer.Configuration) |
public static Dimension getDimension(File videoFile) throws IOException {
try (FileInputStream fis = new FileInputStream(videoFile)) {
return getDimension(fis, new AtomicReference<ByteBuffer>());
}
} | Returns the dimensions for the video
@param videoFile Video file
@return the dimensions
@throws IOException |
private static Dimension getDimension(InputStream fis, AtomicReference<ByteBuffer> lastTkhdHolder)
throws IOException {
while (fis.available() > 0) {
byte[] header = new byte[8];
fis.read(header);
long size = readUint32(header, 0);
String type = new String(header, 4, 4, "ISO-8859-1");
if (containers.contains(type)) {
Dimension dimension = getDimension(fis, lastTkhdHolder);
if (dimension != null) {
return dimension;
}
} else if (type.equals("tkhd")) {
byte[] lastTkhd = new byte[(int) (size - 8)];
lastTkhdHolder.set(ByteBuffer.wrap(lastTkhd));
fis.read(lastTkhd);
} else if (type.equals("hdlr")) {
byte[] hdlr = new byte[(int) (size - 8)];
fis.read(hdlr);
if (hdlr[8] == 0x76 && hdlr[9] == 0x69 && hdlr[10] == 0x64 && hdlr[11] == 0x65) {
byte[] lastTkhd = lastTkhdHolder.get().array();
return new Dimension((int) readFixedPoint1616(lastTkhd, lastTkhd.length - 8),
(int) readFixedPoint1616(lastTkhd, lastTkhd.length - 4));
}
} else {
fis.skip(size - 8);
}
}
return null;
} | Internal loop to fiond w/h headers
@param fis Stream
@param lastTkhdHolder Holder
@return Dimensions
@throws IOException |
public void writeAddress(IndividualAddress newAddress) throws KNXTimeoutException,
KNXLinkClosedException
{
tl.broadcast(false, Priority.SYSTEM, DataUnitBuilder.createAPDU(IND_ADDR_WRITE,
newAddress.toByteArray()));
} | /* (non-Javadoc)
@see tuwien.auto.calimero.mgmt.ManagementClient#writeAddress
(tuwien.auto.calimero.IndividualAddress) |
public synchronized IndividualAddress[] readAddress(boolean oneAddressOnly)
throws KNXTimeoutException, KNXRemoteException, KNXLinkClosedException
{
final List l = new ArrayList();
try {
svcResponse = IND_ADDR_RESPONSE;
tl.broadcast(false, Priority.SYSTEM, DataUnitBuilder.createCompactAPDU(
IND_ADDR_READ, null));
long wait = responseTimeout * 1000;
final long end = System.currentTimeMillis() + wait;
while (wait > 0) {
l.add(new IndividualAddress(waitForResponse(0, 0, wait)));
if (oneAddressOnly)
break;
wait = end - System.currentTimeMillis();
}
}
catch (final KNXTimeoutException e) {
if (l.isEmpty())
throw e;
}
finally {
svcResponse = 0;
}
return (IndividualAddress[]) l.toArray(new IndividualAddress[l.size()]);
} | /* (non-Javadoc)
@see tuwien.auto.calimero.mgmt.ManagementClient#readAddress(boolean) |
public void writeAddress(byte[] serialNo, IndividualAddress newAddress)
throws KNXTimeoutException, KNXLinkClosedException
{
if (serialNo.length != 6)
throw new KNXIllegalArgumentException("length of serial number not 6 bytes");
final byte[] asdu = new byte[12];
for (int i = 0; i < 6; ++i)
asdu[i] = serialNo[i];
asdu[6] = (byte) (newAddress.getRawAddress() >>> 8);
asdu[7] = (byte) newAddress.getRawAddress();
tl.broadcast(false, Priority.SYSTEM, DataUnitBuilder.createAPDU(
IND_ADDR_SN_WRITE, asdu));
} | /* (non-Javadoc)
@see tuwien.auto.calimero.mgmt.ManagementClient#writeAddress
(byte[], tuwien.auto.calimero.IndividualAddress) |
public synchronized IndividualAddress readAddress(byte[] serialNo)
throws KNXTimeoutException, KNXRemoteException, KNXLinkClosedException
{
if (serialNo.length != 6)
throw new KNXIllegalArgumentException("length of serial number not 6 bytes");
try {
svcResponse = IND_ADDR_SN_RESPONSE;
tl.broadcast(false, Priority.SYSTEM, DataUnitBuilder.createAPDU(
IND_ADDR_SN_READ, serialNo));
return new IndividualAddress(waitForResponse(10, 10));
}
finally {
svcResponse = 0;
}
} | /* (non-Javadoc)
@see tuwien.auto.calimero.mgmt.ManagementClient#readAddress(byte[]) |
public void writeDomainAddress(byte[] domain) throws KNXTimeoutException,
KNXLinkClosedException
{
if (domain.length != 2 && domain.length != 6)
throw new KNXIllegalArgumentException("invalid length of domain address");
tl.broadcast(true, priority, DataUnitBuilder.createAPDU(DOA_WRITE, domain));
} | /* (non-Javadoc)
@see tuwien.auto.calimero.mgmt.ManagementClient#writeDomainAddress(byte[]) |
public synchronized List readDomainAddress(boolean oneDomainOnly)
throws KNXLinkClosedException, KNXInvalidResponseException, KNXTimeoutException
{
// we allow 6 bytes ASDU for RF domains
return makeDOAs(readBroadcast(priority, DataUnitBuilder.createCompactAPDU(
DOA_READ, null), DOA_RESPONSE, 6, 6, oneDomainOnly));
} | /* (non-Javadoc)
@see tuwien.auto.calimero.mgmt.ManagementClient#readDomainAddress(boolean) |
public void restart(Destination dst) throws KNXTimeoutException,
KNXLinkClosedException
{
final byte[] send = DataUnitBuilder.createCompactAPDU(RESTART, null);
if (dst.isConnectionOriented())
tl.connect(dst);
else
logger.error("doing restart in connectionless mode, " + dst.toString());
tl.sendData(dst.getAddress(), priority, send);
// force a reconnect at later time
tl.disconnect(dst);
} | /* (non-Javadoc)
@see tuwien.auto.calimero.mgmt.ManagementClient#restart
(tuwien.auto.calimero.mgmt.Destination) |
public byte[] readProperty(Destination dst, int objIndex, int propID, int start,
int elements) throws KNXTimeoutException, KNXRemoteException,
KNXDisconnectException, KNXLinkClosedException
{
if (objIndex < 0 || objIndex > 255 || propID < 0 || propID > 255 || start < 0
|| start > 0xFFF || elements < 0 || elements > 15)
throw new KNXIllegalArgumentException("argument value out of range");
final byte[] asdu = new byte[4];
asdu[0] = (byte) objIndex;
asdu[1] = (byte) propID;
asdu[2] = (byte) ((elements << 4) | ((start >>> 8) & 0xF));
asdu[3] = (byte) start;
final byte[] apdu = sendWait2(dst, priority, DataUnitBuilder.createAPDU(
PROPERTY_READ, asdu), PROPERTY_RESPONSE, 4, 14);
// check if number of elements is 0, indicates access problem
final int number = (apdu[4] & 0xFF) >>> 4;
if (number == 0)
throw new KNXRemoteException("property access failed/forbidden");
if (number != elements)
throw new KNXInvalidResponseException("number of elements differ");
final byte[] prop = new byte[apdu.length - 6];
for (int i = 0; i < prop.length; ++i)
prop[i] = apdu[i + 6];
return prop;
} | /* (non-Javadoc)
@see tuwien.auto.calimero.mgmt.ManagementClient#readProperty
(tuwien.auto.calimero.mgmt.Destination, int, int, int, int) |
public void writeProperty(Destination dst, int objIndex, int propID, int start,
int elements, byte[] data) throws KNXTimeoutException, KNXRemoteException,
KNXDisconnectException, KNXLinkClosedException
{
if (objIndex < 0 || objIndex > 255 || propID < 0 || propID > 255 || start < 0
|| start > 0xFFF || data.length == 0 || elements < 0 || elements > 15)
throw new KNXIllegalArgumentException("argument value out of range");
final byte[] asdu = new byte[4 + data.length];
asdu[0] = (byte) objIndex;
asdu[1] = (byte) propID;
asdu[2] = (byte) ((elements << 4) | ((start >>> 8) & 0xF));
asdu[3] = (byte) start;
for (int i = 0; i < data.length; ++i)
asdu[4 + i] = data[i];
final byte[] send = DataUnitBuilder.createAPDU(PROPERTY_WRITE, asdu);
final byte[] apdu = sendWait2(dst, priority, send, PROPERTY_RESPONSE, 4, 14);
// if number of elements is 0, remote app had problems
final int elems = (apdu[4] & 0xFF) >> 4;
if (elems == 0)
throw new KNXRemoteException("property write failed/forbidden");
if (elems != elements)
throw new KNXInvalidResponseException("number of elements differ");
if (data.length != apdu.length - 6)
throw new KNXInvalidResponseException("data lengths differ, bytes: "
+ data.length + " written, " + (apdu.length - 6) + " response");
// explicitly read back written properties
for (int i = 4; i < asdu.length; ++i)
if (apdu[2 + i] != asdu[i])
throw new KNXRemoteException("read back failed (erroneous property data)");
} | /* (non-Javadoc)
@see tuwien.auto.calimero.mgmt.ManagementClient#writeProperty
(tuwien.auto.calimero.mgmt.Destination, int, int, int, int, byte[]) |
public byte[] readPropertyDesc(Destination dst, int objIndex, int propID,
int propIndex) throws KNXTimeoutException, KNXRemoteException,
KNXDisconnectException, KNXLinkClosedException
{
if (objIndex < 0 || objIndex > 255 || propID < 0 || propID > 255 || propIndex < 0
|| propIndex > 255)
throw new KNXIllegalArgumentException("argument value out of range");
final byte[] send = DataUnitBuilder.createAPDU(PROPERTY_DESC_READ, new byte[] {
(byte) objIndex, (byte) propID, (byte) (propID == 0 ? propIndex : 0) });
final byte[] apdu = sendWait2(dst, priority, send, PROPERTY_DESC_RESPONSE, 7, 7);
// max_nr_elem field is a 4bit exponent + 12bit unsigned
// on problem this field is 0
if (apdu[6] == 0 && apdu[7] == 0)
throw new KNXRemoteException(
"got no property description (object non-existant?)");
return new byte[] { apdu[2], apdu[3], apdu[4], apdu[5], apdu[6], apdu[7], apdu[8] };
} | /* (non-Javadoc)
@see tuwien.auto.calimero.mgmt.ManagementClient#readPropertyDesc
(tuwien.auto.calimero.mgmt.Destination, int, int, int) |
public int readADC(Destination dst, int channelNr, int repeat)
throws KNXTimeoutException, KNXDisconnectException, KNXRemoteException,
KNXLinkClosedException
{
if (channelNr < 0 || channelNr > 63 || repeat < 0 || repeat > 255)
throw new KNXIllegalArgumentException("ADC arguments out of range");
if (dst.isConnectionOriented())
tl.connect(dst);
else
logger.error("doing read ADC in connectionless mode, " + dst.toString());
final byte[] apdu =
sendWait(dst, priority, DataUnitBuilder.createCompactAPDU(ADC_READ,
new byte[] { (byte) channelNr, (byte) repeat }), ADC_RESPONSE, 3, 3);
if (apdu[2] == 0)
throw new KNXRemoteException("error reading value of A/D converter");
return ((apdu[3] & 0xff) << 8) | apdu[4] & 0xff;
} | /* (non-Javadoc)
@see tuwien.auto.calimero.mgmt.ManagementClient#readADC
(tuwien.auto.calimero.mgmt.Destination, int, int) |
public byte[] readMemory(Destination dst, int startAddr, int bytes)
throws KNXTimeoutException, KNXDisconnectException, KNXRemoteException,
KNXLinkClosedException
{
if (startAddr < 0 || startAddr > 0xFFFF || bytes < 1 || bytes > 63)
throw new KNXIllegalArgumentException("argument value out of range");
if (dst.isConnectionOriented())
tl.connect(dst);
else
logger.error("doing read memory in connectionless mode, " + dst.toString());
final byte[] apdu = sendWait(dst, priority, DataUnitBuilder.createCompactAPDU(
MEMORY_READ, new byte[] { (byte) bytes, (byte) (startAddr >>> 8),
(byte) startAddr }), MEMORY_RESPONSE, 2, 65);
int no = apdu[1] & 0x3F;
if (no == 0)
throw new KNXRemoteException("could not read memory from 0x"
+ Integer.toHexString(startAddr));
final byte[] mem = new byte[no];
while (--no >= 0)
mem[no] = apdu[4 + no];
return mem;
} | /* (non-Javadoc)
@see tuwien.auto.calimero.mgmt.ManagementClient#readMemory
(tuwien.auto.calimero.mgmt.Destination, int, int) |
public void writeMemory(Destination dst, int startAddr, byte[] data)
throws KNXDisconnectException, KNXTimeoutException, KNXRemoteException,
KNXLinkClosedException
{
if (startAddr < 0 || startAddr > 0xFFFF || data.length == 0 || data.length > 63)
throw new KNXIllegalArgumentException("argument value out of range");
final byte[] asdu = new byte[data.length + 3];
asdu[0] = (byte) data.length;
asdu[1] = (byte) (startAddr >> 8);
asdu[2] = (byte) startAddr;
for (int i = 0; i < data.length; ++i)
asdu[3 + i] = data[i];
if (dst.isConnectionOriented())
tl.connect(dst);
else
logger.error("doing write memory in connectionless mode, " + dst.toString());
final byte[] send = DataUnitBuilder.createCompactAPDU(MEMORY_WRITE, asdu);
if (dst.isVerifyMode()) {
// explicitly read back data
final byte[] apdu = sendWait(dst, priority, send, MEMORY_RESPONSE, 2, 65);
if ((apdu[1] & 0x3f) == 0)
throw new KNXRemoteException("remote app. could not write memory");
if (apdu.length - 4 != data.length)
throw new KNXInvalidResponseException("number of memory bytes differ");
for (int i = 4; i < apdu.length; ++i)
if (apdu[i] != asdu[i - 1])
throw new KNXRemoteException("verify failed (erroneous memory data)");
}
else
tl.sendData(dst, priority, send);
} | /* (non-Javadoc)
@see tuwien.auto.calimero.mgmt.ManagementClient#writeMemory
(tuwien.auto.calimero.mgmt.Destination, int, byte[]) |
public void writeKey(Destination dst, int level, byte[] key)
throws KNXTimeoutException, KNXDisconnectException, KNXRemoteException,
KNXLinkClosedException
{
// level 255 is free access
if (level < 0 || level > 254 || key.length != 4)
throw new KNXIllegalArgumentException(
"level out of range or key length not 4 bytes");
if (dst.isConnectionOriented())
tl.connect(dst);
else
logger.error("doing write key in connectionless mode, " + dst.toString());
final byte[] apdu =
sendWait(dst, priority, DataUnitBuilder.createAPDU(KEY_WRITE, new byte[] {
(byte) level, key[0], key[1], key[2], key[3] }), KEY_RESPONSE, 1, 1);
if ((apdu[1] & 0xFF) == 0xFF)
throw new KNXRemoteException(
"access denied: current access level > write level");
} | /* (non-Javadoc)
@see tuwien.auto.calimero.mgmt.ManagementClient#writeKey
(tuwien.auto.calimero.mgmt.Destination, int, byte[]) |
public KNXNetworkLink detach()
{
final KNXNetworkLink lnk = tl.detach();
if (lnk != null) {
logger.info("detached from " + lnk.getName());
LogManager.getManager().removeLogService(logger.getName());
}
detached = true;
return lnk;
} | /* (non-Javadoc)
@see tuwien.auto.calimero.mgmt.ManagementClient#detach() |
private byte[] waitForResponse(int minASDULen, int maxASDULen, long timeout)
throws KNXInvalidResponseException, KNXTimeoutException
{
long remaining = timeout;
final long end = System.currentTimeMillis() + remaining;
synchronized (indications) {
while (remaining > 0) {
try {
while (indications.size() > 0) {
final CEMI frame =
((FrameEvent) indications.remove(0)).getFrame();
final byte[] apdu = frame.getPayload();
assert svcResponse == DataUnitBuilder.getAPDUService(apdu);
if (apdu.length < minASDULen + 2 || apdu.length > maxASDULen + 2) {
final String s = "invalid ASDU response length "
+ (apdu.length - 2) + " bytes, expected " + minASDULen
+ " to " + maxASDULen;
logger.error("received response with " + s);
throw new KNXInvalidResponseException(s);
}
if (svcResponse == IND_ADDR_RESPONSE
|| svcResponse == IND_ADDR_SN_RESPONSE)
return ((CEMILData) frame).getSource().toByteArray();
indications.clear();
return apdu;
}
indications.wait(remaining);
}
catch (final InterruptedException e) {}
remaining = end - System.currentTimeMillis();
}
}
throw new KNXTimeoutException("timeout occurred while waiting for data response");
} | min + max ASDU len are *not* including any field that contains ACPI |
private List makeDOAs(List l)
{
for (int i = 0; i < l.size(); ++i) {
final byte[] pdu = (byte[]) l.get(i);
if (pdu.length == 4)
l.set(i, new byte[] { pdu[2], pdu[3] });
else if (pdu.length == 8)
l.set(i, new byte[] { pdu[2], pdu[3], pdu[4], pdu[5], pdu[6], pdu[7] });
}
return l;
} | cut domain addresses out of APDUs |
public static String determineAccessorName(@Nonnull final AccessorPrefix prefix, @Nonnull final String fieldName) {
Check.notNull(prefix, "prefix");
Check.notEmpty(fieldName, "fieldName");
final Matcher m = PATTERN.matcher(fieldName);
Check.stateIsTrue(m.find(), "passed field name '%s' is not applicable", fieldName);
final String name = m.group();
return prefix.getPrefix() + name.substring(0, 1).toUpperCase() + name.substring(1);
} | Determines the accessor method name based on a field name.
@param fieldName
a field name
@return the resulting method name |
public static String determineMutatorName(@Nonnull final String fieldName) {
Check.notEmpty(fieldName, "fieldName");
final Matcher m = PATTERN.matcher(fieldName);
Check.stateIsTrue(m.find(), "passed field name '%s' is not applicable", fieldName);
final String name = m.group();
return METHOD_SET_PREFIX + name.substring(0, 1).toUpperCase() + name.substring(1);
} | Determines the mutator method name based on a field name.
@param fieldName
a field name
@return the resulting method name |
public byte[] getDescription(int objIndex, int pid, int propIndex)
throws KNXException
{
return mc.readPropertyDesc(dst, objIndex, pid, propIndex);
} | /* (non-Javadoc)
@see tuwien.auto.calimero.mgmt.PropertyAdapter#getDescription(int, int, int) |
public static String[] getPortIdentifiers()
{
String ports = null;
try {
ports = System.getProperty("microedition.commports");
}
catch (final SecurityException e) {}
if (ports != null) {
final StringTokenizer st = new StringTokenizer(ports, ",");
final String[] portIDs = new String[st.countTokens()];
for (int i = 0; i < portIDs.length; ++i)
portIDs[i] = st.nextToken();
return portIDs;
}
if (SerialCom.isLoaded()) {
final String prefix = defaultPortPrefix();
final List l = new ArrayList(10);
for (int i = 0; i < 10; ++i)
if (SerialCom.portExists(prefix + i))
l.add(prefix + i);
return (String[]) l.toArray(new String[l.size()]);
}
// skip other possible adapters for now, and return empty list...
return new String[0];
} | Attempts to gets the available serial communication ports on the host.
<p>
At first, the Java system property "microedition.commports" is queried. If there is
no property with that key, and Calimero itself has access to serial ports,
the lowest 10 ports numbers are enumerated and checked if present.<br>
The empty array is returned if no ports are discovered.
@return array of strings with found port IDs |
@Nonnull
public static XMLDSigValidationResult createReferenceErrors (@Nonnull @Nonempty final List <Integer> aInvalidReferences)
{
return new XMLDSigValidationResult (aInvalidReferences);
} | An invalid reference or references. The verification of the digest of a
reference failed. This can be caused by a change to the referenced data
since the signature was generated.
@param aInvalidReferences
The indices to the invalid references.
@return Result object |
public UPnPService getService(String serviceId) {
if (serviceId.equals(timerService.getId())) return timerService;
return null;
} | /* (non-Javadoc)
@see org.osgi.service.upnp.UPnPDevice#getService(java.lang.String) |
public synchronized void setFrame(CEMILData frame)
{
if (!frame.getDestination().equals(getKey()))
throw new KNXIllegalArgumentException("frame key differs from cache key");
value = frame;
resetTimestamp();
} | Sets a new {@link CEMILData} <code>frame</code> for this cache object.
<p>
The key generated out of <code>frame</code> (i.e. out of the KNX address of
<code>frame</code>) has to be equal to the key of this {@link LDataObject},
as returned from {@link #getKey()}. Otherwise a
{@link KNXIllegalArgumentException} will be thrown.<br>
Note that on successful set the timestamp is renewed.
@param frame the new {@link CEMILData} frame to set |
public static Chart getTrajectoryChart(String title, Trajectory t){
if(t.getDimension()==2){
double[] xData = new double[t.size()];
double[] yData = new double[t.size()];
for(int i = 0; i < t.size(); i++){
xData[i] = t.get(i).x;
yData[i] = t.get(i).y;
}
// Create Chart
Chart chart = QuickChart.getChart(title, "X", "Y", "y(x)", xData, yData);
return chart;
//Show it
// SwingWrapper swr = new SwingWrapper(chart);
// swr.displayChart();
}
return null;
} | Plots the trajectory
@param title Title of the plot
@param t Trajectory to be plotted |
public static Chart getMSDLineChart(Trajectory t, int lagMin, int lagMax,
AbstractMeanSquaredDisplacmentEvaluator msdeval) {
double[] xData = new double[lagMax - lagMin + 1];
double[] yData = new double[lagMax - lagMin + 1];
msdeval.setTrajectory(t);
msdeval.setTimelag(lagMin);
for (int i = lagMin; i < lagMax + 1; i++) {
msdeval.setTimelag(i);
double msdhelp = msdeval.evaluate()[0];
xData[i - lagMin] = i;
yData[i - lagMin] = msdhelp;
}
// Create Chart
Chart chart = QuickChart.getChart("MSD Line", "LAG", "MSD", "MSD",
xData, yData);
// Show it
//new SwingWrapper(chart).displayChart();
return chart;
} | Plots the MSD curve for trajectory t
@param t Trajectory to calculate the msd curve
@param lagMin Minimum timelag (e.g. 1,2,3..) lagMin*timelag = elapsed time in seconds
@param lagMax Maximum timelag (e.g. 1,2,3..) lagMax*timelag = elapsed time in seconds
@param msdeval Evaluates the mean squared displacment |
public static Chart getMSDLineWithConfinedModelChart(Trajectory t, int lagMin,
int lagMax, double timelag, double a, double b, double c, double d) {
double[] xData = new double[lagMax - lagMin + 1];
double[] yData = new double[lagMax - lagMin + 1];
double[] modelData = new double[lagMax - lagMin + 1];
MeanSquaredDisplacmentFeature msdeval = new MeanSquaredDisplacmentFeature(
t, lagMin);
msdeval.setTrajectory(t);
msdeval.setTimelag(lagMin);
for (int i = lagMin; i < lagMax + 1; i++) {
msdeval.setTimelag(i);
double msdhelp = msdeval.evaluate()[0];
xData[i - lagMin] = i;
yData[i - lagMin] = msdhelp;
modelData[i - lagMin] = a
* (1 - b * Math.exp((-4 * d) * ((i * timelag) / a) * c));
}
// Create Chart
Chart chart = QuickChart.getChart("MSD Line", "LAG", "MSD", "MSD",
xData, yData);
if(Math.abs(1-b)<0.00001 && Math.abs(1-a)<0.00001){
chart.addSeries("y=a*(1-exp(-4*D*t/a))", xData, modelData);
}else{
chart.addSeries("y=a*(1-b*exp(-4*c*D*t/a))", xData, modelData);
}
// Show it
//new SwingWrapper(chart).displayChart();
return chart;
} | Plots the MSD curve with the trajectory t and adds the fitted model for confined diffusion above.
@param t Trajectory to calculate the msd curve
@param lagMin Minimum timelag (e.g. 1,2,3..) lagMin*timelag = elapsed time in seconds
@param lagMax Maximum timelag (e.g. 1,2,3..) lagMax*timelag = elapsed time in seconds
@param timelag Elapsed time between two frames.
@param a Parameter alpha
@param b Shape parameter 1
@param c Shape parameter 2
@param d Diffusion coefficient |
public static Chart getMSDLineWithPowerModelChart(Trajectory t, int lagMin,
int lagMax, double timelag, double a, double D) {
double[] xData = new double[lagMax - lagMin + 1];
double[] yData = new double[lagMax - lagMin + 1];
double[] modelData = new double[lagMax - lagMin + 1];
MeanSquaredDisplacmentFeature msdeval = new MeanSquaredDisplacmentFeature(
t, lagMin);
msdeval.setTrajectory(t);
msdeval.setTimelag(lagMin);
for (int i = lagMin; i < lagMax + 1; i++) {
msdeval.setTimelag(i);
double msdhelp = msdeval.evaluate()[0];
xData[i - lagMin] = i;
yData[i - lagMin] = msdhelp;
modelData[i - lagMin] = 4 * D * Math.pow(i * timelag, a);
}
// Create Chart
Chart chart = QuickChart.getChart("MSD Line", "LAG", "MSD", "MSD",
xData, yData);
chart.addSeries("y=4*D*t^alpha", xData, modelData);
// Show it
//new SwingWrapper(chart).displayChart();
return chart;
} | Plots the MSD curve with the trajectory t and adds the fitted model for anomalous diffusion above.
@param t
@param lagMin Minimum timelag (e.g. 1,2,3..) lagMin*timelag = elapsed time in seconds
@param lagMax lagMax Maximum timelag (e.g. 1,2,3..) lagMax*timelag = elapsed time in seconds
@param timelag Elapsed time between two frames.
@param a Exponent alpha of power law function
@param D Diffusion coeffcient |
public static Chart getMSDLineWithFreeModelChart(Trajectory t, int lagMin,
int lagMax, double timelag, double diffusionCoefficient, double intercept) {
double[] xData = new double[lagMax - lagMin + 1];
double[] yData = new double[lagMax - lagMin + 1];
double[] modelData = new double[lagMax - lagMin + 1];
MeanSquaredDisplacmentFeature msdeval = new MeanSquaredDisplacmentFeature(
t, lagMin);
msdeval.setTrajectory(t);
msdeval.setTimelag(lagMin);
for (int i = lagMin; i < lagMax + 1; i++) {
msdeval.setTimelag(i);
double msdhelp = msdeval.evaluate()[0];
xData[i - lagMin] = i;
yData[i - lagMin] = msdhelp;
modelData[i - lagMin] = intercept + 4*diffusionCoefficient*(i*timelag);//4 * D * Math.pow(i * timelag, a);
}
// Create Chart
Chart chart = QuickChart.getChart("MSD Line", "LAG", "MSD", "MSD",
xData, yData);
chart.addSeries("y=4*D*t + a", xData, modelData);
// Show it
//new SwingWrapper(chart).displayChart();
return chart;
} | Plots the MSD curve with the trajectory t and adds the fitted model for free diffusion.
@param t
@param lagMin Minimum timelag (e.g. 1,2,3..) lagMin*timelag = elapsed time in seconds
@param lagMax lagMax Maximum timelag (e.g. 1,2,3..) lagMax*timelag = elapsed time in seconds
@param timelag Elapsed time between two frames.
@param diffusionCoefficient Diffusion coefficient
@param intercept |
public static Chart getMSDLineWithActiveTransportModelChart(Trajectory t, int lagMin,
int lagMax, double timelag, double diffusionCoefficient, double velocity) {
double[] xData = new double[lagMax - lagMin + 1];
double[] yData = new double[lagMax - lagMin + 1];
double[] modelData = new double[lagMax - lagMin + 1];
MeanSquaredDisplacmentFeature msdeval = new MeanSquaredDisplacmentFeature(
t, lagMin);
msdeval.setTrajectory(t);
msdeval.setTimelag(lagMin);
for (int i = lagMin; i < lagMax + 1; i++) {
msdeval.setTimelag(i);
double msdhelp = msdeval.evaluate()[0];
xData[i - lagMin] = i;
yData[i - lagMin] = msdhelp;
modelData[i - lagMin] = Math.pow(velocity*(i*timelag), 2) + 4*diffusionCoefficient*(i*timelag);//4 * D * Math.pow(i * timelag, a);
}
// Create Chart
Chart chart = QuickChart.getChart("MSD Line", "LAG", "MSD", "MSD",
xData, yData);
chart.addSeries("y=4*D*t + (v*t)^2", xData, modelData);
// Show it
//new SwingWrapper(chart).displayChart();
return chart;
} | Plots the MSD curve with the trajectory t and adds the fitted model for directed motion above.
@param t
@param lagMin Minimum timelag (e.g. 1,2,3..) lagMin*timelag = elapsed time in seconds
@param lagMax lagMax Maximum timelag (e.g. 1,2,3..) lagMax*timelag = elapsed time in seconds
@param timelag Elapsed time between two frames.
@param diffusionCoefficient Diffusion coefficient
@param velocity velocity of the active transport |
public static Chart getMSDLineChart(ArrayList<? extends Trajectory> t, int lagMin,
int lagMax, AbstractMeanSquaredDisplacmentEvaluator msdeval) {
double[] xData = new double[lagMax - lagMin + 1];
double[] yData = new double[lagMax - lagMin + 1];
for (int j = lagMin; j < lagMax + 1; j++) {
double msd = 0;
int N = 0;
for (int i = 0; i < t.size(); i++) {
if(t.get(i).size()>lagMax){
msdeval.setTrajectory(t.get(i));
msdeval.setTimelag(j);
msd += msdeval.evaluate()[0];
N++;
}
}
msd = 1.0 / N * msd;
xData[j - lagMin] = j;
yData[j - lagMin] = msd;
}
// Create Chart
Chart chart = QuickChart.getChart("MSD Line", "LAG", "MSD", "MSD",
xData, yData);
// Show it
// new SwingWrapper(chart).displayChart();
return chart;
} | Plots the mean MSD curve over all trajectories in t.
@param t List of trajectories
@param lagMin Minimum timelag (e.g. 1,2,3..) lagMin*timelag = elapsed time in seconds
@param lagMax Maximum timelag (e.g. 1,2,3..) lagMax*timelag = elapsed time in seconds
@param msdeval Evaluates the mean squared displacment |
public static Chart getMSDLineChart(Trajectory t, int lagMin, int lagMax) {
return getMSDLineChart(t, lagMin, lagMax, new MeanSquaredDisplacmentFeature(t,
lagMin));
} | Plots the MSD curve for trajectory t.
@param t List of trajectories
@param lagMin Minimum timelag (e.g. 1,2,3..) lagMin*timelag = elapsed time in seconds
@param lagMax Maximum timelag (e.g. 1,2,3..) lagMax*timelag = elapsed time in seconds |
public static Chart getMSDLineChart(ArrayList<Trajectory> t, int lagMin,
int lagMax) {
return getMSDLineChart(t, lagMin, lagMax,
new MeanSquaredDisplacmentFeature(t.get(0), lagMin));
} | Plots the mean MSD curve over all trajectories in t.
@param t List of trajectories
@param lagMin Minimum timelag (e.g. 1,2,3..) lagMin*timelag = elapsed time in seconds
@param lagMax Maximum timelag (e.g. 1,2,3..) lagMax*timelag = elapsed time in seconds |
public static void plotCharts(List<Chart> charts){
int numRows =1;
int numCols =1;
if(charts.size()>1){
numRows = (int) Math.ceil(charts.size()/2.0);
numCols = 2;
}
final JFrame frame = new JFrame("");
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.getContentPane().setLayout(new GridLayout(numRows, numCols));
for (Chart chart : charts) {
if (chart != null) {
JPanel chartPanel = new XChartPanel(chart);
frame.add(chartPanel);
}
else {
JPanel chartPanel = new JPanel();
frame.getContentPane().add(chartPanel);
}
}
// Display the window.
frame.pack();
frame.setVisible(true);
} | Plots a list of charts in matrix with 2 columns.
@param charts |
DataInputStream openDataInputStream()
{
final InputStream is = getInputStream();
if (is instanceof DataInputStream) {
return (DataInputStream) is;
}
return new DataInputStream(is);
} | /* (non-Javadoc)
@see javax.microedition.io.InputConnection#openDataInputStream() |
DataOutputStream openDataOutputStream()
{
final OutputStream os = getOutputStream();
if (os instanceof DataOutputStream) {
return (DataOutputStream) os;
}
return new DataOutputStream(os);
} | /* (non-Javadoc)
@see javax.microedition.io.OutputConnection#openDataOutputStream() |
public static CRD createResponse(byte[] data, int offset) throws KNXFormatException
{
return (CRD) create(false, data, offset);
} | Creates a new CRD out of a byte array.
<p>
If possible, a matching, more specific, CRD subtype is returned. Note, that CRD for
specific communication types might expect certain characteristics on
<code>data</code> (regarding contained data).<br>
@param data byte array containing the CRD structure
@param offset start offset of CRD in <code>data</code>
@return the new CRD object
@throws KNXFormatException if no CRD found or invalid structure |
@Nonnull
public Imports copyAndAdd(final Collection<Import> imports) {
Check.notNull(imports, "imports");
final List<Import> internal = Lists.newArrayList(imports);
internal.addAll(imports);
return new Imports(internal);
} | Adds the passed set of {@code Import}s to the current set and returns them as new instance of {@code Imports}.
@param imports
set of {@code Import}s to add
@return new instance of {@code Imports} |
@Nonnull
public Imports copyAndAdd(final Imports imports) {
Check.notNull(imports, "imports");
return copyAndAdd(imports.asList());
} | Adds the passed {@code Imports} to the current set and returns them as new instance of {@code Imports}.
@param imports
{@code Imports} to add
@return new instance of {@code Imports} |
@Nonnull
public Imports filter() {
return new Imports(Sets.newHashSet(Collections2.filter(imports, Predicates.and(IGNORE_JAVA_LANG, IGNORE_UNDEFINED))));
} | Filters primitive types, types without a package declaration and duplicates and returns them as new instance of
{@code Imports}.
@return new instance of {@code Imports} |
@Nullable
public Import find(@Nonnull final String typeName) {
Check.notEmpty(typeName, "typeName");
Import ret = null;
final Type type = new Type(typeName);
for (final Import imp : imports) {
if (imp.getType().getName().equals(type.getName())) {
ret = imp;
break;
}
}
if (ret == null) {
final Type javaLangType = Type.evaluateJavaLangType(typeName);
if (javaLangType != null) {
ret = Import.of(javaLangType);
}
}
return ret;
} | Searches the set of imports to find a matching import by type name.
@param typeName
name of type (qualified or simple name allowed)
@return found import or {@code null} |
@Nonnull
public Imports sortByName() {
final List<Import> imports = Lists.newArrayList(this.imports);
Collections.sort(imports, ORDER.nullsLast());
return new Imports(imports);
} | Sorts the current set of {@code Import}s by name and returns them as new instance of {@code Imports}.
@return new instance of {@code Imports} |
public synchronized void destroy()
{
if (state == DESTROYED)
return;
if (state != DISCONNECTED)
try {
tl.disconnect(this);
}
catch (final KNXLinkClosedException e) {
// we already should've been destroyed on catching this exception
}
setState(DESTROYED);
tl.destroyDestination(this);
} | Destroys this destination.
<p>
If the connection state is connected, it will be disconnected. The connection state
is set to {@link #DESTROYED}. The associated transport layer is notified through
{@link TransportLayer#destroyDestination(Destination)}. <br>
On an already destroyed destination, no action is performed. |
private void query(String zipcode) {
/* Setup YQL query statement using dynamic zipcode. The statement searches geo.places
for the zipcode and returns XML which includes the WOEID. For more info about YQL go
to: http://developer.yahoo.com/yql/ */
String qry = URLEncoder.encode("SELECT woeid FROM geo.places WHERE text=" + zipcode + " LIMIT 1");
// Generate request URI using the query statement
URL url;
try {
// get URL content
url = new URL("http://query.yahooapis.com/v1/public/yql?q=" + qry);
URLConnection conn = url.openConnection();
InputStream content = conn.getInputStream();
parseResponse(content);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} | Query zipcode from Yahoo to find associated WOEID |
private void parseResponse(InputStream inputStream) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputStream);
doc.getDocumentElement().normalize();
NodeList nodes = doc.getElementsByTagName("place");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
_woeid = getValue("woeid", element);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
} | Extract WOEID after XML loads |
public String getErrorMessage()
{
if (!isNegativeResponse())
return "no error";
final int err = data[0] & 0xFF;
if (err > errors.length - 1)
return "unknown error code";
return errors[err];
} | Returns a descriptive error message on a negative response, as determined by
{@link #isNegativeResponse()}.
<p>
A negative response contains an error information code, which is used to find the
associated message.<br>
If invoked on positive response, "no error" will be returned.
@return error status message as string |
public void startSearch(int localPort, NetworkInterface ni, int timeout, boolean wait)
throws KNXException
{
if (timeout < 0)
throw new KNXIllegalArgumentException("timeout has to be >= 0");
if (localPort < 0 || localPort > 65535)
throw new KNXIllegalArgumentException("port out of range [0..0xFFFF]");
final Receiver r = search(new InetSocketAddress(host, localPort), ni, timeout);
if (wait)
join(r);
} | Starts a new discovery, the <code>localPort</code> and network interface can be
specified.
<p>
The search will continue for <code>timeout</code> seconds, or infinite if timeout
value is zero. During this time, search responses will get collected asynchronous
in the background by this {@link Discoverer}.<br>
With <code>wait</code> you can force this method into blocking mode to wait until
the search finished, otherwise the method returns with the search running in the
background.<br>
A search is finished if either the <code>timeout</code> was reached or the
background receiver stopped.<br>
The reason the <code>localPort</code> parameter is specified here, in addition to
the port queried at {@link #Discoverer(int, boolean)}, is to distinguish between
search responses if more searches are running concurrently.<br>
@param localPort the port used to bind the socket, a valid port is 0 to 65535, if
localPort is zero an arbitrary unused (ephemeral) port is picked
@param ni the {@link NetworkInterface} used for sending outgoing multicast
messages, or <code>null</code> to use the default multicast interface
@param timeout time window in seconds during which search response messages will
get collected, timeout >= 0. If timeout is zero, no timeout is set, the
search has to be stopped with {@link #stopSearch()}.
@param wait <code>true</code> to block until end of search before return
@throws KNXException on network I/O error
@see MulticastSocket
@see NetworkInterface |
public void startSearch(int timeout, boolean wait) throws KNXException
{
if (timeout < 0)
throw new KNXIllegalArgumentException("timeout has to be >= 0");
final Enumeration eni;
try {
eni = NetworkInterface.getNetworkInterfaces();
}
catch (final SocketException e) {
logger.error("failed to get network interfaces", e);
throw new KNXException("network interface error: " + e.getMessage());
}
if (eni == null) {
logger.error("no network interfaces found");
throw new KNXException("no network interfaces found");
}
final List rcv = new ArrayList();
boolean lo = false;
while (eni.hasMoreElements()) {
final NetworkInterface ni = (NetworkInterface) eni.nextElement();
for (final Enumeration ea = ni.getInetAddresses(); ea.hasMoreElements();) {
final InetAddress a = (InetAddress) ea.nextElement();
if (!isNatAware && a.getAddress().length != 4)
logger.info("skipped " + a + ", not an IPv4 address");
else
try {
if (!(lo && a.isLoopbackAddress()))
rcv.add(search(new InetSocketAddress(a, port), ni, timeout));
if (a.isLoopbackAddress())
lo = true;
else
break;
}
catch (final KNXException e) {}
}
}
if (rcv.size() == 0)
throw new KNXException("search couldn't be started on any network interface");
if (wait)
for (final Iterator i = rcv.iterator(); i.hasNext();)
join((Thread) i.next());
}
/**
* Stops every search currently running within this Discoverer.
* <p>
* Already gathered search responses from a search will not be removed.
*/
public final void stopSearch()
{
synchronized (receiver) {
for (final Iterator i = receiver.iterator(); i.hasNext();)
((Receiver) i.next()).quit();
receiver.clear();
}
}
/**
* Returns <code>true</code> if a search is currently running.
* <p>
*
* @return a <code>boolean</code> showing the search state
*/
public final boolean isSearching()
{
return receiver.size() != 0;
}
/**
* Returns all collected search responses received by searches so far.
* <p>
* As long as searches are running, new responses might be added to the list of
* responses.
*
* @return array of {@link SearchResponse}s
* @see #stopSearch()
*/
public final SearchResponse[] getSearchResponses()
{
return (SearchResponse[]) responses.toArray(new SearchResponse[responses.size()]);
}
/**
* Removes all search responses collected so far.
* <p>
*/
public final void clearSearchResponses()
{
responses.clear();
}
/**
* Sends a description request to <code>server</code> and waits at most
* <code>timeout</code> seconds for the answer message to arrive.
* <p>
*
* @param server the InetSocketAddress of the server the description is requested from
* @param timeout time window in seconds to wait for answer message, 0 < timeout
* < ({@link Integer#MAX_VALUE} / 1000)
* @return the description response message
* @throws KNXException on network I/O error
* @throws KNXTimeoutException if the timeout was reached before the description
* response arrived
* @throws KNXInvalidResponseException if a received message from <code>server</code>
* does not match the expected response
*/
public DescriptionResponse getDescription(InetSocketAddress server, int timeout)
throws KNXException
{
if (timeout <= 0 || timeout >= Integer.MAX_VALUE / 1000)
throw new KNXIllegalArgumentException("timeout out of range");
DatagramSocket s = null;
try {
s = new DatagramSocket(port, host);
final byte[] buf = PacketHelper.toPacket(new DescriptionRequest(
isNatAware ? null : (InetSocketAddress) s.getLocalSocketAddress()));
s.send(new DatagramPacket(buf, buf.length, server));
final long end = System.currentTimeMillis() + timeout * 1000L;
DatagramPacket p = null;
while ((p = receive(s, end)) != null) {
if (p.getSocketAddress().equals(server)) {
final KNXnetIPHeader h =
new KNXnetIPHeader(p.getData(), p.getOffset());
if (h.getServiceType() == KNXnetIPHeader.DESCRIPTION_RES)
return new DescriptionResponse(p.getData(), p.getOffset()
+ h.getStructLength());
}
}
}
catch (final IOException e) {
final String msg = "network failure on getting description";
logger.error(msg, e);
throw new KNXException(msg);
}
catch (final KNXFormatException e) {
logger.error("invalid description response", e);
throw new KNXInvalidResponseException(e.getMessage());
}
finally {
if (s != null)
s.close();
}
final String msg = "timeout, no description response received";
logger.warn(msg);
throw new KNXTimeoutException(msg);
}
/**
* Starts a search sending a search request message.
* <p>
*
* @param a local SocketAddress to send search request from
* @param ni {@link NetworkInterface} used to send outgoing multicast, or
* <code>null</code> to use the default multicast interface
* @param timeout timeout in seconds, timeout >= 0, 0 for an infinite time window
* @return the receiver thread for the search started
* @throws KNXException
*/
private Receiver search(InetSocketAddress a, NetworkInterface ni, int timeout)
throws KNXException
{
logger.info("search on " + a);
MulticastSocket s = null;
try {
s = new MulticastSocket(a);
if (ni != null)
s.setNetworkInterface(ni);
final byte[] buf = PacketHelper.toPacket(new SearchRequest(isNatAware ? null
: (InetSocketAddress) s.getLocalSocketAddress()));
s.send(new DatagramPacket(buf, buf.length, multicast, SEARCH_PORT));
final Receiver r = new Receiver(s, timeout);
receiver.add(r);
return r;
}
catch (final IOException e) {
if (s != null)
s.close();
e.printStackTrace();
logger.warn("I/O failure sending search request on " + a, e);
throw new KNXException("search request failed, " + e.getMessage());
}
}
// timeEnd = 0 for infinite timeout
private DatagramPacket receive(DatagramSocket s, long timeEnd) throws IOException
{
final long timeout = timeEnd == 0 ? 0 : timeEnd - System.currentTimeMillis();
if (timeout > 0 || timeEnd == 0) {
final byte[] buf = new byte[bufferSize];
final DatagramPacket p = new DatagramPacket(buf, bufferSize);
try {
s.setSoTimeout((int) timeout);
s.receive(p);
return p;
}
catch (final InterruptedIOException ignore) {}
}
return null;
}
private void join(Thread t)
{
while (t.isAlive())
try {
t.join();
}
catch (final InterruptedException ignore) {}
}
private void checkHost() throws KNXException
{
if (isNatAware || host.getAddress().length == 4)
return;
final KNXException e =
new KNXException(host.getHostAddress() + " is not an IPv4 address");
logger.error("NAT not used, only IPv4 address support", e);
throw e;
}
private final class Receiver extends Thread
{
private volatile boolean quit;
private final MulticastSocket s;
private final int timeout;
/**
* Creates a new Receiver.
* <p>
*
* @param socket socket to receive from
* @param timeout live time of this Receiver, timeout >= 0, 0 is infinite timeout
*/
Receiver(MulticastSocket socket, int timeout)
{
super("Discoverer receiver " + socket.getLocalAddress().getHostAddress());
s = socket;
this.timeout = timeout;
setDaemon(true);
start();
}
void quit()
{
quit = true;
s.close();
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
public void run()
{
final long end = System.currentTimeMillis() + timeout * 1000;
DatagramPacket p;
try {
while (!quit && (p = receive(s, timeout == 0 ? 0 : end)) != null)
checkForResponse(p);
}
catch (final IOException e) {
if (!quit)
logger.error("while waiting for response", e);
}
finally {
s.close();
receiver.remove(this);
}
}
private void checkForResponse(final DatagramPacket p)
{
try {
final KNXnetIPHeader h = new KNXnetIPHeader(p.getData(), p.getOffset());
if (h.getServiceType() == KNXnetIPHeader.SEARCH_RES)
// sync with receiver queue: check if our search was stopped
synchronized (receiver) {
if (receiver.contains(this))
responses.add(new SearchResponse(p.getData(), p.getOffset()
+ h.getStructLength()));
}
}
catch (final KNXFormatException ignore) {}
}
}
} | Starts a new discovery from all found network interfaces.
<p>
The search will continue for <code>timeout</code> seconds, or infinite if timeout
value is zero. During this time, search responses will get collected asynchronous
in the background by this Discoverer.<br>
With <code>wait</code> you can force this method into blocking mode to wait until
the search finished, otherwise the method returns with the search running in the
background.<br>
A search has finished if either the <code>timeout</code> was reached, all
background receiver stopped (all responses received) or {@link #stopSearch()} was
invoked.
@param timeout time window in seconds during which search response messages will
get collected, timeout >= 0. If timeout is 0, no timeout is set, the search
has to be stopped with <code>stopSearch</code>.
@param wait <code>true</code> to block until end of search before return
@throws KNXException on network I/O error |
public static void main(String[] args)
{
try {
new IPConfig(args);
}
catch (final Throwable t) {
if (t.getMessage() != null)
System.out.println(t.getMessage());
}
} | Entry point for running IPConfig.
<p>
An IP host or port identifier has to be supplied to specify the endpoint for the
KNX network access.<br>
To show the usage message of this tool on the console, supply the command line
option -help (or -h).<br>
Command line options are treated case sensitive. Available options:
<ul>
<li><code>-help -h</code> show help message</li>
<li><code>-version</code> show tool/library version and exit</li>
<li><code>-local -l</code> local device management</li>
<li><code>-remote -r</code> <i>KNX addr</i> remote property service</li>
<li><code>-localhost</code> <i>id</i> local IP/host name</li>
<li><code>-localport</code> <i>number</i> local UDP port (default system
assigned)</li>
<li><code>-port -p</code> <i>number</i> UDP port on host (default 3671)</li>
<li><code>-nat -n</code> enable Network Address Translation</li>
<li><code>-serial -s</code> use FT1.2 serial communication</li>
</ul>
For remote property service these options are available:
<ul>
<li><code>-routing</code> use KNXnet/IP routing</li>
<li><code>-medium -m</code> <i>id</i> KNX medium [tp0|tp1|p110|p132|rf]
(defaults to tp1)</li>
<li><code>-connect -c</code> connection oriented mode</li>
<li><code>-authorize -a</code> <i>key</i> authorize key to access KNX
device</li>
</ul>
<br>
In any case, the tool reads out the IP configuration of the connected endpoint and
writes it to standard output.<br>
Supply one or more of the following commands to change the IP configuration (these
commands are accepted without regard to capitalization):
<ul>
<li><code>IP</code> <i>address</i> set the configured fixed IP address</li>
<li><code>subnet</code> <i>address</i> set the configured IP subnet mask</li>
<li><code>gateway</code> <i>address</i> set the configured IP address of
the default gateway</li>
<li><code>multicast</code> <i>address</i> set the routing multicast
address</li>
<li><code>manual</code> set manual IP assignment for the current IP address to
enabled</li>
<li><code>BootP</code> set Bootstrap Protocol IP assignment for the current IP
address to enabled</li>
<li><code>DHCP</code> set DHCP IP assignment for the current IP address to
enabled</li>
<li><code>AutoIP</code> set automatic IP assignment for the current IP address
to enabled</li>
</ul>
@param args command line options to run the tool |
protected void receivedConfig(List config)
{
System.out.println("KNXnet/IP server " + ((String[]) config.get(0))[2] + " "
+ ((String[]) config.get(1))[2]);
final String padding = " ";
for (int i = 2; i < config.size(); ++i) {
final String[] s = (String[]) config.get(i);
System.out.println(s[1] + padding.substring(s[1].length()) + s[2]);
}
} | Supplies information about a received IP configuration.
<p>
This default implementation writes information to standard output.
@param config a list with config entries, a config entry is of type String[3], with
[0] being the PID, [1] being a short config name, [2] being the value |
private PropertyAdapter create(Map options) throws KNXException
{
// create local and remote socket address for use in adapter
final InetSocketAddress local = createLocalSocket((InetAddress) options
.get("localhost"), (Integer) options.get("localport"));
final InetSocketAddress host = new InetSocketAddress((InetAddress) options
.get("host"), ((Integer) options.get("port")).intValue());
// decide what type of adapter to create
if (options.containsKey("localDM"))
return createLocalDMAdapter(local, host, options);
return createRemoteAdapter(local, host, options);
} | Creates the property adapter to be used, depending on the supplied user
<code>options</code>.
<p>
There are two types of property adapters. One uses KNXnet/IP local device
management to access KNX properties in an interface object, the other type uses
remote property services. The remote adapter needs a KNX network link to access the
KNX network, the link is also created by this method if this adapter type is
requested.
@param options contains parameters for property adapter creation
@return the created adapter
@throws KNXException on adapter creation problem |
private PropertyAdapter createLocalDMAdapter(InetSocketAddress local,
InetSocketAddress host, Map options) throws KNXException
{
return new KnIPDeviceMgmtAdapter(local, host, options.containsKey("nat"), null,
false);
} | Creates a local device management adapter.
<p>
@param local local socket address
@param host remote socket address of host
@param options contains parameters for property adapter creation
@return local DM adapter
@throws KNXException on adapter creation problem |
private PropertyAdapter createRemoteAdapter(InetSocketAddress local,
InetSocketAddress host, Map options) throws KNXException
{
final KNXMediumSettings medium = (KNXMediumSettings) options.get("medium");
if (options.containsKey("serial")) {
// create FT1.2 network link
final String p = (String) options.get("serial");
try {
lnk = new KNXNetworkLinkFT12(Integer.parseInt(p), medium);
}
catch (final NumberFormatException e) {
lnk = new KNXNetworkLinkFT12(p, medium);
}
}
else {
final int mode = options.containsKey("routing") ? KNXNetworkLinkIP.ROUTER
: KNXNetworkLinkIP.TUNNEL;
lnk = new KNXNetworkLinkIP(mode, local, host, options.containsKey("nat"),
medium);
}
final IndividualAddress remote = (IndividualAddress) options.get("remote");
// if an authorization key was supplied, the adapter uses
// connection oriented mode and tries to authenticate
final byte[] authKey = (byte[]) options.get("authorize");
if (authKey != null)
return new RemotePropertyServiceAdapter(lnk, remote, null, authKey);
return new RemotePropertyServiceAdapter(lnk, remote, null, options
.containsKey("connect"));
} | Creates a remote property service adapter for one device in the KNX network.
<p>
The adapter uses a KNX network link for access, also is created by this method.
@param local local socket address
@param host remote socket address of host
@param options contains parameters for property adapter creation
@return remote property service adapter
@throws KNXException on adapter creation problem |
@Nonnull
public static InterfaceAnalysis analyze(@Nonnull final String code) {
Check.notNull(code, "code");
final CompilationUnit unit = Check.notNull(SourceCodeReader.parse(code), "compilationUnit");
final List<TypeDeclaration> types = Check.notEmpty(unit.getTypes(), "typeDeclarations");
Check.stateIsTrue(types.size() == 1, "only one interface declaration per analysis is supported");
final ClassOrInterfaceDeclaration type = (ClassOrInterfaceDeclaration) types.get(0);
final Imports imports = SourceCodeReader.findImports(unit.getImports());
final Package pkg = unit.getPackage() != null ? new Package(unit.getPackage().getName().toString()) : Package.UNDEFINED;
final List<Annotation> annotations = SourceCodeReader.findAnnotations(type.getAnnotations(), imports);
final List<Method> methods = SourceCodeReader.findMethods(type.getMembers(), imports);
Check.stateIsTrue(!hasPossibleMutatingMethods(methods), "The passed interface '%s' seems to have mutating methods", type.getName());
final List<Interface> extendsInterfaces = SourceCodeReader.findExtends(type);
final String interfaceName = type.getName();
return new ImmutableInterfaceAnalysis(annotations, extendsInterfaces, imports.asList(), interfaceName, methods, pkg);
} | Analyzes the source code of an interface. The specified interface must not contain methods, that changes the
state of the corresponding object itself.
@param code
source code of an interface which describes how to generate the <i>immutable</i>
@return analysis result |
private static boolean hasPossibleMutatingMethods(@Nonnull final List<Method> methods) {
boolean result = false;
for (final Method method : methods) {
if (!method.getAttributes().isEmpty()) {
result = true;
break;
}
}
return result;
} | Checks if the given type has possible mutating methods (e.g. setter methods or methods with parameters).
@param type
interface
@return {@code true} if possible mutating methods were found otherwise {@code false} |
public byte[] toByteArray()
{
final byte[] buf = super.toByteArray();
int i = 2;
for (final Iterator it = map.entrySet().iterator(); it.hasNext();) {
final Map.Entry e = (Map.Entry) it.next();
buf[i++] = ((Short) e.getKey()).byteValue();
buf[i++] = ((Short) e.getValue()).byteValue();
}
return buf;
} | /* (non-Javadoc)
@see tuwien.auto.calimero.knxnetip.util.DIB#toByteArray() |
public void setOutput(Writer output, boolean close)
{
reset();
w = new BufferedWriter(output);
closeWriter = close;
} | /* (non-Javadoc)
@see tuwien.auto.calimero.xml.XMLWriter#setOutput(java.io.Writer, boolean) |
public void writeDeclaration(boolean standalone, String encoding)
throws KNXMLException
{
try {
w.write("<?xml version=" + quote + "1.0" + quote);
w.write(" standalone=" + quote + (standalone ? "yes" : "no") + quote);
if (encoding != null && encoding.length() > 0)
w.write(" encoding=" + quote + encoding + quote);
w.write("?>");
w.newLine();
}
catch (final IOException e) {
throw new KNXMLException(e.getMessage());
}
} | /* (non-Javadoc)
@see tuwien.auto.calimero.xml.XMLWriter#writeDeclaration(boolean, java.lang.String) |
public void writeElement(String name, List att, String content) throws KNXMLException
{
try {
final Tag tag = new Tag(name, att, content, false);
layout.push(tag);
}
catch (final IOException e) {
throw new KNXMLException(e.getMessage());
}
} | /* (non-Javadoc)
@see tuwien.auto.calimero.xml.XMLWriter#writeElement
(java.lang.String, java.util.List, java.lang.String) |
public void writeEmptyElement(String name, List att) throws KNXMLException
{
try {
final Tag tag = new Tag(name, att, null, true);
tag.endTag();
}
catch (final IOException e) {
throw new KNXMLException(e.getMessage());
}
} | /* (non-Javadoc)
@see tuwien.auto.calimero.xml.XMLWriter#writeEmptyElement
(java.lang.String, java.util.List) |
public void writeCharData(String text, boolean isCDATASection) throws KNXMLException
{
try {
if (isCDATASection) {
w.write("<![CDATA[");
w.write(text);
w.write("]]>");
}
else
w.write(References.replace(text, true));
}
catch (final IOException e) {
throw new KNXMLException(e.getMessage());
}
} | /* (non-Javadoc)
@see tuwien.auto.calimero.xml.XMLWriter#writeCharData(java.lang.String, boolean) |
public void writeComment(String comment) throws KNXMLException
{
try {
w.write("<!--");
w.write(comment);
w.write("-->");
w.newLine();
}
catch (final IOException e) {
throw new KNXMLException(e.getMessage());
}
} | /* (non-Javadoc)
@see tuwien.auto.calimero.xml.XMLWriter#writeComment(java.lang.String) |
public void endElement() throws KNXMLException
{
if (layout.empty())
throw new KNXIllegalStateException("no elements to end");
try {
((Tag) layout.pop()).endTag();
if (layout.empty())
w.flush();
}
catch (final IOException e) {
throw new KNXMLException(e.getMessage());
}
} | /* (non-Javadoc)
@see tuwien.auto.calimero.xml.XMLWriter#endElement() |
public void endAllElements() throws KNXMLException
{
try {
while (!layout.empty())
((Tag) layout.pop()).endTag();
w.flush();
}
catch (final IOException e) {
throw new KNXMLException(e.getMessage());
}
} | /* (non-Javadoc)
@see tuwien.auto.calimero.xml.XMLWriter#endAllElements() |
public void close() throws KNXMLException
{
if (!layout.isEmpty())
endAllElements();
if (closeWriter)
try {
w.close();
}
catch (final IOException e) {
throw new KNXMLException(e.getMessage());
}
} | /* (non-Javadoc)
@see tuwien.auto.calimero.xml.XMLWriter#close() |
public Integer next() {
for(int i = currentIndex; i < t.size(); i++){
if(i+timelag>=t.size()){
return null;
}
if((t.get(i) != null) && (t.get(i+timelag) != null)){
if(overlap){
currentIndex = i+1;
}
else{
currentIndex = i+timelag;
}
return i;
}
}
return null;
} | Give next index i where i and i+timelag is valid |
public void write(byte[] b) throws IOException
{
if (b == null)
throw new NullPointerException();
p.writeBytes(b, 0, b.length);
} | /* (non-Javadoc)
@see java.io.OutputStream#write(byte[]) |
public void write(byte[] b, int off, int len) throws IOException
{
if (b == null)
throw new NullPointerException();
if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length)
|| ((off + len) < 0))
throw new IndexOutOfBoundsException();
p.writeBytes(b, off, len);
} | /* (non-Javadoc)
@see java.io.OutputStream#write(byte[], int, int) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.