List of usage examples for org.apache.commons.lang StringUtils chomp
public static String chomp(String str)
Removes one newline from end of a String if it's there, otherwise leave it alone.
From source file:org.openhab.binding.keba.handler.KeContactP20Handler.java
protected void onRead(ByteBuffer byteBuffer, DatagramChannel datagramChannel) { String response = new String(byteBuffer.array(), 0, byteBuffer.limit()); response = StringUtils.chomp(response); if (response.contains("TCH-OK")) { // ignore confirmation messages which are not JSON return;/* ww w . java 2 s .co m*/ } try { JsonObject readObject = parser.parse(response).getAsJsonObject(); for (Entry<String, JsonElement> entry : readObject.entrySet()) { switch (entry.getKey()) { case "Product": { Map<String, String> properties = editProperties(); properties.put(CHANNEL_MODEL, entry.getValue().getAsString()); updateProperties(properties); break; } case "Serial": { Map<String, String> properties = editProperties(); properties.put(CHANNEL_SERIAL, entry.getValue().getAsString()); updateProperties(properties); break; } case "Firmware": { Map<String, String> properties = editProperties(); properties.put(CHANNEL_FIRMWARE, entry.getValue().getAsString()); updateProperties(properties); break; } case "Plug": { int state = entry.getValue().getAsInt(); switch (state) { case 0: { updateState(new ChannelUID(getThing().getUID(), CHANNEL_WALLBOX), OnOffType.OFF); updateState(new ChannelUID(getThing().getUID(), CHANNEL_VEHICLE), OnOffType.OFF); updateState(new ChannelUID(getThing().getUID(), CHANNEL_PLUG_LOCKED), OnOffType.OFF); break; } case 1: { updateState(new ChannelUID(getThing().getUID(), CHANNEL_WALLBOX), OnOffType.ON); updateState(new ChannelUID(getThing().getUID(), CHANNEL_VEHICLE), OnOffType.OFF); updateState(new ChannelUID(getThing().getUID(), CHANNEL_PLUG_LOCKED), OnOffType.OFF); break; } case 3: { updateState(new ChannelUID(getThing().getUID(), CHANNEL_WALLBOX), OnOffType.ON); updateState(new ChannelUID(getThing().getUID(), CHANNEL_VEHICLE), OnOffType.OFF); updateState(new ChannelUID(getThing().getUID(), CHANNEL_PLUG_LOCKED), OnOffType.ON); break; } case 5: { updateState(new ChannelUID(getThing().getUID(), CHANNEL_WALLBOX), OnOffType.ON); updateState(new ChannelUID(getThing().getUID(), CHANNEL_VEHICLE), OnOffType.ON); updateState(new ChannelUID(getThing().getUID(), CHANNEL_PLUG_LOCKED), OnOffType.OFF); break; } case 7: { updateState(new ChannelUID(getThing().getUID(), CHANNEL_WALLBOX), OnOffType.ON); updateState(new ChannelUID(getThing().getUID(), CHANNEL_VEHICLE), OnOffType.ON); updateState(new ChannelUID(getThing().getUID(), CHANNEL_PLUG_LOCKED), OnOffType.ON); break; } } break; } case "State": { State newState = new DecimalType(entry.getValue().getAsInt()); updateState(new ChannelUID(getThing().getUID(), CHANNEL_STATE), newState); break; } case "Enable sys": { int state = entry.getValue().getAsInt(); switch (state) { case 1: { updateState(new ChannelUID(getThing().getUID(), CHANNEL_ENABLED), OnOffType.ON); break; } default: { updateState(new ChannelUID(getThing().getUID(), CHANNEL_ENABLED), OnOffType.OFF); break; } } break; } case "Curr HW": { int state = entry.getValue().getAsInt(); maxSystemCurrent = state; State newState = new DecimalType(state); updateState(new ChannelUID(getThing().getUID(), CHANNEL_MAX_SYSTEM_CURRENT), newState); if (maxSystemCurrent < maxPresetCurrent) { sendCommand("curr " + String.valueOf(maxSystemCurrent)); updateState(new ChannelUID(getThing().getUID(), CHANNEL_MAX_PRESET_CURRENT), new DecimalType(maxSystemCurrent)); updateState(new ChannelUID(getThing().getUID(), CHANNEL_MAX_PRESET_CURRENT_RANGE), new PercentType((maxSystemCurrent - 6000) * 100 / (maxSystemCurrent - 6000))); } break; } case "Curr user": { int state = entry.getValue().getAsInt(); maxPresetCurrent = state; updateState(new ChannelUID(getThing().getUID(), CHANNEL_MAX_PRESET_CURRENT), new DecimalType(state)); updateState(new ChannelUID(getThing().getUID(), CHANNEL_MAX_PRESET_CURRENT_RANGE), new PercentType((state - 6000) * 100 / (maxSystemCurrent - 6000))); break; } case "Curr FS": { int state = entry.getValue().getAsInt(); State newState = new DecimalType(state); updateState(new ChannelUID(getThing().getUID(), CHANNEL_FAILSAFE_CURRENT), newState); break; } case "Output": { int state = entry.getValue().getAsInt(); switch (state) { case 1: { updateState(new ChannelUID(getThing().getUID(), CHANNEL_OUTPUT), OnOffType.ON); break; } default: { updateState(new ChannelUID(getThing().getUID(), CHANNEL_OUTPUT), OnOffType.OFF); break; } } break; } case "Input": { int state = entry.getValue().getAsInt(); switch (state) { case 1: { updateState(new ChannelUID(getThing().getUID(), CHANNEL_INPUT), OnOffType.ON); break; } default: { updateState(new ChannelUID(getThing().getUID(), CHANNEL_INPUT), OnOffType.OFF); break; } } break; } case "Sec": { long state = entry.getValue().getAsLong(); Calendar uptime = Calendar.getInstance(); uptime.setTimeZone(TimeZone.getTimeZone("GMT")); uptime.setTimeInMillis(state * 1000); SimpleDateFormat pFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); pFormatter.setTimeZone(TimeZone.getTimeZone("GMT")); updateState(new ChannelUID(getThing().getUID(), CHANNEL_UPTIME), new DateTimeType(pFormatter.format(uptime.getTime()))); break; } case "U1": { int state = entry.getValue().getAsInt(); State newState = new DecimalType(state); updateState(new ChannelUID(getThing().getUID(), CHANNEL_U1), newState); break; } case "U2": { int state = entry.getValue().getAsInt(); State newState = new DecimalType(state); updateState(new ChannelUID(getThing().getUID(), CHANNEL_U2), newState); break; } case "U3": { int state = entry.getValue().getAsInt(); State newState = new DecimalType(state); updateState(new ChannelUID(getThing().getUID(), CHANNEL_U3), newState); break; } case "I1": { int state = entry.getValue().getAsInt(); State newState = new DecimalType(state / 1000); updateState(new ChannelUID(getThing().getUID(), CHANNEL_I1), newState); break; } case "I2": { int state = entry.getValue().getAsInt(); State newState = new DecimalType(state / 1000); updateState(new ChannelUID(getThing().getUID(), CHANNEL_I2), newState); break; } case "I3": { int state = entry.getValue().getAsInt(); State newState = new DecimalType(state / 1000); updateState(new ChannelUID(getThing().getUID(), CHANNEL_I3), newState); break; } case "P": { long state = entry.getValue().getAsLong(); State newState = new DecimalType(state / 1000); updateState(new ChannelUID(getThing().getUID(), CHANNEL_POWER), newState); break; } case "PF": { int state = entry.getValue().getAsInt(); State newState = new PercentType(state / 10); updateState(new ChannelUID(getThing().getUID(), CHANNEL_POWER_FACTOR), newState); break; } case "E pres": { long state = entry.getValue().getAsLong(); State newState = new DecimalType(state / 10); updateState(new ChannelUID(getThing().getUID(), CHANNEL_SESSION_CONSUMPTION), newState); break; } case "E total": { long state = entry.getValue().getAsLong(); State newState = new DecimalType(state / 10); updateState(new ChannelUID(getThing().getUID(), CHANNEL_TOTAL_CONSUMPTION), newState); break; } } } } catch (JsonParseException e) { logger.debug("Invalid JSON data will be ignored: '{}'", response); } }
From source file:org.openhab.binding.keba.internal.handler.KeContactHandler.java
protected void onData(ByteBuffer byteBuffer) { String response = new String(byteBuffer.array(), 0, byteBuffer.limit()); response = StringUtils.chomp(response); if (response.contains("TCH-OK")) { // ignore confirmation messages which are not JSON return;// w w w .j a va2s . c o m } try { JsonObject readObject = parser.parse(response).getAsJsonObject(); for (Entry<String, JsonElement> entry : readObject.entrySet()) { switch (entry.getKey()) { case "Product": { Map<String, String> properties = editProperties(); String product = entry.getValue().getAsString().trim(); properties.put(CHANNEL_MODEL, product); updateProperties(properties); if (product.contains("P20")) { type = KebaType.P20; } else if (product.contains("P30")) { type = KebaType.P30; } series = KebaSeries.getSeries(product.substring(13, 14).charAt(0)); break; } case "Serial": { Map<String, String> properties = editProperties(); properties.put(CHANNEL_SERIAL, entry.getValue().getAsString()); updateProperties(properties); break; } case "Firmware": { Map<String, String> properties = editProperties(); properties.put(CHANNEL_FIRMWARE, entry.getValue().getAsString()); updateProperties(properties); break; } case "Plug": { int state = entry.getValue().getAsInt(); switch (state) { case 0: { updateState(new ChannelUID(getThing().getUID(), CHANNEL_WALLBOX), OnOffType.OFF); updateState(new ChannelUID(getThing().getUID(), CHANNEL_VEHICLE), OnOffType.OFF); updateState(new ChannelUID(getThing().getUID(), CHANNEL_PLUG_LOCKED), OnOffType.OFF); break; } case 1: { updateState(new ChannelUID(getThing().getUID(), CHANNEL_WALLBOX), OnOffType.ON); updateState(new ChannelUID(getThing().getUID(), CHANNEL_VEHICLE), OnOffType.OFF); updateState(new ChannelUID(getThing().getUID(), CHANNEL_PLUG_LOCKED), OnOffType.OFF); break; } case 3: { updateState(new ChannelUID(getThing().getUID(), CHANNEL_WALLBOX), OnOffType.ON); updateState(new ChannelUID(getThing().getUID(), CHANNEL_VEHICLE), OnOffType.OFF); updateState(new ChannelUID(getThing().getUID(), CHANNEL_PLUG_LOCKED), OnOffType.ON); break; } case 5: { updateState(new ChannelUID(getThing().getUID(), CHANNEL_WALLBOX), OnOffType.ON); updateState(new ChannelUID(getThing().getUID(), CHANNEL_VEHICLE), OnOffType.ON); updateState(new ChannelUID(getThing().getUID(), CHANNEL_PLUG_LOCKED), OnOffType.OFF); break; } case 7: { updateState(new ChannelUID(getThing().getUID(), CHANNEL_WALLBOX), OnOffType.ON); updateState(new ChannelUID(getThing().getUID(), CHANNEL_VEHICLE), OnOffType.ON); updateState(new ChannelUID(getThing().getUID(), CHANNEL_PLUG_LOCKED), OnOffType.ON); break; } } break; } case "State": { State newState = new DecimalType(entry.getValue().getAsInt()); updateState(new ChannelUID(getThing().getUID(), CHANNEL_STATE), newState); break; } case "Enable sys": { int state = entry.getValue().getAsInt(); switch (state) { case 1: { updateState(new ChannelUID(getThing().getUID(), CHANNEL_ENABLED), OnOffType.ON); break; } default: { updateState(new ChannelUID(getThing().getUID(), CHANNEL_ENABLED), OnOffType.OFF); break; } } break; } case "Curr HW": { int state = entry.getValue().getAsInt(); maxSystemCurrent = state; State newState = new DecimalType(state); updateState(new ChannelUID(getThing().getUID(), CHANNEL_MAX_SYSTEM_CURRENT), newState); if (maxSystemCurrent != 0) { if (maxSystemCurrent < maxPresetCurrent) { transceiver.send("curr " + String.valueOf(maxSystemCurrent), this); updateState(new ChannelUID(getThing().getUID(), CHANNEL_MAX_PRESET_CURRENT), new DecimalType(maxSystemCurrent)); updateState(new ChannelUID(getThing().getUID(), CHANNEL_MAX_PRESET_CURRENT_RANGE), new PercentType((maxSystemCurrent - 6000) * 100 / (maxSystemCurrent - 6000))); } } else { logger.debug("maxSystemCurrent is 0. Ignoring."); } break; } case "Curr user": { int state = entry.getValue().getAsInt(); maxPresetCurrent = state; updateState(new ChannelUID(getThing().getUID(), CHANNEL_MAX_PRESET_CURRENT), new DecimalType(state)); if (maxSystemCurrent != 0) { updateState(new ChannelUID(getThing().getUID(), CHANNEL_MAX_PRESET_CURRENT_RANGE), new PercentType(Math.min(100, (state - 6000) * 100 / (maxSystemCurrent - 6000)))); } break; } case "Curr FS": { int state = entry.getValue().getAsInt(); State newState = new DecimalType(state); updateState(new ChannelUID(getThing().getUID(), CHANNEL_FAILSAFE_CURRENT), newState); break; } case "Max curr": { int state = entry.getValue().getAsInt(); maxPresetCurrent = state; updateState(new ChannelUID(getThing().getUID(), CHANNEL_PILOT_CURRENT), new DecimalType(state)); updateState(new ChannelUID(getThing().getUID(), CHANNEL_PILOT_PWM), new DecimalType(state)); break; } case "Output": { int state = entry.getValue().getAsInt(); switch (state) { case 1: { updateState(new ChannelUID(getThing().getUID(), CHANNEL_OUTPUT), OnOffType.ON); break; } default: { updateState(new ChannelUID(getThing().getUID(), CHANNEL_OUTPUT), OnOffType.OFF); break; } } break; } case "Input": { int state = entry.getValue().getAsInt(); switch (state) { case 1: { updateState(new ChannelUID(getThing().getUID(), CHANNEL_INPUT), OnOffType.ON); break; } default: { updateState(new ChannelUID(getThing().getUID(), CHANNEL_INPUT), OnOffType.OFF); break; } } break; } case "Sec": { long state = entry.getValue().getAsLong(); Calendar uptime = Calendar.getInstance(); uptime.setTimeZone(TimeZone.getTimeZone("GMT")); uptime.setTimeInMillis(state * 1000); SimpleDateFormat pFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); pFormatter.setTimeZone(TimeZone.getTimeZone("GMT")); updateState(new ChannelUID(getThing().getUID(), CHANNEL_UPTIME), new DateTimeType(pFormatter.format(uptime.getTime()))); break; } case "U1": { int state = entry.getValue().getAsInt(); State newState = new DecimalType(state); updateState(new ChannelUID(getThing().getUID(), CHANNEL_U1), newState); break; } case "U2": { int state = entry.getValue().getAsInt(); State newState = new DecimalType(state); updateState(new ChannelUID(getThing().getUID(), CHANNEL_U2), newState); break; } case "U3": { int state = entry.getValue().getAsInt(); State newState = new DecimalType(state); updateState(new ChannelUID(getThing().getUID(), CHANNEL_U3), newState); break; } case "I1": { int state = entry.getValue().getAsInt(); State newState = new DecimalType(state); updateState(new ChannelUID(getThing().getUID(), CHANNEL_I1), newState); break; } case "I2": { int state = entry.getValue().getAsInt(); State newState = new DecimalType(state); updateState(new ChannelUID(getThing().getUID(), CHANNEL_I2), newState); break; } case "I3": { int state = entry.getValue().getAsInt(); State newState = new DecimalType(state); updateState(new ChannelUID(getThing().getUID(), CHANNEL_I3), newState); break; } case "P": { long state = entry.getValue().getAsLong(); State newState = new DecimalType(state / 1000); updateState(new ChannelUID(getThing().getUID(), CHANNEL_POWER), newState); break; } case "PF": { int state = entry.getValue().getAsInt(); State newState = new PercentType(state / 10); updateState(new ChannelUID(getThing().getUID(), CHANNEL_POWER_FACTOR), newState); break; } case "E pres": { long state = entry.getValue().getAsLong(); State newState = new DecimalType(state / 10); updateState(new ChannelUID(getThing().getUID(), CHANNEL_SESSION_CONSUMPTION), newState); break; } case "E total": { long state = entry.getValue().getAsLong(); State newState = new DecimalType(state / 10); updateState(new ChannelUID(getThing().getUID(), CHANNEL_TOTAL_CONSUMPTION), newState); break; } case "AuthON": { int state = entry.getValue().getAsInt(); State newState = new DecimalType(state); updateState(new ChannelUID(getThing().getUID(), CHANNEL_AUTHON), newState); break; } case "Authreq": { int state = entry.getValue().getAsInt(); State newState = new DecimalType(state); updateState(new ChannelUID(getThing().getUID(), CHANNEL_AUTHREQ), newState); break; } } } } catch (JsonParseException e) { logger.debug("Invalid JSON data will be ignored: '{}'", response); } }
From source file:org.openhab.binding.mart.handler.martHandler.java
/** * this function parses the responses or data read from the datagram channel * * @param byteBuffer/*from ww w.j a v a2s .c om*/ * @param datagramChannel */ protected void readerHandler(ByteBuffer byteBuffer, DatagramChannel datagramChannel) { // Constructs a new String by decoding the specified subarray of bytes using // the platform's default charset. The length of the new String is a function // of the charset, and hence may not be equal to the length of the subarray String response = new String(byteBuffer.array(), 0, byteBuffer.limit()); // Removes one newline from end of a String if it's there, otherwise leave it alone. response = StringUtils.chomp(response); // get data to update channels and to send to machine learning web-service try { JsonObject readData = parser.parse(response).getAsJsonObject(); for (Entry<String, JsonElement> data : readData.entrySet()) { switch (data.getKey()) { case "onToday": State onToday = new DecimalType(data.getValue().getAsInt()); if (onToday != null) { logger.debug("", onToday, getThing().getUID()); updateState(new ChannelUID(getThing().getUID(), CHANNEL_ON_TODAY), onToday); } break; case "onTotal": State onTotal = new DecimalType(data.getValue().getAsInt()); if (onTotal != null) { logger.debug("", onTotal, getThing().getUID()); updateState(new ChannelUID(getThing().getUID(), CHANNEL_ON_TOTAL), onTotal); } break; default: break; } } } catch (JsonParseException e) { logger.debug("Invalid JSON response: '{}'", response); } }
From source file:org.openhab.binding.oceanic.handler.NetworkOceanicThingHandler.java
@Override protected String requestResponse(String commandAsString) { synchronized (this) { if (getThing().getStatus() == ThingStatus.ONLINE) { NetworkOceanicBindingConfiguration config = getConfigAs(NetworkOceanicBindingConfiguration.class); Throttler.lock(config.ipAddress); String request = commandAsString + "\r"; byte[] dataBuffer = new byte[bufferSize]; byte[] tmpData = new byte[bufferSize]; String line;/*from w w w .j ava 2s .c o m*/ int len = -1; int index = 0; boolean sequenceFound = false; final byte lineFeed = (byte) '\n'; final byte carriageReturn = (byte) '\r'; final byte nullChar = (byte) '\0'; final byte eChar = (byte) 'E'; final byte rChar = (byte) 'R'; try { logger.debug("Sending request '{}'", request); outputStream.write(request.getBytes()); outputStream.flush(); while (true) { if ((len = inputStream.read(tmpData)) > -1) { if (logger.isTraceEnabled()) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { sb.append(String.format("%02X ", tmpData[i])); } logger.trace("Read {} bytes : {}", len, sb.toString()); } for (int i = 0; i < len; i++) { if (logger.isTraceEnabled()) { logger.trace("Byte {} equals '{}' (hex '{}')", i, new String(new byte[] { tmpData[i] }), String.format("%02X", tmpData[i])); } if (tmpData[i] == nullChar && !sequenceFound) { sequenceFound = true; logger.trace("Start of sequence found"); } if (sequenceFound && tmpData[i] != lineFeed && tmpData[i] != carriageReturn && tmpData[i] != nullChar) { dataBuffer[index++] = tmpData[i]; if (logger.isTraceEnabled()) { logger.trace("dataBuffer[{}] set to '{}'(hex '{}')", index - 1, new String(new byte[] { dataBuffer[index - 1] }), String.format("%02X", dataBuffer[index - 1])); } } if (sequenceFound && i >= 2) { if (tmpData[i - 2] == eChar && tmpData[i - 1] == rChar && tmpData[i] == rChar) { // Received ERR from the device. return null; } } if (sequenceFound && i > 0 && (tmpData[i - 1] != carriageReturn && tmpData[i] == nullChar)) { index = 0; // Ignore trash received if (logger.isTraceEnabled()) { StringBuilder sb = new StringBuilder(); for (int j = 0; j < i; j++) { sb.append(String.format("%02X ", tmpData[j])); } logger.trace("Ingoring {} bytes : {}", i, sb); } } if (sequenceFound && (tmpData[i] == carriageReturn)) { if (index > 0) { line = new String(Arrays.copyOf(dataBuffer, index)); logger.debug("Received response '{}'", line); line = StringUtils.chomp(line); line = line.replace(",", "."); line = line.trim(); index = 0; return line; } } if (index == bufferSize) { index = 0; } } } } } catch (IOException e) { logger.debug("An exception occurred while quering host {}:{} : '{}'", config.ipAddress, config.portNumber, e.getMessage(), e); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage()); reconnectJob = scheduler.schedule(reconnectRunnable, RECONNECT_INTERVAL, TimeUnit.SECONDS); } finally { Throttler.unlock(config.ipAddress); } } return null; } }
From source file:org.openhab.binding.plugwise.internal.PlugwiseMessageProcessor.java
/** * Parse a buffer into a Message and put it in the appropriate queue for further processing * * @param readBuffer - the string to parse *///from w w w.j a va 2 s . com private void parseAndQueue(ByteBuffer readBuffer) { if (readBuffer != null) { String response = new String(readBuffer.array(), 0, readBuffer.limit()); response = StringUtils.chomp(response); Matcher matcher = RESPONSE_PATTERN.matcher(response); if (matcher.matches()) { String protocolHeader = matcher.group(1); String messageTypeHex = matcher.group(2); String sequence = matcher.group(3); String payload = matcher.group(4); String crc = matcher.group(5); if (protocolHeader.equals(PROTOCOL_HEADER)) { String calculatedCRC = Message.getCRC(messageTypeHex + sequence + payload); if (calculatedCRC.equals(crc)) { MessageType messageType = MessageType.forValue(Integer.parseInt(messageTypeHex, 16)); int sequenceNumber = Integer.parseInt(sequence, 16); if (messageType == null) { logger.debug( "Received unrecognized message: messageTypeHex=0x{}, sequence={}, payload={}", messageTypeHex, sequenceNumber, payload); return; } logger.debug("Received message: messageType={}, sequenceNumber={}, payload={}", messageType, sequenceNumber, payload); try { Message message = messageFactory.createMessage(messageType, sequenceNumber, payload); if (message instanceof AcknowledgementMessage && !((AcknowledgementMessage) message).isExtended()) { logger.debug("Adding to acknowledgedQueue: {}", message); context.getAcknowledgedQueue().put((AcknowledgementMessage) message); } else { logger.debug("Adding to receivedQueue: {}", message); context.getReceivedQueue().put(message); } } catch (IllegalArgumentException e) { logger.warn("Failed to create message", e); } catch (InterruptedException e) { Thread.interrupted(); } } else { logger.warn("Plugwise protocol CRC error: {} does not match {} in message", calculatedCRC, crc); } } else { logger.debug("Plugwise protocol header error: {} in message {}", protocolHeader, response); } } else if (!response.contains("APSRequestNodeInfo") && !response.contains("APSSetSleepBehaviour") && !response.startsWith("# ")) { logger.warn("Plugwise protocol message error: {}", response); } } }
From source file:org.openhab.binding.plugwise.internal.Stick.java
/** * Parse a buffer into a Message and put it in the appropriate queue for further processing * /*from w w w.j av a 2 s.c om*/ * @param readBuffer - the string to parse */ private void parseAndQueue(ByteBuffer readBuffer) { if (readBuffer != null) { Pattern RESPONSE_PATTERN = Pattern.compile("(.{4})(\\w{4})(\\w{4})(\\w*?)(\\w{4})"); String response = new String(readBuffer.array(), 0, readBuffer.limit()); response = StringUtils.chomp(response); Matcher matcher = RESPONSE_PATTERN.matcher(response); if (matcher.matches()) { String protocolHeader = matcher.group(1); String command = matcher.group(2); String sequence = matcher.group(3); String payload = matcher.group(4); String CRC = matcher.group(5); if (protocolHeader.equals(PROTOCOL_HEADER)) { String calculatedCRC = getCRCFromString(command + sequence + payload); if (calculatedCRC.equals(CRC)) { logger.debug( "parseAndQueue: Parsing Plugwise protocol data unit: command:{} sequence:{} payload:{}", new String[] { MessageType.forValue(Integer.parseInt(command, 16)).toString(), Integer.toString(Integer.parseInt(sequence, 16)), payload }); Message theMessage = null; switch (MessageType.forValue(Integer.parseInt(command, 16))) { case ACKNOWLEDGEMENT: theMessage = new AcknowledgeMessage(Integer.parseInt(sequence, 16), payload); break; case NODE_AVAILABLE: theMessage = new NodeAvailableMessage(Integer.parseInt(sequence, 16), payload); break; case INITIALISE_RESPONSE: theMessage = new InitialiseResponseMessage(Integer.parseInt(sequence, 16), payload); break; case DEVICE_ROLECALL_RESPONSE: theMessage = new RoleCallResponseMessage(Integer.parseInt(sequence, 16), payload); break; case DEVICE_CALIBRATION_RESPONSE: theMessage = new CalibrationResponseMessage(Integer.parseInt(sequence, 16), payload); break; case DEVICE_INFORMATION_RESPONSE: theMessage = new InformationResponseMessage(Integer.parseInt(sequence, 16), payload); break; case REALTIMECLOCK_GET_RESPONSE: theMessage = new RealTimeClockGetResponseMessage(Integer.parseInt(sequence, 16), payload); break; case CLOCK_GET_RESPONSE: theMessage = new ClockGetResponseMessage(Integer.parseInt(sequence, 16), payload); break; case POWER_BUFFER_RESPONSE: theMessage = new PowerBufferResponseMessage(Integer.parseInt(sequence, 16), payload); break; case POWER_INFORMATION_RESPONSE: theMessage = new PowerInformationResponseMessage(Integer.parseInt(sequence, 16), payload); break; default: logger.debug( "parseAndQueue: Received unrecognized Plugwise protocol data unit: command:{} sequence:{} payload:{}", new String[] { command, Integer.toString(Integer.parseInt(sequence, 16)), payload }); break; } ; if (theMessage != null) { try { receiveLock.lock(); logger.debug( "parseAndQueue: {} messages before the message ({}) put in the receiveQ", receivedQueue.size(), theMessage.toString()); receivedQueue.put(theMessage); receiveLock.unlock(); } catch (InterruptedException e) { logger.error( "Error queueing Plugwise protocol data unit: command:{} sequence:{} payload:{}", new String[] { MessageType.forValue(Integer.parseInt(command, 16)).toString(), Integer.toString(Integer.parseInt(sequence, 16)), payload }); } } } else { logger.error("Plugwise protocol CRC error: {} does not match {} in message", new String[] { calculatedCRC, CRC }); } } else { logger.debug("parseAndQueue: Plugwise protocol header error: {} in message {}", new String[] { protocolHeader, response }); } } else { if (!response.contains("APSRequestNodeInfo")) { logger.error("Plugwise protocol message error: {} ", response); } } } }
From source file:org.openhab.binding.rme.handler.RMEThingHandler.java
@Override public void onDataReceived(String line) { line = StringUtils.chomp(line); // little hack to overcome Locale limits of the RME Rain Manager // note to the attentive reader : should we add support for system // locale's in the Type classes? ;-) line = line.replace(",", "."); line = line.trim();/* w w w. j ava 2 s . co m*/ Pattern RESPONSE_PATTERN = Pattern.compile("(.*);(0|1);(0|1);(0|1);(0|1);(0|1);(0|1);(0|1);(0|1);(0|1)"); try { logger.trace("Processing '{}'", line); Matcher matcher = RESPONSE_PATTERN.matcher(line); if (matcher.matches()) { for (int i = 1; i <= matcher.groupCount(); i++) { switch (DataField.get(i)) { case LEVEL: { DecimalType decimalType = new DecimalType(matcher.group(i)); updateState(new ChannelUID(getThing().getUID(), DataField.get(i).channelID()), decimalType); break; } case MODE: { StringType stringType = null; if (matcher.group(i).equals("0")) { stringType = MANUAL; } else if (matcher.group(i).equals("1")) { stringType = AUTOMATIC; } updateState(new ChannelUID(getThing().getUID(), DataField.get(i).channelID()), stringType); break; } case SOURCE: { StringType stringType = null; if (matcher.group(i).equals("0")) { stringType = RAIN; } else if (matcher.group(i).equals("1")) { stringType = CITY; } updateState(new ChannelUID(getThing().getUID(), DataField.get(i).channelID()), stringType); break; } default: if (matcher.group(i).equals("0")) { updateState(new ChannelUID(getThing().getUID(), DataField.get(i).channelID()), OnOffType.OFF); } else if (matcher.group(i).equals("1")) { updateState(new ChannelUID(getThing().getUID(), DataField.get(i).channelID()), OnOffType.ON); } break; } } } } catch (Exception e) { logger.error("An exception occurred while receiving data : '{}'", e.getMessage(), e); } }
From source file:org.openhab.binding.rme.internal.handler.RMEThingHandler.java
@Override public void onDataReceived(String line) { line = StringUtils.chomp(line); // little hack to overcome Locale limits of the RME Rain Manager // note to the attentive reader : should we add support for system // locale's in the Type classes? ;-) line = line.replace(",", "."); line = line.trim();/*from ww w . ja va2s .co m*/ Pattern responsePattern = Pattern.compile("(.*);(0|1);(0|1);(0|1);(0|1);(0|1);(0|1);(0|1);(0|1);(0|1)"); try { logger.trace("Processing '{}'", line); Matcher matcher = responsePattern.matcher(line); if (matcher.matches()) { for (int i = 1; i <= matcher.groupCount(); i++) { switch (DataField.get(i)) { case LEVEL: { DecimalType decimalType = new DecimalType(matcher.group(i)); updateState(new ChannelUID(getThing().getUID(), DataField.get(i).channelID()), decimalType); break; } case MODE: { StringType stringType = null; if (matcher.group(i).equals("0")) { stringType = MANUAL; } else if (matcher.group(i).equals("1")) { stringType = AUTOMATIC; } if (stringType != null) { updateState(new ChannelUID(getThing().getUID(), DataField.get(i).channelID()), stringType); } break; } case SOURCE: { StringType stringType = null; if (matcher.group(i).equals("0")) { stringType = RAIN; } else if (matcher.group(i).equals("1")) { stringType = CITY; } if (stringType != null) { updateState(new ChannelUID(getThing().getUID(), DataField.get(i).channelID()), stringType); } break; } default: if (matcher.group(i).equals("0")) { updateState(new ChannelUID(getThing().getUID(), DataField.get(i).channelID()), OnOffType.OFF); } else if (matcher.group(i).equals("1")) { updateState(new ChannelUID(getThing().getUID(), DataField.get(i).channelID()), OnOffType.ON); } break; } } } } catch (Exception e) { logger.error("An exception occurred while receiving data : '{}'", e.getMessage(), e); } }
From source file:org.openhab.io.net.exec.ExecUtil.java
/** * <p>/*from ww w . j ava 2 s . co m*/ * Executes <code>commandLine</code>. Sometimes (especially observed on * MacOS) the commandLine isn't executed properly. In that cases another * exec-method is to be used. To accomplish this please use the special * delimiter '<code>@@</code>'. If <code>commandLine</code> contains this * delimiter it is split into a String[] array and the special exec-method * is used. * </p> * <p> * A possible {@link IOException} gets logged but no further processing is * done. * </p> * * @param commandLine * the command line to execute * @param timeout * timeout for execution in milliseconds * @return response data from executed command line */ public static String executeCommandLineAndWaitResponse(String commandLine, int timeout) { String retval = null; CommandLine cmdLine = null; if (commandLine.contains(CMD_LINE_DELIMITER)) { String[] cmdArray = commandLine.split(CMD_LINE_DELIMITER); cmdLine = new CommandLine(cmdArray[0]); for (int i = 1; i < cmdArray.length; i++) { cmdLine.addArgument(cmdArray[i], false); } } else { cmdLine = CommandLine.parse(commandLine); } DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout); Executor executor = new DefaultExecutor(); ByteArrayOutputStream stdout = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(stdout); executor.setExitValue(1); executor.setStreamHandler(streamHandler); executor.setWatchdog(watchdog); try { executor.execute(cmdLine, resultHandler); logger.debug("executed commandLine '{}'", commandLine); } catch (ExecuteException e) { logger.error("couldn't execute commandLine '" + commandLine + "'", e); } catch (IOException e) { logger.error("couldn't execute commandLine '" + commandLine + "'", e); } // some time later the result handler callback was invoked so we // can safely request the exit code try { resultHandler.waitFor(); int exitCode = resultHandler.getExitValue(); retval = StringUtils.chomp(stdout.toString()); if (resultHandler.getException() != null) { logger.warn(resultHandler.getException().getMessage()); } else { logger.debug("exit code '{}', result '{}'", exitCode, retval); } } catch (InterruptedException e) { logger.error("Timeout occured when executing commandLine '" + commandLine + "'", e); } return retval; }
From source file:org.opennms.javamail.JavaReadMailer.java
/** * <p>string2Lines</p>/*from ww w .j a va 2 s . co m*/ * * @param text a {@link java.lang.String} object. * @return a {@link java.util.List} object. */ public static List<String> string2Lines(String text) { if (text == null) { return null; } String[] linea = StringUtils.split(text, "\n"); for (int i = 0; i < linea.length; i++) { linea[i] = StringUtils.chomp(linea[i]); } return Arrays.asList(linea); }