code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
public boolean readBool(GroupAddress dst) throws KNXTimeoutException,
KNXRemoteException, KNXLinkClosedException, KNXFormatException
{
final byte[] apdu = readFromGroup(dst, priority, 0, 0);
final DPTXlatorBoolean t = new DPTXlatorBoolean(DPTXlatorBoolean.DPT_BOOL);
extractGroupASDU(apdu, t);
return t.getValueBoolean();
} | /* (non-Javadoc)
@see tuwien.auto.calimero.process.ProcessCommunicator#readBool
(tuwien.auto.calimero.GroupAddress) |
public void write(GroupAddress dst, boolean value) throws KNXTimeoutException,
KNXLinkClosedException
{
try {
final DPTXlatorBoolean t = new DPTXlatorBoolean(DPTXlatorBoolean.DPT_BOOL);
t.setValue(value);
write(dst, priority, t);
}
catch (final KNXFormatException ignore) {}
} | /* (non-Javadoc)
@see tuwien.auto.calimero.process.ProcessCommunicator#write
(tuwien.auto.calimero.GroupAddress, boolean) |
public short readUnsigned(GroupAddress dst, String scale)
throws KNXTimeoutException, KNXRemoteException, KNXLinkClosedException,
KNXFormatException
{
final byte[] apdu = readFromGroup(dst, priority, 1, 1);
final DPTXlator8BitUnsigned t = new DPTXlator8BitUnsigned(scale);
extractGroupASDU(apdu, t);
return t.getValueUnsigned();
} | /* (non-Javadoc)
@see tuwien.auto.calimero.process.ProcessCommunicator#readUnsigned
(tuwien.auto.calimero.GroupAddress, java.lang.String) |
public void write(GroupAddress dst, int value, String scale)
throws KNXTimeoutException, KNXFormatException, KNXLinkClosedException
{
final DPTXlator8BitUnsigned t = new DPTXlator8BitUnsigned(scale);
t.setValue(value);
write(dst, priority, t);
} | /* (non-Javadoc)
@see tuwien.auto.calimero.process.ProcessCommunicator#write
(tuwien.auto.calimero.GroupAddress, int, java.lang.String) |
public byte readControl(GroupAddress dst) throws KNXTimeoutException,
KNXRemoteException, KNXLinkClosedException, KNXFormatException
{
final byte[] apdu = readFromGroup(dst, priority, 0, 0);
final DPTXlator3BitControlled t =
new DPTXlator3BitControlled(DPTXlator3BitControlled.DPT_CONTROL_DIMMING);
extractGroupASDU(apdu, t);
return t.getValueSigned();
} | /* (non-Javadoc)
@see tuwien.auto.calimero.process.ProcessCommunicator#readControl
(tuwien.auto.calimero.GroupAddress) |
public void write(GroupAddress dst, boolean control, byte stepcode)
throws KNXTimeoutException, KNXFormatException, KNXLinkClosedException
{
final DPTXlator3BitControlled t =
new DPTXlator3BitControlled(DPTXlator3BitControlled.DPT_CONTROL_DIMMING);
t.setValue(control, stepcode);
write(dst, priority, t);
} | /* (non-Javadoc)
@see tuwien.auto.calimero.process.ProcessCommunicator#write
(tuwien.auto.calimero.GroupAddress, boolean, byte) |
public float readFloat(GroupAddress dst) throws KNXTimeoutException,
KNXRemoteException, KNXLinkClosedException, KNXFormatException
{
final byte[] apdu = readFromGroup(dst, priority, 2, 2);
final DPTXlator2ByteFloat t =
new DPTXlator2ByteFloat(DPTXlator2ByteFloat.DPT_TEMPERATURE_DIFFERENCE);
extractGroupASDU(apdu, t);
return t.getValueFloat();
} | /* (non-Javadoc)
@see tuwien.auto.calimero.process.ProcessCommunicator#readFloat
(tuwien.auto.calimero.GroupAddress) |
public void write(GroupAddress dst, float value) throws KNXTimeoutException,
KNXFormatException, KNXLinkClosedException
{
final DPTXlator2ByteFloat t =
new DPTXlator2ByteFloat(DPTXlator2ByteFloat.DPT_TEMPERATURE_DIFFERENCE);
t.setValue(value);
write(dst, priority, t);
} | /* (non-Javadoc)
@see tuwien.auto.calimero.process.ProcessCommunicator#write
(tuwien.auto.calimero.GroupAddress, float) |
public String readString(GroupAddress dst) throws KNXTimeoutException,
KNXRemoteException, KNXLinkClosedException, KNXFormatException
{
final byte[] apdu = readFromGroup(dst, priority, 0, 14);
final DPTXlatorString t = new DPTXlatorString(DPTXlatorString.DPT_STRING_8859_1);
extractGroupASDU(apdu, t);
return t.getValue();
} | /* (non-Javadoc)
@see tuwien.auto.calimero.process.ProcessCommunicator#readString
(tuwien.auto.calimero.GroupAddress) |
public void write(GroupAddress dst, String value) throws KNXTimeoutException,
KNXFormatException, KNXLinkClosedException
{
final DPTXlatorString t = new DPTXlatorString(DPTXlatorString.DPT_STRING_8859_1);
t.setValue(value);
write(dst, priority, t);
} | /* (non-Javadoc)
@see tuwien.auto.calimero.process.ProcessCommunicator#write
(tuwien.auto.calimero.GroupAddress, java.lang.String) |
public String read(Datapoint dp) throws KNXException
{
if (dp.getDPT() == null)
throw new KNXIllegalArgumentException("specify DPT for datapoint");
final byte[] apdu = readFromGroup(dp.getMainAddress(), dp.getPriority(), 0, 14);
final DPTXlator t =
TranslatorTypes.createTranslator(dp.getMainNumber(), dp.getDPT());
extractGroupASDU(apdu, t);
return t.getValue();
} | /* (non-Javadoc)
@see tuwien.auto.calimero.process.ProcessCommunicator#read
(tuwien.auto.calimero.datapoint.Datapoint) |
public void write(Datapoint dp, String value) throws KNXException
{
final DPTXlator t =
TranslatorTypes.createTranslator(dp.getMainNumber(), dp.getDPT());
t.setValue(value);
write(dp.getMainAddress(), dp.getPriority(), t);
} | /* (non-Javadoc)
@see tuwien.auto.calimero.process.ProcessCommunicator#write
(tuwien.auto.calimero.datapoint.Datapoint, java.lang.String) |
public KNXNetworkLink detach()
{
// if we synchronize on method we would take into account
// a worst case blocking of response timeout seconds
synchronized (lnkListener) {
// wait of response time seconds
if (detached)
return null;
detached = true;
}
lnk.removeLinkListener(lnkListener);
fireDetached();
logger.info("detached from " + lnk.getName());
LogManager.getManager().removeLogService(logger.getName());
return lnk;
} | /* (non-Javadoc)
@see tuwien.auto.calimero.process.ProcessCommunicator#detach() |
private static byte[] createGroupAPDU(int service, DPTXlator t)
{
// check for group read
if (service == 0x00)
return new byte[2];
// only group response and group write are allowed
if (service != 0x40 && service != 0x80)
throw new KNXIllegalArgumentException("not an APDU group service");
// determine if data starts at byte offset 1 (optimized) or 2 (default)
final int offset = (t.getItems() == 1 && t.getTypeSize() == 0) ? 1 : 2;
final byte[] buf = new byte[t.getItems() * Math.max(1, t.getTypeSize()) + offset];
buf[0] = (byte) (service >> 8);
buf[1] = (byte) service;
return t.getData(buf, offset);
} | Creates a group service application layer protocol data unit containing all
items of a DPT translator.
<p>
The transport layer bits in the first byte (TL / AL control field) are set 0. The
maximum length used for the ASDU is not checked.<br>
For DPTs occupying <= 6 bits in length the optimized (compact) group write /
response format layout is used.
@param service application layer group service code
@param t DPT translator with items to put into ASDU
@return group APDU as byte array |
private static void extractGroupASDU(byte[] apdu, DPTXlator t)
{
if (apdu.length < 2)
throw new KNXIllegalArgumentException("minimum APDU length is 2 bytes");
t.setData(apdu, apdu.length == 2 ? 1 : 2);
} | Extracts the service data unit of an application layer protocol data unit into a
DPT translator.
<p>
The whole service data unit is taken as data for translation. If the length of the
supplied <code>apdu</code> is 2, a compact group APDU format layout is assumed.<br>
On return of this method, the supplied translator contains the DPT items from the
ASDU.
@param apdu application layer protocol data unit, 2 <= apdu.length
@param t the DPT translator to fill with the ASDU |
public byte[] getData(byte[] dst, int offset)
{
final int end = Math.min(data.length, dst.length - offset) / 3 * 3;
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 Map getSubTypes()
{
return types;
}
/**
* @return the subtypes of the date translator type
* @see DPTXlator#getSubTypesStatic()
*/
protected static Map getSubTypesStatic()
{
return types;
}
private String fromDPT(int index)
{
if (sdf != null)
synchronized (DPTXlatorDate.class) {
try {
return sdf.format(new Date(fromDPTMillis(index)));
}
catch (final KNXFormatException e) {}
return "invalid date";
}
final int i = index * 3;
// return year-month-day
final int d = data[i + DAY];
final int m = data[i + MONTH];
return Short.toString(absYear(data[i + YEAR])) + '-' + align(m) + m + '-'
+ align(d) + d;
}
private long fromDPTMillis(int index) throws KNXFormatException
{
synchronized (DPTXlatorDate.class) {
getCalendar().clear();
final int i = index * 3;
c.set(Calendar.DAY_OF_MONTH, data[i + DAY]);
c.set(Calendar.MONTH, data[i + MONTH] - 1);
c.set(Calendar.YEAR, absYear(data[i + YEAR]));
try {
return c.getTimeInMillis();
}
catch (final IllegalArgumentException e) {
throw new KNXFormatException(e.getMessage());
}
}
}
protected void toDPT(String value, short[] dst, int index) throws KNXFormatException
{
if (sdf != null)
synchronized (DPTXlatorDate.class) {
toDPT(parse(value), dst, index);
return;
}
final StringTokenizer t = new StringTokenizer(value, "- ");
final int maxTokens = 3;
final int[] tokens = new int[maxTokens];
try {
int count = 0;
for (; count < maxTokens && t.hasMoreTokens(); ++count)
tokens[count] = Short.parseShort(t.nextToken());
if (count < 3)
throw logThrow(LogLevel.WARN, "invalid date " + value, null, value);
set(tokens[0], tokens[1], tokens[2], dst, index);
}
catch (final KNXIllegalArgumentException e) {
throw logThrow(LogLevel.WARN, "invalid date " + value, e.getMessage(), value);
}
catch (final NumberFormatException e) {
throw logThrow(LogLevel.WARN, "invalid number in " + value, null, value);
}
}
private short[] toDPT(long milliseconds, short[] dst, int index)
{
synchronized (DPTXlatorDate.class) {
getCalendar().clear();
c.setTimeInMillis(milliseconds);
set(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c
.get(Calendar.DAY_OF_MONTH), dst, index);
}
return dst;
}
private short[] set(int year, int month, int day, short[] dst, int index)
{
if (year < 1990 || year > 2089)
throw new KNXIllegalArgumentException("year out of range [1990..2089]");
if (month < 1 || month > 12)
throw new KNXIllegalArgumentException("month out of range [1..12]");
if (day < 1 || day > 31)
throw new KNXIllegalArgumentException("day out of range [1..31]");
final int i = 3 * index;
dst[i + DAY] = (short) day;
dst[i + MONTH] = (short) month;
dst[i + YEAR] = (short) (year % 100);
return dst;
}
private short absYear(int relative)
{
if (relative > 99)
throw new KNXIllegalArgumentException("relative year out of range [0..99]");
return (short) (relative + (relative < 90 ? 2000 : 1900));
}
private long parse(String value) throws KNXFormatException
{
try {
return sdf.parse(value).getTime();
}
catch (final ParseException e) {
throw logThrow(LogLevel.WARN, "invalid date format", e.getMessage(), value);
}
}
private static String align(int number)
{
return number > 9 ? "" : "0";
}
private static Calendar getCalendar()
{
// don't need to synchronize, it's harmless if we have 2 instances
// and we synchronize on class anyway
if (c == null) {
final Calendar calendar = Calendar.getInstance();
calendar.setLenient(false);
c = calendar;
}
return c;
}
} | /* (non-Javadoc)
@see tuwien.auto.calimero.dptxlator.DPTXlator#getData(byte[], int) |
public UPnPStateVariable getStateVariable(String argumentName) {
if (argumentName.equals("NewTime")) return time;
else if (argumentName.equals("Result")) return result;
else return null;
} | /* (non-Javadoc)
@see org.osgi.service.upnp.UPnPAction#getStateVariable(java.lang.String) |
public Dictionary invoke(Dictionary args) throws Exception {
Long newValue = (Long) args.get(NEW_TIME_VALUE);
Long oldValue = (Long) ((TimeStateVariable) time).getCurrentValue();
((TimeStateVariable) time).setCurrentTime(newValue.longValue());
ClockDevice.notifier.propertyChange(new PropertyChangeEvent(time,"Time",oldValue,newValue));
args.remove(NEW_TIME_VALUE);
args.put(NEW_RESULT_VALUE,((TimeStateVariable) time).getCurrentTime());
return args;
} | /* (non-Javadoc)
@see org.osgi.service.upnp.UPnPAction#invoke(java.util.Dictionary) |
byte[] toByteArray(ByteArrayOutputStream os)
{
os.write(CONN_HEADER_SIZE);
os.write(channelid);
os.write(seq);
os.write(0);
final byte[] buf = cemi.toByteArray();
os.write(buf, 0, buf.length);
return os.toByteArray();
} | /* (non-Javadoc)
@see tuwien.auto.calimero.knxnetip.servicetype.ServiceType#toByteArray
(java.io.ByteArrayOutputStream) |
public static CEMI createFromEMI(byte[] frame) throws KNXFormatException
{
// check for minimum frame length (i.e. busmonitor)
if (frame.length < 4)
throw new KNXFormatException("EMI frame too short");
final int mc = frame[0] & 0xff;
if (mc == CEMIBusMon.MC_BUSMON_IND) {
return new CEMIBusMon(frame[1] & 0xff, (frame[2] & 0xff) << 8 | frame[3] & 0xff,
false, truncate(frame, 4, frame.length - 4));
}
final Priority p = Priority.get(frame[1] >> 2 & 0x3);
final boolean ack = (frame[1] & 0x02) != 0;
final boolean c = (frame[1] & 0x01) != 0;
final int dst = (frame[4] & 0xff) << 8 | frame[5] & 0xff;
final KNXAddress a = (frame[6] & 0x80) != 0 ?
(KNXAddress) new GroupAddress(dst) : new IndividualAddress(dst);
final int hops = frame[6] >> 4 & 0x07;
final int len = (frame[6] & 0x0f) + 1;
final byte[] tpdu = truncate(frame, 7, Math.min(len, frame.length - 7));
// no long frames in EMI2
return c ? new CEMILData(mc, new IndividualAddress(0), a, tpdu, p, c)
: new CEMILData(mc, new IndividualAddress(0), a, tpdu, p, true, true, ack,
hops);
} | Creates a new cEMI message out of the supplied EMI frame.
<p>
@param frame EMI frame
@return the new cEMI message
@throws KNXFormatException if no (valid) EMI structure was found or unsupported EMI
message code |
private static CEMI create(int msgCode, IndividualAddress src, KNXAddress dst,
byte[] data, CEMILData original, boolean ext)
{
final int mc = msgCode != 0 ? msgCode : original.getMessageCode();
final IndividualAddress s = src != null ? src : original.getSource();
final KNXAddress d = dst != null ? dst : original.getDestination();
final byte[] content = data != null ? data : original.getPayload();
if (original instanceof CEMILDataEx) {
final CEMILDataEx f = (CEMILDataEx) original;
final CEMILDataEx copy =
new CEMILDataEx(mc, s, d, content, f.getPriority(), f.isRepetition(), f
.isDomainBroadcast(), f.isAckRequested(), f.getHopCount());
// copy additional info
final List l = f.getAdditionalInfo();
for (final Iterator i = l.iterator(); i.hasNext();) {
final CEMILDataEx.AddInfo info = (CEMILDataEx.AddInfo) i.next();
copy.addAdditionalInfo(info.getType(), info.getInfo());
}
return copy;
}
if (ext)
return new CEMILDataEx(mc, s, d, content, original.getPriority(), original
.isRepetition(), original.getHopCount());
return new CEMILData(mc, s, d, content, original.getPriority(), original
.isRepetition(), original.getHopCount());
} | leave msgcode/src/dst/data null/0 to use from original |
@Validate
public void startup(){
try {
logger.info("Starting Z-Wave controller");
connect(serialPortName);
this.watchdog = new Timer(true);
this.watchdog.schedule(
new WatchDogTimerTask(serialPortName),
WATCHDOG_TIMER_PERIOD, WATCHDOG_TIMER_PERIOD);
} catch (SerialInterfaceException e) {
e.printStackTrace();
logger.info("Failed starting Z-Wave controller");
}
} | Constructors |
private void handleIncomingMessage(SerialMessage incomingMessage) {
logger.debug("Incoming message to process");
logger.debug(incomingMessage.toString());
switch (incomingMessage.getMessageType()) {
case Request:
handleIncomingRequestMessage(incomingMessage);
break;
case Response:
handleIncomingResponseMessage(incomingMessage);
break;
default:
logger.warn("Unsupported incomingMessageType: 0x%02X", incomingMessage.getMessageType());
}
} | Handles incoming Serial Messages. Serial messages can either be messages
that are a response to our own requests, or the stick asking us information.
@param incomingMessage the incoming message to process. |
private void handleIncomingRequestMessage(SerialMessage incomingMessage) {
logger.debug("Message type = REQUEST");
switch (incomingMessage.getMessageClass()) {
case ApplicationCommandHandler:
handleApplicationCommandRequest(incomingMessage);
break;
case SendData:
handleSendDataRequest(incomingMessage);
break;
case ApplicationUpdate:
handleApplicationUpdateRequest(incomingMessage);
break;
default:
logger.warn(String.format("TODO: Implement processing of Request Message = %s (0x%02X)",
incomingMessage.getMessageClass().getLabel(),
incomingMessage.getMessageClass().getKey()));
break;
}
} | Handles an incoming request message.
An incoming request message is a message initiated by a node or the controller.
@param incomingMessage the incoming message to process. |
private void handleApplicationCommandRequest(SerialMessage incomingMessage) {
logger.trace("Handle Message Application Command Request");
int nodeId = incomingMessage.getMessagePayloadByte(1);
logger.debug("Application Command Request from Node " + nodeId);
ZWaveNode node = getNode(nodeId);
if (node == null) {
logger.warn("Node {} not initialized yet, ignoring message.", nodeId);
return;
}
node.resetResendCount();
int commandClassCode = incomingMessage.getMessagePayloadByte(3);
ZWaveCommandClass.CommandClass commandClass = ZWaveCommandClass.CommandClass.getCommandClass(commandClassCode);
if (commandClass == null) {
logger.error(String.format("Unsupported command class 0x%02x", commandClassCode));
return;
}
logger.debug(String.format("Incoming command class %s (0x%02x)", commandClass.getLabel(), commandClass.getKey()));
ZWaveCommandClass zwaveCommandClass = node.getCommandClass(commandClass);
// We got an unsupported command class, return.
if (zwaveCommandClass == null) {
logger.error(String.format("Unsupported command class %s (0x%02x)", commandClass.getLabel(), commandClassCode));
return;
}
logger.trace("Found Command Class {}, passing to handleApplicationCommandRequest", zwaveCommandClass.getCommandClass().getLabel());
zwaveCommandClass.handleApplicationCommandRequest(incomingMessage, 4, 1);
if (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && nodeId == this.lastSentMessage.getMessageNode() && !incomingMessage.isTransActionCanceled()) {
notifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));
transactionCompleted.release();
logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
}
} | Handles incoming Application Command Request.
@param incomingMessage the request message to process. |
private void handleSendDataRequest(SerialMessage incomingMessage) {
logger.trace("Handle Message Send Data Request");
int callbackId = incomingMessage.getMessagePayloadByte(0);
TransmissionState status = TransmissionState.getTransmissionState(incomingMessage.getMessagePayloadByte(1));
SerialMessage originalMessage = this.lastSentMessage;
if (status == null) {
logger.warn("Transmission state not found, ignoring.");
return;
}
logger.debug("CallBack ID = {}", callbackId);
logger.debug(String.format("Status = %s (0x%02x)", status.getLabel(), status.getKey()));
if (originalMessage == null || originalMessage.getCallbackId() != callbackId) {
logger.warn("Already processed another send data request for this callback Id, ignoring.");
return;
}
switch (status) {
case COMPLETE_OK:
ZWaveNode node = this.getNode(originalMessage.getMessageNode());
node.resetResendCount();
// in case we received a ping response and the node is alive, we proceed with the next node stage for this node.
if (node != null && node.getNodeStage() == NodeStage.NODEBUILDINFO_PING) {
node.advanceNodeStage();
}
if (incomingMessage.getMessageClass() == originalMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) {
notifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));
transactionCompleted.release();
logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
}
return;
case COMPLETE_NO_ACK:
case COMPLETE_FAIL:
case COMPLETE_NOT_IDLE:
case COMPLETE_NOROUTE:
try {
handleFailedSendDataRequest(originalMessage);
} finally {
transactionCompleted.release();
logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
}
default:
}
} | Handles incoming Send Data Request. Send Data request are used
to acknowledge or cancel failed messages.
@param incomingMessage the request message to process. |
private void handleFailedSendDataRequest(SerialMessage originalMessage) {
ZWaveNode node = this.getNode(originalMessage.getMessageNode());
if (node.getNodeStage() == NodeStage.NODEBUILDINFO_DEAD)
return;
if (!node.isListening() && originalMessage.getPriority() != SerialMessage.SerialMessagePriority.Low) {
ZWaveWakeUpCommandClass wakeUpCommandClass = (ZWaveWakeUpCommandClass)node.getCommandClass(ZWaveCommandClass.CommandClass.WAKE_UP);
if (wakeUpCommandClass != null) {
wakeUpCommandClass.setAwake(false);
wakeUpCommandClass.putInWakeUpQueue(originalMessage); //it's a battery operated device, place in wake-up queue.
return;
}
} else if (!node.isListening() && originalMessage.getPriority() == SerialMessage.SerialMessagePriority.Low)
return;
node.incrementResendCount();
logger.error("Got an error while sending data to node {}. Resending message.", node.getNodeId());
this.sendData(originalMessage);
} | Handles a failed SendData request. This can either be because of the stick actively reporting it
or because of a time-out of the transaction in the send thread.
@param originalMessage the original message that was sent |
private void handleApplicationUpdateRequest(SerialMessage incomingMessage) {
logger.trace("Handle Message Application Update Request");
int nodeId = incomingMessage.getMessagePayloadByte(1);
logger.trace("Application Update Request from Node " + nodeId);
UpdateState updateState = UpdateState.getUpdateState(incomingMessage.getMessagePayloadByte(0));
switch (updateState) {
case NODE_INFO_RECEIVED:
logger.debug("Application update request, node information received.");
int length = incomingMessage.getMessagePayloadByte(2);
ZWaveNode node = getNode(nodeId);
node.resetResendCount();
for (int i = 6; i < length + 3; i++) {
int data = incomingMessage.getMessagePayloadByte(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, node, this);
if (commandClass != null)
node.addCommandClass(commandClass);
}
// advance node stage.
node.advanceNodeStage();
if (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) {
notifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));
transactionCompleted.release();
logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
}
break;
case NODE_INFO_REQ_FAILED:
logger.debug("Application update request, Node Info Request Failed, re-request node info.");
SerialMessage requestInfoMessage = this.lastSentMessage;
if (requestInfoMessage.getMessageClass() != SerialMessage.SerialMessageClass.RequestNodeInfo) {
logger.warn("Got application update request without node info request, ignoring.");
return;
}
if (--requestInfoMessage.attempts >= 0) {
logger.error("Got Node Info Request Failed while sending this serial message. Requeueing");
this.enqueue(requestInfoMessage);
} else
{
logger.warn("Node Info Request Failed 3x. Discarding message: {}", lastSentMessage.toString());
}
transactionCompleted.release();
break;
default:
logger.warn(String.format("TODO: Implement Application Update Request Handling of %s (0x%02X).", updateState.getLabel(), updateState.getKey()));
}
} | Handles incoming Application Update Request.
@param incomingMessage the request message to process. |
private void handleIncomingResponseMessage(SerialMessage incomingMessage) {
logger.debug("Message type = RESPONSE");
switch (incomingMessage.getMessageClass()) {
case GetVersion:
handleGetVersionResponse(incomingMessage);
if (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) {
notifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));
transactionCompleted.release();
logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
}
break;
case MemoryGetId:
handleMemoryGetId(incomingMessage);
if (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) {
notifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));
transactionCompleted.release();
logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
}
break;
case SerialApiGetInitData:
handleSerialApiGetInitDataResponse(incomingMessage);
if (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) {
notifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));
transactionCompleted.release();
logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
}
break;
case IdentifyNode:
handleIdentifyNodeResponse(incomingMessage);
if (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) {
notifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));
transactionCompleted.release();
logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
}
break;
case RequestNodeInfo:
handleRequestNodeInfoResponse(incomingMessage);
break;
case SerialApiGetCapabilities:
handleSerialAPIGetCapabilitiesResponse(incomingMessage);
if (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) {
notifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));
transactionCompleted.release();
logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
}
break;
case SendData:
handleSendDataResponse(incomingMessage);
break;
default:
logger.warn(String.format("TODO: Implement processing of Response Message = %s (0x%02X)",
incomingMessage.getMessageClass().getLabel(),
incomingMessage.getMessageClass().getKey()));
break;
}
} | Handles an incoming response message.
An incoming response message is a response, based one of our own requests.
@param incomingMessage the response message to process. |
private void handleGetVersionResponse(SerialMessage incomingMessage) {
this.ZWaveLibraryType = incomingMessage.getMessagePayloadByte(12);
this.zWaveVersion = new String(ArrayUtils.subarray(incomingMessage.getMessagePayload(), 0, 11));
logger.debug(String.format("Got MessageGetVersion response. Version = %s, Library Type = 0x%02X", zWaveVersion, ZWaveLibraryType));
} | Handles the response of the getVersion request.
@param incomingMessage the response message to process. |
private void handleSerialApiGetInitDataResponse(
SerialMessage incomingMessage) {
logger.debug(String.format("Got MessageSerialApiGetInitData response."));
this.isConnected = true;
int nodeBytes = incomingMessage.getMessagePayloadByte(2);
if (nodeBytes != NODE_BYTES) {
logger.error("Invalid number of node bytes = {}", nodeBytes);
return;
}
int nodeId = 1;
// loop bytes
for (int i = 3;i < 3 + nodeBytes;i++) {
int incomingByte = incomingMessage.getMessagePayloadByte(i);
// loop bits in byte
for (int j=0;j<8;j++) {
int b1 = incomingByte & (int)Math.pow(2.0D, j);
int b2 = (int)Math.pow(2.0D, j);
if (b1 == b2) {
logger.info(String.format("Found node id = %d", nodeId));
// Place nodes in the local ZWave Controller
this.zwaveNodes.put(nodeId, new ZWaveNode(this.homeId, nodeId, this));
this.getNode(nodeId).advanceNodeStage();
}
nodeId++;
}
}
logger.info("------------Number of Nodes Found Registered to ZWave Controller------------");
logger.info(String.format("# Nodes = %d", this.zwaveNodes.size()));
logger.info("----------------------------------------------------------------------------");
// Advance node stage for the first node.
} | Handles the response of the SerialApiGetInitData request.
@param incomingMlivessage the response message to process. |
private void handleMemoryGetId(SerialMessage incomingMessage) {
this.homeId = ((incomingMessage.getMessagePayloadByte(0)) << 24) |
((incomingMessage.getMessagePayloadByte(1)) << 16) |
((incomingMessage.getMessagePayloadByte(2)) << 8) |
(incomingMessage.getMessagePayloadByte(3));
this.ownNodeId = incomingMessage.getMessagePayloadByte(4);
logger.debug(String.format("Got MessageMemoryGetId response. Home id = 0x%08X, Controller Node id = %d", this.homeId, this.ownNodeId));
} | Handles the response of the MemoryGetId request.
The MemoryGetId function gets the home and node id from the controller memory.
@param incomingMessage the response message to process. |
private void handleIdentifyNodeResponse(SerialMessage incomingMessage) {
logger.trace("Handle Message Get Node ProtocolInfo Response");
int nodeId = lastSentMessage.getMessagePayloadByte(0);
logger.debug("ProtocolInfo for Node = " + nodeId);
boolean listening = (incomingMessage.getMessagePayloadByte(0) & 0x80)!=0 ? true : false;
boolean routing = (incomingMessage.getMessagePayloadByte(0) & 0x40)!=0 ? true : false;
int version = (incomingMessage.getMessagePayloadByte(0) & 0x07) + 1;
logger.debug("Listening = " + listening);
logger.debug("Routing = " + routing);
logger.debug("Version = " + version);
this.zwaveNodes.get(nodeId).setListening(listening);
this.zwaveNodes.get(nodeId).setRouting(routing);
this.zwaveNodes.get(nodeId).setVersion(version);
ZWaveDeviceClass.Basic basic = ZWaveDeviceClass.Basic.getBasic(incomingMessage.getMessagePayloadByte(3));
if (basic == null) {
logger.error(String.format("Basic device class 0x%02x not found", incomingMessage.getMessagePayloadByte(3)));
return;
}
ZWaveDeviceClass.Generic generic = ZWaveDeviceClass.Generic.getGeneric(incomingMessage.getMessagePayloadByte(4));
if (generic == null) {
logger.error(String.format("Generic device class 0x%02x not found", incomingMessage.getMessagePayloadByte(4)));
return;
}
ZWaveDeviceClass.Specific specific = ZWaveDeviceClass.Specific.getSpecific(generic, incomingMessage.getMessagePayloadByte(5));
if (specific == null) {
logger.error(String.format("Specific device class 0x%02x not found", incomingMessage.getMessagePayloadByte(5)));
return;
}
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 = this.zwaveNodes.get(nodeId).getDeviceClass();
deviceClass.setBasicDeviceClass(basic);
deviceClass.setGenericDeviceClass(generic);
deviceClass.setSpecificDeviceClass(specific);
// Add mandatory command classes as specified by it's generic device class.
for (ZWaveCommandClass.CommandClass commandClass : generic.getMandatoryCommandClasses()) {
ZWaveCommandClass zwaveCommandClass = ZWaveCommandClass.getInstance(commandClass.getKey(), this.zwaveNodes.get(nodeId), this);
if (zwaveCommandClass != null)
this.zwaveNodes.get(nodeId).addCommandClass(zwaveCommandClass);
}
// Add mandatory command classes as specified by it's specific device class.
for (ZWaveCommandClass.CommandClass commandClass : specific.getMandatoryCommandClasses()) {
ZWaveCommandClass zwaveCommandClass = ZWaveCommandClass.getInstance(commandClass.getKey(), this.zwaveNodes.get(nodeId), this);
if (zwaveCommandClass != null)
this.zwaveNodes.get(nodeId).addCommandClass(zwaveCommandClass);
}
// Add the WAKE_UP command class to this node, since it's not listening.
if (!listening) {
ZWaveCommandClass zwaveCommandClass = ZWaveCommandClass.getInstance(ZWaveCommandClass.CommandClass.WAKE_UP.getKey(), this.zwaveNodes.get(nodeId), this);
if (zwaveCommandClass != null)
this.zwaveNodes.get(nodeId).addCommandClass(zwaveCommandClass);
}
// advance node stage of the current node.
this.getNode(nodeId).advanceNodeStage();
} | Handles the response of the IdentifyNode request.
@param incomingMessage the response message to process. |
private void handleSerialAPIGetCapabilitiesResponse(SerialMessage incomingMessage) {
logger.trace("Handle Message Serial API Get Capabilities");
this.serialAPIVersion = String.format("%d.%d", incomingMessage.getMessagePayloadByte(0), incomingMessage.getMessagePayloadByte(1));
this.manufactureId = ((incomingMessage.getMessagePayloadByte(2)) << 8) | (incomingMessage.getMessagePayloadByte(3));
this.deviceType = ((incomingMessage.getMessagePayloadByte(4)) << 8) | (incomingMessage.getMessagePayloadByte(5));
this.deviceId = (((incomingMessage.getMessagePayloadByte(6)) << 8) | (incomingMessage.getMessagePayloadByte(7)));
logger.debug(String.format("API Version = %s", this.getSerialAPIVersion()));
logger.debug(String.format("Manufacture ID = 0x%x", this.getManufactureId()));
logger.debug(String.format("Device Type = 0x%x", this.getDeviceType()));
logger.debug(String.format("Device ID = 0x%x", this.getDeviceId()));
// Ready to get information on Serial API
this.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.SerialApiGetInitData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.SerialApiGetInitData, SerialMessage.SerialMessagePriority.High));
} | Handles the response of the SerialAPIGetCapabilities request.
@param incomingMessage the response message to process. |
private void handleSendDataResponse(SerialMessage incomingMessage) {
logger.trace("Handle Message Send Data Response");
if(incomingMessage.getMessageBuffer()[2] != 0x00)
logger.debug("Sent Data successfully placed on stack.");
else
logger.error("Sent Data was not placed on stack due to error.");
} | Handles the response of the SendData request.
@param incomingMessage the response message to process. |
private void handleRequestNodeInfoResponse(SerialMessage incomingMessage) {
logger.trace("Handle RequestNodeInfo Response");
if(incomingMessage.getMessageBuffer()[2] != 0x00)
logger.debug("Request node info successfully placed on stack.");
else
logger.error("Request node info not placed on stack due to error.");
} | Handles the response of the Request node request.
@param incomingMessage the response message to process. |
public void connect(final String serialPortName)
throws SerialInterfaceException {
logger.info("Connecting to serial port {}", serialPortName);
try {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(serialPortName);
CommPort commPort = portIdentifier.open("org.openhab.binding.zwave",2000);
this.serialPort = (SerialPort) commPort;
this.serialPort.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
this.serialPort.enableReceiveThreshold(1);
this.serialPort.enableReceiveTimeout(ZWAVE_RECEIVE_TIMEOUT);
this.receiveThread = new ZWaveReceiveThread();
this.receiveThread.start();
this.sendThread = new ZWaveSendThread();
this.sendThread.start();
logger.info("Serial port is initialized");
} catch (NoSuchPortException e) {
logger.error(e.getLocalizedMessage());
throw new SerialInterfaceException(e.getLocalizedMessage(), e);
} catch (PortInUseException e) {
logger.error(e.getLocalizedMessage());
throw new SerialInterfaceException(e.getLocalizedMessage(), e);
} catch (UnsupportedCommOperationException e) {
logger.error(e.getLocalizedMessage());
throw new SerialInterfaceException(e.getLocalizedMessage(), e);
}
} | Connects to the comm port and starts send and receive threads.
@param serialPortName the port name to open
@throws SerialInterfaceException when a connection error occurs. |
public void close() {
if (watchdog != null) {
watchdog.cancel();
watchdog = null;
}
disconnect();
// clear nodes collection and send queue
for (Object listener : this.zwaveEventListeners.toArray()) {
if (!(listener instanceof ZWaveNode))
continue;
this.zwaveEventListeners.remove(listener);
}
this.zwaveNodes.clear();
this.sendQueue.clear();
logger.info("Stopped Z-Wave controller");
} | Closes the connection to the Z-Wave controller. |
public void disconnect() {
if (sendThread != null) {
sendThread.interrupt();
try {
sendThread.join();
} catch (InterruptedException e) {
}
sendThread = null;
}
if (receiveThread != null) {
receiveThread.interrupt();
try {
receiveThread.join();
} catch (InterruptedException e) {
}
receiveThread = null;
}
if(transactionCompleted.availablePermits() < 0)
transactionCompleted.release(transactionCompleted.availablePermits());
transactionCompleted.drainPermits();
logger.trace("Transaction completed permit count -> {}", transactionCompleted.availablePermits());
if (this.serialPort != null) {
this.serialPort.close();
this.serialPort = null;
}
logger.info("Disconnected from serial port");
} | Disconnects from the serial interface and stops
send and receive threads. |
public void enqueue(SerialMessage serialMessage) {
this.sendQueue.add(serialMessage);
logger.debug("Enqueueing message. Queue length = {}", this.sendQueue.size());
} | Enqueues a message for sending on the send thread.
@param serialMessage the serial message to enqueue. |
public void notifyEventListeners(ZWaveEvent event) {
logger.debug("Notifying event listeners");
for (ZWaveEventListener listener : this.zwaveEventListeners) {
logger.trace("Notifying {}", listener.toString());
listener.ZWaveIncomingEvent(event);
}
} | Notify our own event listeners of a Z-Wave event.
@param event the event to send. |
public void initialize() {
this.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.GetVersion, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.GetVersion, SerialMessage.SerialMessagePriority.High));
this.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.MemoryGetId, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.MemoryGetId, SerialMessage.SerialMessagePriority.High));
this.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.SerialApiGetCapabilities, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.SerialApiGetCapabilities, SerialMessage.SerialMessagePriority.High));
} | Initializes communication with the Z-Wave controller stick. |
public void identifyNode(int nodeId) throws SerialInterfaceException {
SerialMessage newMessage = new SerialMessage(nodeId, SerialMessage.SerialMessageClass.IdentifyNode, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.IdentifyNode, SerialMessage.SerialMessagePriority.High);
byte[] newPayload = { (byte) nodeId };
newMessage.setMessagePayload(newPayload);
this.enqueue(newMessage);
} | Send Identify Node message to the controller.
@param nodeId the nodeId of the node to identify
@throws SerialInterfaceException when timing out or getting an invalid response. |
public void requestNodeInfo(int nodeId) {
SerialMessage newMessage = new SerialMessage(nodeId, SerialMessage.SerialMessageClass.RequestNodeInfo, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.ApplicationUpdate, SerialMessage.SerialMessagePriority.High);
byte[] newPayload = { (byte) nodeId };
newMessage.setMessagePayload(newPayload);
this.enqueue(newMessage);
} | Send Request Node info message to the controller.
@param nodeId the nodeId of the node to identify
@throws SerialInterfaceException when timing out or getting an invalid response. |
public void checkForDeadOrSleepingNodes(){
int completeCount = 0;
if (zwaveNodes.isEmpty())
return;
// There are still nodes waiting to get a ping.
// So skip the dead node checking.
for (SerialMessage serialMessage : sendQueue) {
if (serialMessage.getPriority() == SerialMessage.SerialMessagePriority.Low)
return;
}
logger.trace("Checking for Dead or Sleeping Nodes.");
for (Map.Entry<Integer, ZWaveNode> entry : zwaveNodes.entrySet()){
if (entry.getValue().getNodeStage() == ZWaveNode.NodeStage.NODEBUILDINFO_EMPTYNODE)
continue;
logger.debug(String.format("Node %d has been in Stage %s since %s", entry.getKey(), entry.getValue().getNodeStage().getLabel(), entry.getValue().getQueryStageTimeStamp().toString()));
if(entry.getValue().getNodeStage() == ZWaveNode.NodeStage.NODEBUILDINFO_DONE || !entry.getValue().isListening()) {
completeCount++;
continue;
}
logger.trace("Checking if {} miliseconds have passed in current stage.", QUERY_STAGE_TIMEOUT);
if(Calendar.getInstance().getTimeInMillis() < (entry.getValue().getQueryStageTimeStamp().getTime() + QUERY_STAGE_TIMEOUT))
continue;
logger.warn(String.format("Node %d may be dead, setting stage to DEAD.", entry.getKey()));
entry.getValue().setNodeStage(ZWaveNode.NodeStage.NODEBUILDINFO_DEAD);
completeCount++;
}
if(this.zwaveNodes.size() == completeCount){
ZWaveEvent zEvent = new ZWaveEvent(ZWaveEventType.NETWORK_EVENT, 1, 0, "INIT_DONE");
this.notifyEventListeners(zEvent);
}
} | Checks for dead or sleeping nodes during Node initialization.
JwS: merged checkInitComplete and checkForDeadOrSleepingNodes to prevent possibly looping nodes multiple times. |
public void requestValue(int nodeId, int endpoint) {
ZWaveNode node = this.getNode(nodeId);
ZWaveGetCommands zwaveCommandClass = null;
SerialMessage serialMessage = null;
for (ZWaveCommandClass.CommandClass commandClass : new ZWaveCommandClass.CommandClass[] { ZWaveCommandClass.CommandClass.SENSOR_BINARY, ZWaveCommandClass.CommandClass.SENSOR_ALARM, ZWaveCommandClass.CommandClass.SENSOR_MULTILEVEL, ZWaveCommandClass.CommandClass.SWITCH_MULTILEVEL, ZWaveCommandClass.CommandClass.SWITCH_BINARY, ZWaveCommandClass.CommandClass.BASIC }) {
zwaveCommandClass = (ZWaveGetCommands)node.resolveCommandClass(commandClass, endpoint);
if (zwaveCommandClass != null)
break;
}
if (zwaveCommandClass == null) {
logger.error("No Command Class found on node {}, instance/endpoint {} to request value.", nodeId, endpoint);
return;
}
serialMessage = node.encapsulate(zwaveCommandClass.getValueMessage(), (ZWaveCommandClass)zwaveCommandClass, endpoint);
if (serialMessage != null)
this.sendData(serialMessage);
} | Request value from the node / endpoint;
@param nodeId the node id to request the value for.
@param endpoint the endpoint to request the value for. |
public void requestBatteryLevel(int nodeId, int endpoint) {
ZWaveNode node = this.getNode(nodeId);
SerialMessage serialMessage = null;
ZWaveBatteryCommandClass zwaveBatteryCommandClass = (ZWaveBatteryCommandClass)node.resolveCommandClass(ZWaveCommandClass.CommandClass.BATTERY, endpoint);
if (zwaveBatteryCommandClass == null) {
logger.error("No Command Class BATTERY found on node {}, instance/endpoint {} to request value.", nodeId, endpoint);
return;
}
serialMessage = node.encapsulate(zwaveBatteryCommandClass.getValueMessage(), zwaveBatteryCommandClass, endpoint);
if (serialMessage != null)
this.sendData(serialMessage);
} | Request the battery level from the node / endpoint;
@param nodeId the node id to request the battery level for.
@param endpoint the endpoint to request the battery level for. |
public void increaseLevel(int nodeId, int endpoint) {
ZWaveNode node = this.getNode(nodeId);
SerialMessage serialMessage = null;
ZWaveMultiLevelSwitchCommandClass zwaveCommandClass = (ZWaveMultiLevelSwitchCommandClass)node.resolveCommandClass(ZWaveCommandClass.CommandClass.SWITCH_MULTILEVEL, endpoint);
if (zwaveCommandClass == null) {
logger.error("No Command Class found on node {}, instance/endpoint {} to request level.", nodeId, endpoint);
return;
}
serialMessage = node.encapsulate(zwaveCommandClass.increaseLevelMessage(), zwaveCommandClass, endpoint);
if (serialMessage != null)
{
this.sendData(serialMessage);
ZWaveEvent zEvent = new ZWaveEvent(ZWaveEventType.DIMMER_EVENT, nodeId, endpoint, zwaveCommandClass.getLevel());
this.notifyEventListeners(zEvent);
}
} | increase level on the node / endpoint. The level is
increased. Only dimmers support this.
@param nodeId the node id to increase the level for.
@param endpoint the endpoint to increase the level for. |
public void sendData(SerialMessage serialMessage)
{
if (serialMessage.getMessageClass() != SerialMessage.SerialMessageClass.SendData) {
logger.error(String.format("Invalid message class %s (0x%02X) for sendData", serialMessage.getMessageClass().getLabel(), serialMessage.getMessageClass().getKey()));
return;
}
if (serialMessage.getMessageType() != SerialMessage.SerialMessageType.Request) {
logger.error("Only request messages can be sent");
return;
}
ZWaveNode node = this.getNode(serialMessage.getMessageNode());
if (node.getNodeStage() == NodeStage.NODEBUILDINFO_DEAD) {
logger.debug("Node {} is dead, not sending message.", node.getNodeId());
return;
}
if (!node.isListening() && serialMessage.getPriority() != SerialMessage.SerialMessagePriority.Low) {
ZWaveWakeUpCommandClass wakeUpCommandClass = (ZWaveWakeUpCommandClass)node.getCommandClass(ZWaveCommandClass.CommandClass.WAKE_UP);
if (wakeUpCommandClass != null && !wakeUpCommandClass.isAwake()) {
wakeUpCommandClass.putInWakeUpQueue(serialMessage); //it's a battery operated device, place in wake-up queue.
return;
}
}
serialMessage.setTransmitOptions(TRANSMIT_OPTION_ACK | TRANSMIT_OPTION_AUTO_ROUTE | TRANSMIT_OPTION_EXPLORE);
if (++sentDataPointer > 0xFF)
sentDataPointer = 1;
serialMessage.setCallbackId(sentDataPointer);
logger.debug("Callback ID = {}", sentDataPointer);
this.enqueue(serialMessage);
} | Transmits the SerialMessage to a single Z-Wave Node.
Sets the transmission options as well.
@param serialMessage the Serial message to send. |
public void sendValue(int nodeId, int endpoint, int value) {
ZWaveNode node = this.getNode(nodeId);
ZWaveSetCommands zwaveCommandClass = null;
SerialMessage serialMessage = null;
for (ZWaveCommandClass.CommandClass commandClass : new ZWaveCommandClass.CommandClass[] { ZWaveCommandClass.CommandClass.SWITCH_MULTILEVEL, ZWaveCommandClass.CommandClass.SWITCH_BINARY, ZWaveCommandClass.CommandClass.BASIC }) {
zwaveCommandClass = (ZWaveSetCommands)node.resolveCommandClass(commandClass, endpoint);
if (zwaveCommandClass != null)
break;
}
if (zwaveCommandClass == null) {
logger.error("No Command Class found on node {}, instance/endpoint {} to request level.", nodeId, endpoint);
return;
}
serialMessage = node.encapsulate(zwaveCommandClass.setValueMessage(value), (ZWaveCommandClass)zwaveCommandClass, endpoint);
if (serialMessage != null)
this.sendData(serialMessage);
// read back level on "ON" command
if (((ZWaveCommandClass)zwaveCommandClass).getCommandClass() == ZWaveCommandClass.CommandClass.SWITCH_MULTILEVEL && value == 255)
this.requestValue(nodeId, endpoint);
} | Send value to node.
@param nodeId the node Id to send the value to.
@param endpoint the endpoint to send the value to.
@param value the value to send |
public boolean asBool(ProcessEvent e) throws KNXFormatException
{
final DPTXlatorBoolean t = new DPTXlatorBoolean(DPTXlatorBoolean.DPT_BOOL);
t.setData(e.getASDU());
return t.getValueBoolean();
} | Returns the ASDU of the received process event as boolean datapoint value.
<p>
This method has to be invoked manually by the user (either in
{@link #groupReadResponse(ProcessEvent)} or
{@link ProcessListener#groupWrite(ProcessEvent)}), depending on the received
datapoint type.
@param e the process event with the ASDU to translate
@return the received value of type boolean
@throws KNXFormatException on not supported or not available boolean DPT |
public short asUnsigned(ProcessEvent e, String scale) throws KNXFormatException
{
final DPTXlator8BitUnsigned t = new DPTXlator8BitUnsigned(scale);
t.setData(e.getASDU());
return t.getValueUnsigned();
} | Returns the ASDU of the received process event as unsigned 8 Bit datapoint value.
<p>
This method has to be invoked manually by the user (either in
{@link #groupReadResponse(ProcessEvent)} or
{@link ProcessListener#groupWrite(ProcessEvent)}), depending on the received
datapoint type.
@param e the process event with the ASDU to translate
@param scale see {@link ProcessCommunicator#readUnsigned(
tuwien.auto.calimero.GroupAddress, String)}
@return the received value of type 8 Bit unsigned
@throws KNXFormatException on not supported or not available 8 Bit unsigned DPT |
public byte asControl(ProcessEvent e) throws KNXFormatException
{
final DPTXlator3BitControlled t = new DPTXlator3BitControlled(
DPTXlator3BitControlled.DPT_CONTROL_DIMMING);
t.setData(e.getASDU());
return t.getValueSigned();
} | Returns the ASDU of the received process event as 3 Bit controlled datapoint value.
<p>
This method has to be invoked manually by the user (either in
{@link #groupReadResponse(ProcessEvent)} or
{@link ProcessListener#groupWrite(ProcessEvent)}), depending on the received
datapoint type.
@param e the process event with the ASDU to translate
@return the received value of type 3 Bit controlled
@throws KNXFormatException on not supported or not available 3 Bit controlled DPT |
public float asFloat(ProcessEvent e) throws KNXFormatException
{
final DPTXlator2ByteFloat t = new DPTXlator2ByteFloat(
DPTXlator2ByteFloat.DPT_TEMPERATURE_DIFFERENCE);
t.setData(e.getASDU());
return t.getValueFloat();
} | Returns the ASDU of the received process event as 2 byte KNX float datapoint value.
<p>
This method has to be invoked manually by the user (either in
{@link #groupReadResponse(ProcessEvent)} or
{@link ProcessListener#groupWrite(ProcessEvent)}), depending on the received
datapoint type.
@param e the process event with the ASDU to translate
@return the received value of type float
@throws KNXFormatException on not supported or not available float DPT |
public String asString(ProcessEvent e) throws KNXFormatException
{
final DPTXlatorString t = new DPTXlatorString(DPTXlatorString.DPT_STRING_8859_1);
t.setData(e.getASDU());
return t.getValue();
} | Returns the ASDU of the received process event as string datapoint value.
<p>
The used character set is ISO-8859-1 (Latin 1), with an allowed string length of 14
characters.
<p>
This method has to be invoked manually by the user (either in
{@link #groupReadResponse(ProcessEvent)} or
{@link ProcessListener#groupWrite(ProcessEvent)}), depending on the received
datapoint type.
@param e the process event with the ASDU to translate
@return the received value of type String
@throws KNXFormatException on not supported or not available ISO-8859-1 DPT |
public String asString(ProcessEvent e, int dptMainNumber, String dptID)
throws KNXException
{
final DPTXlator t = TranslatorTypes.createTranslator(dptMainNumber, dptID);
t.setData(e.getASDU());
return t.getValue();
} | Returns the ASDU of the received process event as datapoint value of the requested
DPT in String representation.
<p>
This method has to be invoked manually by the user (either in
{@link #groupReadResponse(ProcessEvent)} or
{@link ProcessListener#groupWrite(ProcessEvent)}), depending on the received
datapoint type.
@param e the process event with the ASDU to translate
@param dptMainNumber datapoint type main number, number >= 0; use 0 to infer
translator type from <code>dptID</code> argument only
@param dptID datapoint type ID for selecting a particular kind of value translation
@return the received value of the requested type as String representation
@throws KNXException on not supported or not available DPT
@see TranslatorTypes#createTranslator(int, String) |
public final static String toClockString(int value)
{
if (value < 10)
return "0" + Integer.toString(value);
return Integer.toString(value);
} | ////////////////////////////////////////////// |
public String getTimeString()
{
Calendar cal = getCalendar();
return
toClockString(cal.get(Calendar.HOUR)) +
(((cal.get(Calendar.SECOND) % 2) == 0) ? ":" : " ") +
toClockString(cal.get(Calendar.MINUTE));
} | ////////////////////////////////////////////// |
private void processProperties() {
state = true;
try {
importerServiceFilter = getFilter(importerServiceFilterProperty);
} catch (InvalidFilterException invalidFilterException) {
LOG.debug("The value of the Property " + FILTER_IMPORTERSERVICE_PROPERTY + " is invalid,"
+ " the recuperation of the Filter has failed. The instance gonna stop.", invalidFilterException);
state = false;
return;
}
try {
importDeclarationFilter = getFilter(importDeclarationFilterProperty);
} catch (InvalidFilterException invalidFilterException) {
LOG.debug("The value of the Property " + FILTER_IMPORTDECLARATION_PROPERTY + " is invalid,"
+ " the recuperation of the Filter has failed. The instance gonna stop.", invalidFilterException);
state = false;
return;
}
} | Get the filters ImporterServiceFilter and ImportDeclarationFilter from the properties, stop the instance if one of.
them is invalid. |
@Updated
public void updated() {
processProperties();
synchronized (lock) {
importersManager.applyFilterChanges(importerServiceFilter);
declarationsManager.applyFilterChanges(importDeclarationFilter);
}
} | Called by iPOJO when the configuration of the DefaultImportationLinker is updated.
<p/>
Call #processProperties() to get the updated filters ImporterServiceFilter and ImportDeclarationFilter.
Compute and apply the changes in the links relatives to the changes in the filters. |
@Bind(id = "importerServices", specification = ImporterService.class, aggregate = true, optional = true)
void bindImporterService(ServiceReference<ImporterService> serviceReference) {
synchronized (lock) {
try {
importersManager.add(serviceReference);
} catch (InvalidFilterException invalidFilterException) {
LOG.error("The ServiceProperty \"" + TARGET_FILTER_PROPERTY + "\" of the ImporterService "
+ bundleContext.getService(serviceReference) + " doesn't provides a valid Filter."
+ " To be used, it must provides a correct \"" + TARGET_FILTER_PROPERTY + "\" ServiceProperty.",
invalidFilterException
);
return;
}
if (!importersManager.matched(serviceReference)) {
return;
}
LOG.debug(linkerName + " : Bind the ImporterService "
+ importersManager.getDeclarationBinder(serviceReference)
+ " with filter " + importersManager.getTargetFilter(serviceReference));
importersManager.createLinks(serviceReference);
}
} | Bind the {@link ImporterService} matching the importerServiceFilter.
<p/>
Check all the already bound {@link ImportDeclaration}s, if the metadata of the ImportDeclaration match the filter
exposed by the ImporterService, link them together. |
@Modified(id = "importerServices")
void modifiedImporterService(ServiceReference<ImporterService> serviceReference) {
try {
importersManager.modified(serviceReference);
} catch (InvalidFilterException invalidFilterException) {
LOG.error("The ServiceProperty \"" + TARGET_FILTER_PROPERTY + "\" of the ImporterService "
+ bundleContext.getService(serviceReference) + " doesn't provides a valid Filter."
+ " To be used, it must provides a correct \"" + TARGET_FILTER_PROPERTY + "\" ServiceProperty.",
invalidFilterException
);
importersManager.removeLinks(serviceReference);
return;
}
if (importersManager.matched(serviceReference)) {
importersManager.updateLinks(serviceReference);
} else {
importersManager.removeLinks(serviceReference);
}
} | Update the Target Filter of the ImporterService.
Apply the induce modifications on the links of the ImporterService
@param serviceReference |
@Unbind(id = "importerServices")
void unbindImporterService(ServiceReference<ImporterService> serviceReference) {
LOG.debug(linkerName + " : Unbind the ImporterService " + importersManager.getDeclarationBinder(serviceReference));
synchronized (lock) {
importersManager.removeLinks(serviceReference);
importersManager.remove(serviceReference);
}
} | Unbind the {@link ImporterService}. |
@Bind(id = "importDeclarations", specification = ImportDeclaration.class, aggregate = true, optional = true)
void bindImportDeclaration(ServiceReference<ImportDeclaration> importDeclarationSRef) {
synchronized (lock) {
declarationsManager.add(importDeclarationSRef);
if (!declarationsManager.matched(importDeclarationSRef)) {
LOG.debug("No service matching was found, ignoring service reference.");
return;
}
LOG.debug(linkerName + " : Bind the ImportDeclaration "
+ declarationsManager.getDeclaration(importDeclarationSRef));
declarationsManager.createLinks(importDeclarationSRef);
}
} | Bind the {@link ImportDeclaration} matching the filter ImportDeclarationFilter.
<p/>
Check if metadata of the ImportDeclaration match the filter exposed by the {@link ImporterService}s bound.
If the ImportDeclaration matches the ImporterService filter, link them together. |
@Modified(id = "importDeclarations")
void modifiedImportDeclaration(ServiceReference<ImportDeclaration> importDeclarationSRef) {
LOG.debug(linkerName + " : Modify the ImportDeclaration "
+ declarationsManager.getDeclaration(importDeclarationSRef));
synchronized (lock) {
declarationsManager.removeLinks(importDeclarationSRef);
declarationsManager.modified(importDeclarationSRef);
if (!declarationsManager.matched(importDeclarationSRef)) {
return;
}
declarationsManager.createLinks(importDeclarationSRef);
}
} | Unbind and bind the {@link ImportDeclaration}. |
@Unbind(id = "importDeclarations")
void unbindImportDeclaration(ServiceReference<ImportDeclaration> importDeclarationSRef) {
try {
if (!declarationsManager.matched(importDeclarationSRef)) {
LOG.debug("Declaration {} do not match service, skipping",declarationsManager.getDeclaration(importDeclarationSRef));
return;
}
LOG.debug(linkerName + " : Unbind the ImportDeclaration "
+ declarationsManager.getDeclaration(importDeclarationSRef));
synchronized (lock) {
declarationsManager.removeLinks(importDeclarationSRef);
declarationsManager.remove(importDeclarationSRef);
}
} catch(Exception e){
LOG.error("Failed to unbind declaration",e);
}
} | Unbind the {@link ImportDeclaration}. |
@Nonnull
private static GenericDeclaration createGenericDeclaration(@Nonnull final String declaration) {
Check.notNull(declaration, "declaration");
return declaration.isEmpty() ? GenericDeclaration.UNDEFINED : GenericDeclaration.of(declaration);
} | Creates a new instance of {@code GenericDeclaration} when the given declaration is not empty other wise it
returns {@link GenericDeclaration#UNDEFINED}.
@param declaration
declaration of a generic
@return instance of {@code GenericDeclaration} and never null |
@Nonnull
private static Package createPackage(@Nonnull final String packageName) {
Check.notNull(packageName, "packageName");
return packageName.isEmpty() ? Package.UNDEFINED : new Package(packageName);
} | Creates a new instance of {@code Package} when the given name is not empty other wise it returns
{@link Package#UNDEFINED}.
@param packageName
package name
@return instance of {@code Package} and never null |
@Nullable
public static Type evaluateJavaLangType(@Nonnull final String name) {
Check.notEmpty(name, "name");
Type ret = null;
for (final Type type : JAVA_LANG_VALUE_TYPES) {
if (type.getName().equals(name.replace("java.lang.", ""))) {
ret = type;
break;
}
}
return ret;
} | Checks if the passed type is a type of <code>java.lang</code>. If it is a type of <code>java.lang</code> the
matching type will be returned otherwise {@code null}.
@param name
simple or qualified name of a type
@return matching type or {@code null} |
public static void main(String[] args)
{
try {
final ProcComm pc = new ProcComm(args, null);
// use a log writer for the console (System.out), setting the user
// specified log level, if any
pc.w = new ConsoleWriter(pc.options.containsKey("verbose"));
if (pc.options.containsKey("read") == pc.options.containsKey("write"))
throw new IllegalArgumentException("do either read or write");
try {
pc.run(null);
pc.readWrite();
}
finally {
pc.quit();
}
}
catch (final Throwable t) {
if (t.getMessage() != null)
System.out.println(t.getMessage());
}
} | Entry point for running ProcComm.
<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 the
communication connection:
<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>-routing</code> use KNXnet/IP routing</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>
Available commands for process communication:
<ul>
<li><code>read</code> <i>DPT KNX-address</i> read from group
address, using DPT value format</li>
<li><code>write</code> <i>DPT value KNX-address</i> write
to group address, using DPT value format</li>
</ul>
For the more common datapoint types (DPTs) the following name aliases can be used
instead of the general DPT number string:
<ul>
<li><code>switch</code> for DPT 1.001</li>
<li><code>bool</code> for DPT 1.002</li>
<li><code>string</code> for DPT 16.001</li>
<li><code>float</code> for DPT 9.002</li>
<li><code>ucount</code> for DPT 5.010</li>
<li><code>angle</code> for DPT 5.003</li>
</ul>
@param args command line options for process communication |
public void run(ProcessListener l) throws KNXException
{
// create the network link to the KNX network
final KNXNetworkLink lnk = createLink();
LogManager.getManager().addWriter(lnk.getName(), w);
// create process communicator with the established link
pc = new ProcessCommunicatorImpl(lnk);
if (l != null)
pc.addProcessListener(l);
registerShutdownHandler();
// user might specify a response timeout for KNX message
// answers from the KNX network
if (options.containsKey("timeout"))
pc.setResponseTimeout(((Integer) options.get("timeout")).intValue());
} | Runs the process communicator.
<p>
This method immediately returns when the process communicator is running. Call
{@link #quit()} to quit process communication.
@param l a process event listener, can be <code>null</code>
@throws KNXException on problems creating network link or communication |
public void quit()
{
if (pc != null) {
final KNXNetworkLink lnk = pc.detach();
if (lnk != null)
lnk.close();
Runtime.getRuntime().removeShutdownHook(sh);
}
} | Quits process communication.
<p>
Detaches the network link from the process communicator and closes the link. |
private KNXNetworkLink createLink() 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 {
return new KNXNetworkLinkFT12(Integer.parseInt(p), medium);
}
catch (final NumberFormatException e) {
return new KNXNetworkLinkFT12(p, medium);
}
}
// create local and remote socket address for network 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());
final int mode = options.containsKey("routing") ? KNXNetworkLinkIP.ROUTER
: KNXNetworkLinkIP.TUNNEL;
return new KNXNetworkLinkIP(mode, local, host, options.containsKey("nat"),
medium);
} | Creates the KNX network link to access the network specified in
<code>options</code>.
<p>
@return the KNX network link
@throws KNXException on problems on link creation |
private String getDPT()
{
final String dpt = (String) options.get("dpt");
if (dpt.equals("switch"))
return "1.001";
if (dpt.equals("bool"))
return "1.002";
if (dpt.equals("string"))
return "16.001";
if (dpt.equals("float"))
return "9.002";
if (dpt.equals("ucount"))
return "5.010";
if (dpt.equals("angle"))
return "5.003";
return dpt;
} | Gets the datapoint type identifier from the <code>options</code>, and maps alias
names of common datapoint types to its datapoint type ID.
<p>
The option map must contain a "dpt" key with value.
@return datapoint type identifier |
private static KNXMediumSettings getMedium(String id)
{
if (id.equals("tp0"))
return TPSettings.TP0;
else if (id.equals("tp1"))
return TPSettings.TP1;
else if (id.equals("p110"))
return new PLSettings(false);
else if (id.equals("p132"))
return new PLSettings(true);
else if (id.equals("rf"))
return new RFSettings(null);
else
throw new KNXIllegalArgumentException("unknown medium");
} | Creates a medium settings type for the supplied medium identifier.
<p>
@param id a medium identifier from command line option
@return medium settings object
@throws KNXIllegalArgumentException on unknown medium identifier |
public synchronized void error(LogWriter source, String msg, Exception e)
{
if (invocations >= maxInvocations)
return;
++invocations;
String out = source + ": " + msg;
StackTraceElement[] trace = null;
if (e != null) {
out += " (" + e.getMessage() + ")";
trace = e.getStackTrace();
}
synchronized (System.err) {
System.err.println(out);
final String srcName = source.getClass().getName();
if (trace != null)
for (int i = 0; i < trace.length; ++i) {
System.err.println("\t- " + trace[i]);
if (trace[i].getClassName().equals(srcName))
break;
}
}
} | Invoked on a log writer error event.
<p>
The default behavior used here prints the logging source and the error message to
the system standard error stream (System.err). If an exception object is given, the
exception and the last method calls of the log writer leading to the error are also
printed.<br>
Only predefined maximum invocations are handled, subsequent calls are ignored.
@param source the log writer the error originated from
@param msg message describing the error
@param e exception related to the error, may be <code>null</code> |
public static ZWaveCommandClass getInstance(int i, ZWaveNode node, ZWaveController controller) {
return ZWaveCommandClass.getInstance(i, node, controller, null);
} | Gets an instance of the right command class.
Returns null if the command class is not found.
@param i the code to instantiate
@param node the node this instance commands.
@param controller the controller to send messages to.
@return the ZWaveCommandClass instance that was instantiated, null otherwise |
public static ZWaveCommandClass getInstance(int i, ZWaveNode node, ZWaveController controller, ZWaveEndpoint endpoint) {
logger.debug(String.format("Creating new instance of command class 0x%02X", i));
try {
CommandClass commandClass = CommandClass.getCommandClass(i);
if (commandClass == null) {
logger.warn(String.format("Unsupported command class 0x%02x", i));
return null;
}
Class<? extends ZWaveCommandClass> commandClassClass = commandClass.getCommandClassClass();
if (commandClassClass == null) {
logger.warn(String.format("Unsupported command class %s (0x%02x)", commandClass.getLabel(), i, endpoint));
return null;
}
Constructor<? extends ZWaveCommandClass> constructor = commandClassClass.getConstructor(ZWaveNode.class, ZWaveController.class, ZWaveEndpoint.class);
return constructor.newInstance(new Object[] {node, controller, endpoint});
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
} catch (IllegalArgumentException e) {
} catch (InvocationTargetException e) {
} catch (NoSuchMethodException e) {
} catch (SecurityException e) {
}
logger.error(String.format("Error instantiating command class 0x%02x", i));
return null;
} | Gets an instance of the right command class.
Returns null if the command class is not found.
@param i the code to instantiate
@param node the node this instance commands.
@param controller the controller to send messages to.
@param endpoint the endpoint this Command class belongs to
@return the ZWaveCommandClass instance that was instantiated, null otherwise |
private void unregisterAllServlets() {
for (String endpoint : registeredServlets) {
registeredServlets.remove(endpoint);
web.unregister(endpoint);
LOG.info("endpoint {} unregistered", endpoint);
}
} | Unregister all servlets registered by this exporter. |
public double[] calculateDrift(ArrayList<T> tracks){
double[] result = new double[3];
double sumX =0;
double sumY = 0;
double sumZ = 0;
int N=0;
for(int i = 0; i < tracks.size(); i++){
T t = tracks.get(i);
TrajectoryValidIndexTimelagIterator it = new TrajectoryValidIndexTimelagIterator(t,1);
//for(int j = 1; j < t.size(); j++){
while(it.hasNext()) {
int j = it.next();
sumX += t.get(j+1).x - t.get(j).x;
sumY += t.get(j+1).y - t.get(j).y;
sumZ += t.get(j+1).z - t.get(j).z;
N++;
}
}
result[0] = sumX/N;
result[1] = sumY/N;
result[2] = sumZ/N;
return result;
} | Calculates the static drift. Static means, that the drift does not change direction or intensity over time.
@param tracks Tracks which seems to exhibit a local drift
@return The static drift over all trajectories |
private static String determineMessage(@Nullable final String className) {
return className != null && !className.isEmpty() ? format(className) : 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 className
the name of the passed {@link Class}
@return {@code DEFAULT_MESSAGE} if the given argument name is {@code null} or empty, otherwise a formatted
{@code MESSAGE_WITH_NAME} |
public void addCommandClass(ZWaveCommandClass commandClass) {
ZWaveCommandClass.CommandClass key = commandClass.getCommandClass();
if (!supportedCommandClasses.containsKey(key)) {
supportedCommandClasses.put(key, commandClass);
}
} | Adds a command class to the list of supported command classes by this
endpoint. Does nothing if command class is already added.
@param commandClass the command class instance to add. |
public boolean canBeLinked(D declaration, ServiceReference<S> declarationBinderRef) {
// Evaluate the target filter of the ImporterService on the Declaration
Filter filter = bindersManager.getTargetFilter(declarationBinderRef);
return filter.matches(declaration.getMetadata());
} | Return true if the Declaration can be linked to the ImporterService.
@param declaration The Declaration
@param declarationBinderRef The ServiceReference<ImporterService> of the ImporterService
@return true if the Declaration can be linked to the ImporterService |
public boolean link(D declaration, ServiceReference<S> declarationBinderRef) {
S declarationBinder = bindersManager.getDeclarationBinder(declarationBinderRef);
LOG.debug(declaration + " match the filter of " + declarationBinder + " : bind them together");
declaration.bind(declarationBinderRef);
try {
declarationBinder.addDeclaration(declaration);
} catch (Exception e) {
declaration.unbind(declarationBinderRef);
LOG.debug(declarationBinder + " throw an exception when giving to it the Declaration "
+ declaration, e);
return false;
}
return true;
} | Try to link the declaration with the importerService referenced by the ServiceReference,.
return true if they have been link together, false otherwise.
@param declaration The Declaration
@param declarationBinderRef The ServiceReference<S> of S
@return true if they have been link together, false otherwise. |
public boolean unlink(D declaration, ServiceReference<S> declarationBinderRef) {
S declarationBinder = bindersManager.getDeclarationBinder(declarationBinderRef);
try {
declarationBinder.removeDeclaration(declaration);
} catch (BinderException e) {
LOG.debug(declarationBinder + " throw an exception when removing of it the Declaration "
+ declaration, e);
declaration.unhandle(declarationBinderRef);
return false;
} finally {
declaration.unbind(declarationBinderRef);
}
return true;
} | Try to unlink the declaration from the importerService referenced by the ServiceReference,.
return true if they have been cleanly unlink, false otherwise.
@param declaration The Declaration
@param declarationBinderRef The ServiceReference of the ImporterService
@return true if they have been cleanly unlink, false otherwise. |
private static String removeLastDot(final String pkgName) {
return pkgName.charAt(pkgName.length() - 1) == Characters.DOT ? pkgName.substring(0, pkgName.length() - 1) : pkgName;
} | Filters a dot at the end of the passed package name if present.
@param pkgName
a package name
@return a filtered package name |
private Point3d nextConfinedPosition(Point3d lastPosition){
double timelagSub = timelag / numberOfSubsteps;
Point3d center = new Point3d(0, 0, 0);
Point3d lastValidPosition = lastPosition;
int validSteps = 0;
while(validSteps<numberOfSubsteps){
double u = r.nextDouble();
double steplength = Math.sqrt(-2*dimension*diffusioncoefficient*timelagSub*Math.log(1-u));
Point3d candiate = SimulationUtil.randomPosition(dimension, steplength);
candiate.add(lastValidPosition);
if(center.distance(candiate)<radius){
lastValidPosition = candiate;
validSteps++;
}else{
proportionReflectedSteps++;
}
}
return lastValidPosition;
} | Simulates a single step (for dt) of a confined diffusion inside of a circle.
Therefore each step is split up in N substeps. A substep which collidates
with an object is set to the previous position.
@param Nsub number of substeps
@return |
@Nonnull
private static Properties findDefaultProperties() {
final InputStream in = SourceCodeFormatter.class.getClassLoader().getResourceAsStream(DEFAULT_PROPERTIES_PATH);
final Properties p = new Properties();
try {
p.load(in);
} catch (final IOException e) {
throw new RuntimeException(String.format("Can not load resource %s", DEFAULT_PROPERTIES_PATH));
}
return p;
} | Gets the default options to be passed when no custom properties are given.
@return properties with formatter options |
public static String format(final String code, final Properties options, final LineEnding lineEnding) {
Check.notEmpty(code, "code");
Check.notEmpty(options, "options");
Check.notNull(lineEnding, "lineEnding");
final CodeFormatter formatter = ToolFactory.createCodeFormatter(options);
final String lineSeparator = LineEnding.find(lineEnding, code);
TextEdit te = null;
try {
te = formatter.format(CodeFormatter.K_COMPILATION_UNIT, code, 0, code.length(), 0, lineSeparator);
} catch (final Exception formatFailed) {
LOG.warn("Formatting failed", formatFailed);
}
String formattedCode = code;
if (te == null) {
LOG.info("Code cannot be formatted. Possible cause is unmatched source/target/compliance version.");
} else {
final IDocument doc = new Document(code);
try {
te.apply(doc);
} catch (final Exception e) {
LOG.warn(e.getLocalizedMessage(), e);
}
formattedCode = doc.get();
}
return formattedCode;
} | Pretty prints the given source code.
@param code
source code to format
@param options
formatter options
@param lineEnding
desired line ending
@return formatted source code |
private void processProperties() {
state = true;
try {
exporterServiceFilter = getFilter(exporterServiceFilterProperty);
} catch (InvalidFilterException invalidFilterException) {
LOG.debug("The value of the Property " + FILTER_EXPORTERSERVICE_PROPERTY + " is invalid,"
+ " the recuperation of the Filter has failed. The instance gonna stop.", invalidFilterException);
state = false;
return;
}
try {
exportDeclarationFilter = getFilter(exportDeclarationFilterProperty);
} catch (InvalidFilterException invalidFilterException) {
LOG.debug("The value of the Property " + FILTER_EXPORTDECLARATION_PROPERTY + " is invalid,"
+ " the recuperation of the Filter has failed. The instance gonna stop.", invalidFilterException);
state = false;
return;
}
} | Get the filters ExporterServiceFilter and ExportDeclarationFilter from the properties, stop the instance if one of.
them is invalid. |
@Updated
public void updated() {
processProperties();
synchronized (lock) {
exportersManager.applyFilterChanges(exporterServiceFilter);
declarationsManager.applyFilterChanges(exportDeclarationFilter);
}
} | Called by iPOJO when the configuration of the DefaultExportationLinker is updated.
<p/>
Call #processProperties() to get the updated filters ExporterServiceFilter and ExportDeclarationFilter.
Compute and apply the changes in the links relatives to the changes in the filters. |
@Bind(id = "exporterServices", specification = ExporterService.class, aggregate = true, optional = true)
void bindExporterService(ServiceReference<ExporterService> serviceReference) {
synchronized (lock) {
try {
exportersManager.add(serviceReference);
} catch (InvalidFilterException invalidFilterException) {
LOG.error("The ServiceProperty \"" + TARGET_FILTER_PROPERTY + "\" of the ExporterService "
+ bundleContext.getService(serviceReference) + " doesn't provides a valid Filter."
+ " To be used, it must provides a correct \"" + TARGET_FILTER_PROPERTY + "\" ServiceProperty.",
invalidFilterException
);
return;
}
if (!exportersManager.matched(serviceReference)) {
return;
}
LOG.debug(linkerName + " : Bind the ExporterService "
+ exportersManager.getDeclarationBinder(serviceReference)
+ " with filter " + exportersManager.getTargetFilter(serviceReference));
exportersManager.createLinks(serviceReference);
}
} | Bind the {@link ExporterService} matching the exporterServiceFilter.
<p/>
Check all the already bound {@link ExportDeclaration}s, if the metadata of the ExportDeclaration match the filter
exposed by the ExporterService, link them together. |
@Modified(id = "exporterServices")
void modifiedExporterService(ServiceReference<ExporterService> serviceReference) {
try {
exportersManager.modified(serviceReference);
} catch (InvalidFilterException invalidFilterException) {
LOG.error("The ServiceProperty \"" + TARGET_FILTER_PROPERTY + "\" of the ExporterService "
+ bundleContext.getService(serviceReference) + " doesn't provides a valid Filter."
+ " To be used, it must provides a correct \"" + TARGET_FILTER_PROPERTY + "\" ServiceProperty.",
invalidFilterException
);
exportersManager.removeLinks(serviceReference);
return;
}
if (exportersManager.matched(serviceReference)) {
exportersManager.updateLinks(serviceReference);
} else {
exportersManager.removeLinks(serviceReference);
}
} | Update the Target Filter of the ExporterService.
Apply the induce modifications on the links of the ExporterService
@param serviceReference |
@Unbind(id = "exporterServices")
void unbindExporterService(ServiceReference<ExporterService> serviceReference) {
LOG.debug(linkerName + " : Unbind the ExporterService " + exportersManager.getDeclarationBinder(serviceReference));
synchronized (lock) {
exportersManager.removeLinks(serviceReference);
exportersManager.remove(serviceReference);
}
} | Unbind the {@link ExporterService}. |
@Bind(id = "exportDeclarations", specification = ExportDeclaration.class, aggregate = true, optional = true)
void bindExportDeclaration(ServiceReference<ExportDeclaration> exportDeclarationSRef) {
synchronized (lock) {
declarationsManager.add(exportDeclarationSRef);
LOG.debug(linkerName + " : Bind the ExportDeclaration "
+ declarationsManager.getDeclaration(exportDeclarationSRef));
if (!declarationsManager.matched(exportDeclarationSRef)) {
return;
}
declarationsManager.createLinks(exportDeclarationSRef);
}
} | Bind the {@link ExportDeclaration} matching the filter ExportDeclarationFilter.
<p/>
Check if metadata of the ExportDeclaration match the filter exposed by the {@link ExporterService}s bound.
If the ExportDeclaration matches the ExporterService filter, link them together. |
@Modified(id = "exportDeclarations")
void modifiedExportDeclaration(ServiceReference<ExportDeclaration> exportDeclarationSRef) {
LOG.debug(linkerName + " : Modify the ExportDeclaration "
+ declarationsManager.getDeclaration(exportDeclarationSRef));
synchronized (lock) {
declarationsManager.removeLinks(exportDeclarationSRef);
declarationsManager.modified(exportDeclarationSRef);
if (!declarationsManager.matched(exportDeclarationSRef)) {
return;
}
declarationsManager.createLinks(exportDeclarationSRef);
}
} | Unbind and bind the {@link ExportDeclaration}. |
@Unbind(id = "exportDeclarations")
void unbindExportDeclaration(ServiceReference<ExportDeclaration> exportDeclarationSRef) {
LOG.debug(linkerName + " : Unbind the ExportDeclaration "
+ declarationsManager.getDeclaration(exportDeclarationSRef));
synchronized (lock) {
declarationsManager.removeLinks(exportDeclarationSRef);
declarationsManager.remove(exportDeclarationSRef);
}
} | Unbind the {@link ExportDeclaration}. |
public void addConnectionListener(KNXListener l)
{
if (l == null)
return;
synchronized (listeners) {
if (!listeners.contains(l)) {
listeners.add(l);
listenersCopy = new ArrayList(listeners);
}
else
logger.warn("event listener already registered");
}
} | /* (non-Javadoc)
@see tuwien.auto.calimero.knxnetip.KNXnetIPConnection#addConnectionListener
(tuwien.auto.calimero.KNXListener) |
public void removeConnectionListener(KNXListener l)
{
synchronized (listeners) {
if (listeners.remove(l))
listenersCopy = new ArrayList(listeners);
}
} | /* (non-Javadoc)
@see tuwien.auto.calimero.knxnetip.KNXnetIPConnection#removeConnectionListener
(tuwien.auto.calimero.KNXListener) |
public void send(CEMI frame, BlockingMode mode) throws KNXTimeoutException,
KNXConnectionClosedException
{
// send state | blocking | nonblocking
// -----------------------------------
// OK |send+wait | send+return
// WAIT |wait+s.+w.| throw
// ACK_ERROR |send+wait | send+return
// ERROR |throw | throw
if (state == CLOSED) {
logger.warn("send invoked on closed connection - aborted");
throw new KNXConnectionClosedException("connection closed");
}
if (state < 0) {
logger.error("send invoked in error state " + state + " - aborted");
throw new KNXIllegalStateException("in error state, send aborted");
}
// arrange into line for blocking mode
if (mode != NONBLOCKING)
sendWaitQueue.acquire();
synchronized (lock) {
if (mode == NONBLOCKING && state != OK && state != ACK_ERROR) {
logger.warn("nonblocking send invoked while waiting for data response "
+ "in state " + state + " - aborted");
throw new KNXIllegalStateException("waiting for data response");
}
try {
if (state == CLOSED) {
logger.warn("send invoked on closed connection - aborted");
throw new KNXConnectionClosedException("connection closed");
}
updateState = mode == NONBLOCKING;
final byte[] buf;
if (serviceRequest == KNXnetIPHeader.ROUTING_IND)
buf = PacketHelper.toPacket(new RoutingIndication(frame));
else
buf = PacketHelper.toPacket(new ServiceRequest(serviceRequest,
channelID, getSeqNoSend(), frame));
final DatagramPacket p =
new DatagramPacket(buf, buf.length, dataEP.getAddress(), dataEP
.getPort());
int attempt = 0;
for (; attempt < maxSendAttempts; ++attempt) {
logger.trace("sending cEMI frame, " + mode + ", attempt "
+ (attempt + 1));
socket.send(p);
// shortcut for routing, don't switch into 'ack-pending'
if (serviceRequest == KNXnetIPHeader.ROUTING_IND)
return;
internalState = ACK_PENDING;
// always forward this state to user
state = ACK_PENDING;
if (mode == NONBLOCKING)
return;
waitForStateChange(ACK_PENDING, responseTimeout);
if (internalState == CEMI_CON_PENDING || internalState == OK)
break;
}
// close connection on no service ack from server
if (attempt == maxSendAttempts) {
final KNXAckTimeoutException e =
new KNXAckTimeoutException("no acknowledge reply received");
close(INTERNAL, "maximum send attempts", LogLevel.ERROR, e);
throw e;
}
// always forward this state to user
state = internalState;
if (mode == WAIT_FOR_ACK)
return;
// wait for incoming request
waitForStateChange(CEMI_CON_PENDING, CONFIRMATION_TIMEOUT);
// throw on no answer
if (internalState == CEMI_CON_PENDING) {
final KNXTimeoutException e =
new KNXTimeoutException("no confirmation reply received");
logger.log(LogLevel.INFO, "send response timeout", e);
internalState = OK;
throw e;
}
}
catch (final IOException e) {
close(INTERNAL, "communication failure", LogLevel.ERROR, e);
throw new KNXConnectionClosedException("connection closed");
}
finally {
updateState = true;
setState(internalState);
if (mode != NONBLOCKING)
sendWaitQueue.release();
}
}
} | <p>
If <code>mode</code> is {@link KNXnetIPConnection#WAIT_FOR_CON} or
{@link KNXnetIPConnection#WAIT_FOR_ACK}, the sequence order of more
{@link #send(CEMI, tuwien.auto.calimero.knxnetip.KNXnetIPConnection.BlockingMode)}
calls from different threads is being maintained according to invocation order
(FIFO).<br>
A call of this method blocks until (possible) previous invocations are done, then
does communication according to the protocol and waits for response (either ACK or
cEMI confirmation), timeout or an error condition.<br>
Note that, for now, when using blocking mode any ongoing nonblocking invocation is
not detected or considered for waiting until completion.
<p>
If mode is {@link KNXnetIPConnection#NONBLOCKING}, sending is only permitted if no
other send is currently being done, otherwise throws a
{@link KNXIllegalStateException}. A user has to check the state ({@link #getState()}
on its own. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.