2 * Copyright (c) 2010-2022 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.globalcache.internal.handler;
15 import static org.openhab.binding.globalcache.internal.GlobalCacheBindingConstants.*;
17 import java.io.BufferedInputStream;
18 import java.io.BufferedReader;
19 import java.io.ByteArrayOutputStream;
20 import java.io.DataOutputStream;
21 import java.io.IOException;
22 import java.io.InputStreamReader;
23 import java.net.InetAddress;
24 import java.net.InetSocketAddress;
25 import java.net.NetworkInterface;
26 import java.net.Socket;
27 import java.net.SocketException;
28 import java.net.URLDecoder;
29 import java.net.URLEncoder;
30 import java.net.UnknownHostException;
31 import java.nio.charset.StandardCharsets;
32 import java.util.concurrent.LinkedBlockingQueue;
33 import java.util.concurrent.ScheduledExecutorService;
34 import java.util.concurrent.ScheduledFuture;
35 import java.util.concurrent.TimeUnit;
36 import java.util.concurrent.atomic.AtomicInteger;
37 import java.util.regex.Pattern;
39 import org.eclipse.jdt.annotation.NonNull;
40 import org.openhab.binding.globalcache.internal.GlobalCacheBindingConstants.CommandType;
41 import org.openhab.binding.globalcache.internal.command.CommandGetstate;
42 import org.openhab.binding.globalcache.internal.command.CommandGetversion;
43 import org.openhab.binding.globalcache.internal.command.CommandSendir;
44 import org.openhab.binding.globalcache.internal.command.CommandSendserial;
45 import org.openhab.binding.globalcache.internal.command.CommandSetstate;
46 import org.openhab.binding.globalcache.internal.command.RequestMessage;
47 import org.openhab.binding.globalcache.internal.command.ResponseMessage;
48 import org.openhab.core.common.ThreadPoolManager;
49 import org.openhab.core.library.types.OnOffType;
50 import org.openhab.core.library.types.StringType;
51 import org.openhab.core.thing.Channel;
52 import org.openhab.core.thing.ChannelUID;
53 import org.openhab.core.thing.Thing;
54 import org.openhab.core.thing.ThingStatus;
55 import org.openhab.core.thing.ThingStatusDetail;
56 import org.openhab.core.thing.ThingTypeUID;
57 import org.openhab.core.thing.binding.BaseThingHandler;
58 import org.openhab.core.transform.TransformationException;
59 import org.openhab.core.transform.TransformationHelper;
60 import org.openhab.core.transform.TransformationService;
61 import org.openhab.core.types.Command;
62 import org.openhab.core.types.RefreshType;
63 import org.osgi.framework.BundleContext;
64 import org.osgi.framework.FrameworkUtil;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
69 * The {@link GlobalCacheHandler} is responsible for handling commands, which are
70 * sent to one of the channels.
72 * @author Mark Hilbush - Initial contribution
74 public class GlobalCacheHandler extends BaseThingHandler {
75 private Logger logger = LoggerFactory.getLogger(GlobalCacheHandler.class);
77 private final BundleContext bundleContext;
79 private static final String GLOBALCACHE_THREAD_POOL = "globalCacheHandler";
81 private InetAddress ifAddress;
82 private CommandProcessor commandProcessor;
83 private ScheduledExecutorService scheduledExecutorService = ThreadPoolManager
84 .getScheduledPool(GLOBALCACHE_THREAD_POOL + "-" + thingID());
85 private ScheduledFuture<?> scheduledFuture;
87 private LinkedBlockingQueue<RequestMessage> sendQueue = null;
89 private String ipv4Address;
91 // IR transaction counter
92 private AtomicInteger irCounter;
94 public GlobalCacheHandler(@NonNull Thing gcDevice, String ipv4Address) {
96 irCounter = new AtomicInteger(1);
97 commandProcessor = new CommandProcessor();
98 scheduledFuture = null;
99 this.ipv4Address = ipv4Address;
100 this.bundleContext = FrameworkUtil.getBundle(GlobalCacheHandler.class).getBundleContext();
104 public void initialize() {
105 logger.debug("Initializing thing {}", thingID());
107 ifAddress = InetAddress.getByName(ipv4Address);
108 logger.debug("Handler using address {} on network interface {}", ifAddress.getHostAddress(),
109 NetworkInterface.getByInetAddress(ifAddress).getName());
110 } catch (SocketException e) {
111 logger.error("Handler got Socket exception creating multicast socket: {}", e.getMessage());
112 markThingOfflineWithError(ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR, "No suitable network interface");
114 } catch (UnknownHostException e) {
115 logger.error("Handler got UnknownHostException getting local IPv4 network interface: {}", e.getMessage());
116 markThingOfflineWithError(ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR, "No suitable network interface");
119 scheduledFuture = scheduledExecutorService.schedule(commandProcessor, 2, TimeUnit.SECONDS);
123 public void dispose() {
124 logger.debug("Disposing thing {}", thingID());
125 commandProcessor.terminate();
126 if (scheduledFuture != null) {
127 scheduledFuture.cancel(false);
132 public void handleCommand(ChannelUID channelUID, Command command) {
133 if (command == null) {
134 logger.warn("Command passed to handler for thing {} is null", thingID());
138 // Don't try to send command if the device is not online
140 logger.debug("Can't handle command {} because handler for thing {} is not ONLINE", command, thingID());
144 Channel channel = thing.getChannel(channelUID.getId());
145 if (channel == null) {
146 logger.warn("Unknown channel {} for thing {}; is item defined correctly", channelUID.getId(), thingID());
150 // Get module and connector properties for this channel
151 String modNum = channel.getProperties().get(CHANNEL_PROPERTY_MODULE);
152 String conNum = channel.getProperties().get(CHANNEL_PROPERTY_CONNECTOR);
153 if (modNum == null || conNum == null) {
154 logger.error("Channel {} of thing {} has no module/connector property", channelUID.getId(), thingID());
158 if (command instanceof RefreshType) {
159 handleRefresh(modNum, conNum, channel);
163 switch (channel.getChannelTypeUID().getId()) {
164 case CHANNEL_TYPE_CC:
165 handleContactClosure(modNum, conNum, command, channelUID);
168 case CHANNEL_TYPE_IR:
169 handleInfrared(modNum, conNum, command, channelUID);
172 case CHANNEL_TYPE_SL:
173 handleSerial(modNum, conNum, command, channelUID);
176 case CHANNEL_TYPE_SL_DIRECT:
177 handleSerialDirect(modNum, conNum, command, channelUID);
181 logger.warn("Thing {} has unknown channel type {}", thingID(), channel.getChannelTypeUID().getId());
186 private void handleContactClosure(String modNum, String conNum, Command command, ChannelUID channelUID) {
187 logger.debug("Handling CC command {} on channel {} of thing {}", command, channelUID.getId(), thingID());
189 if (command instanceof OnOffType) {
190 CommandSetstate setstate = new CommandSetstate(thing, command, sendQueue, modNum, conNum);
195 private void handleInfrared(String modNum, String conNum, Command command, ChannelUID channelUID) {
196 logger.debug("Handling infrared command {} on channel {} of thing {}", command, channelUID.getId(), thingID());
198 String irCode = lookupCode(command);
199 if (irCode != null) {
200 CommandSendir sendir = new CommandSendir(thing, command, sendQueue, modNum, conNum, irCode, getCounter());
205 private void handleSerial(String modNum, String conNum, Command command, ChannelUID channelUID) {
206 logger.debug("Handle serial command {} on channel {} of thing {}", command, channelUID.getId(), thingID());
208 String slCode = lookupCode(command);
209 if (slCode != null) {
210 CommandSendserial sendserial = new CommandSendserial(thing, command, sendQueue, modNum, conNum, slCode);
211 sendserial.execute();
215 private void handleSerialDirect(String modNum, String conNum, Command command, ChannelUID channelUID) {
216 logger.debug("Handle serial command {} on channel {} of thing {}", command, channelUID.getId(), thingID());
218 CommandSendserial sendserial = new CommandSendserial(thing, command, sendQueue, modNum, conNum,
220 sendserial.execute();
223 private void handleRefresh(String modNum, String conNum, Channel channel) {
224 // REFRESH makes sense only for CC channels because we can query the device for the relay state
225 if (channel.getChannelTypeUID().getId().equals(CHANNEL_TYPE_CC)) {
226 logger.debug("Handle REFRESH command on channel {} for thing {}", channel.getUID().getId(), thingID());
228 CommandGetstate getstate = new CommandGetstate(thing, sendQueue, modNum, conNum);
230 if (getstate.isSuccessful()) {
231 updateState(channel.getUID(), getstate.state());
236 private int getCounter() {
237 return irCounter.getAndIncrement();
241 * Look up the IR or serial command code in the MAP file.
244 private String lookupCode(Command command) {
245 if (command.toString() == null) {
246 logger.warn("Unable to perform transform on null command string");
250 String mapFile = (String) thing.getConfiguration().get(THING_CONFIG_MAP_FILENAME);
251 if (mapFile == null || mapFile.isEmpty()) {
252 logger.warn("MAP file is not defined in configuration of thing {}", thingID());
256 TransformationService transformService = TransformationHelper.getTransformationService(bundleContext, "MAP");
257 if (transformService == null) {
258 logger.error("Failed to get MAP transformation service for thing {}; is bundle installed?", thingID());
264 code = transformService.transform(mapFile, command.toString());
265 } catch (TransformationException e) {
266 logger.error("Failed to transform {} for thing {} using map file '{}', exception={}", command, thingID(),
267 mapFile, e.getMessage());
271 if (code == null || code.isEmpty()) {
272 logger.warn("No entry for {} in map file '{}' for thing {}", command, mapFile, thingID());
276 logger.debug("Transformed {} for thing {} with map file '{}'", command, thingID(), mapFile);
278 // Determine if the code is hex format. If so, convert to GC format
279 if (isHexCode(code)) {
280 logger.debug("Code is in hex format, convert to GC format");
282 code = convertHexToGC(code);
283 logger.debug("Converted hex code is: {}", code);
284 } catch (HexCodeConversionException e) {
285 logger.info("Failed to convert hex code to globalcache format: {}", e.getMessage());
293 * Check if the string looks like a hex code; if not then assume it's GC format
295 private boolean isHexCode(String code) {
296 Pattern pattern = Pattern.compile("0000( +[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f])+");
297 return pattern.matcher(code).find();
301 * Convert a hex code IR string to a Global Cache formatted IR string
303 private String convertHexToGC(String hexCode) throws HexCodeConversionException {
304 // Magic number for converting frequency to GC format
305 final int freqConversionFactor = 4145146;
306 final int repeat = 1;
311 String[] hexCodeArray = hexCode.trim().split(" ");
313 if (hexCodeArray.length < 5) {
314 throw new HexCodeConversionException("Hex code is too short");
317 if (!hexCodeArray[0].equals("0000")) {
318 throw new HexCodeConversionException("Illegal hex code element 0, should be 0000");
322 // Use magic number to get frequency
323 frequency = Math.round(freqConversionFactor / Integer.parseInt(hexCodeArray[1], 16));
324 } catch (Exception e) {
325 throw new HexCodeConversionException("Unable to convert frequency from element 1");
329 // Offset is derived from sequenceLength1
330 sequence1Length = Integer.parseInt(hexCodeArray[2], 16);
331 offset = (sequence1Length * 2) + 1;
332 } catch (Exception e) {
333 throw new HexCodeConversionException("Unable to convert offset from element 2");
336 // sequenceLength2 (hexCodeArray[3]) is not used
338 StringBuilder gcCode = new StringBuilder();
339 gcCode.append(frequency);
341 gcCode.append(repeat);
343 gcCode.append(offset);
346 // The remaining fields are just converted to decimal
347 for (int i = 4; i < hexCodeArray.length; i++) {
349 gcCode.append(Integer.parseInt(hexCodeArray[i], 16));
351 } catch (Exception e) {
352 throw new HexCodeConversionException("Unable to convert remaining hex code string");
355 return gcCode.toString();
358 public static String getAsHexString(byte[] b) {
359 StringBuilder sb = new StringBuilder();
361 for (int j = 0; j < b.length; j++) {
362 String s = String.format("%02x ", b[j] & 0xff);
365 return sb.toString();
368 public String getIP() {
369 return thing.getConfiguration().get(THING_PROPERTY_IP).toString();
372 public String getFlexActiveCable() {
373 return thing.getConfiguration().get(THING_CONFIG_ACTIVECABLE).toString();
376 private String thingID() {
377 // Return segments 2 & 3 only
378 String s = thing.getUID().getAsString();
379 return s.substring(s.indexOf(':') + 1);
383 * Manage the ONLINE/OFFLINE status of the thing
385 private void markThingOnline() {
387 logger.debug("Changing status of {} from {}({}) to ONLINE", thingID(), getStatus(), getDetail());
388 updateStatus(ThingStatus.ONLINE);
392 private void markThingOffline() {
394 logger.debug("Changing status of {} from {}({}) to OFFLINE", thingID(), getStatus(), getDetail());
395 updateStatus(ThingStatus.OFFLINE);
399 private void markThingOfflineWithError(ThingStatusDetail statusDetail, String statusMessage) {
400 // If it's offline with no detail or if it's not offline, mark it offline with detailed status
401 if ((isOffline() && getDetail().equals(ThingStatusDetail.NONE)) || !isOffline()) {
402 logger.debug("Changing status of {} from {}({}) to OFFLINE({})", thingID(), getStatus(), getDetail(),
404 updateStatus(ThingStatus.OFFLINE, statusDetail, statusMessage);
409 private boolean isOnline() {
410 return thing.getStatus().equals(ThingStatus.ONLINE);
413 private boolean isOffline() {
414 return thing.getStatus().equals(ThingStatus.OFFLINE);
417 private ThingStatus getStatus() {
418 return thing.getStatus();
421 private ThingStatusDetail getDetail() {
422 return thing.getStatusInfo().getStatusDetail();
426 * The {@link HexCodeConversionException} class is responsible for
428 * @author Mark Hilbush - Initial contribution
430 private class HexCodeConversionException extends Exception {
431 private static final long serialVersionUID = -4422352677677729196L;
433 public HexCodeConversionException(String message) {
439 * The {@link CommandProcessor} class is responsible for handling communication with the GlobalCache
440 * device. It waits for requests to arrive on a queue. When a request arrives, it sends the command to the
441 * GlobalCache device, waits for a response from the device, parses the response, then responds to the caller by
442 * placing a message in a response queue. Device response time is typically well below 100 ms, hence the reason
443 * fgor a relatively low timeout when reading the response queue.
445 * @author Mark Hilbush - Initial contribution
447 private class CommandProcessor extends Thread {
448 private Logger logger = LoggerFactory.getLogger(CommandProcessor.class);
450 private boolean terminate = false;
451 private final String TERMINATE_COMMAND = "terminate";
453 private final int SEND_QUEUE_MAX_DEPTH = 10;
454 private final int SEND_QUEUE_TIMEOUT = 2000;
456 private ConnectionManager connectionManager;
458 public CommandProcessor() {
459 super("GlobalCache Command Processor");
460 sendQueue = new LinkedBlockingQueue<>(SEND_QUEUE_MAX_DEPTH);
461 logger.debug("Processor for thing {} created request queue, depth={}", thingID(), SEND_QUEUE_MAX_DEPTH);
464 public void terminate() {
465 logger.debug("Processor for thing {} is being marked ready to terminate.", thingID());
468 // Send the command processor a terminate message
469 sendQueue.put(new RequestMessage(TERMINATE_COMMAND, null, null, null));
470 } catch (InterruptedException e) {
471 Thread.currentThread().interrupt();
478 logger.debug("Command processor STARTING for thing {} at IP {}", thingID(), getIP());
479 connectionManager = new ConnectionManager();
480 connectionManager.connect();
481 connectionManager.scheduleConnectionMonitorJob();
486 RequestMessage requestMessage;
488 requestMessage = sendQueue.poll(SEND_QUEUE_TIMEOUT, TimeUnit.MILLISECONDS);
489 if (requestMessage != null) {
490 if (requestMessage.getCommandName().equals(TERMINATE_COMMAND)) {
491 logger.debug("Processor for thing {} received terminate message", thingID());
496 connectionManager.connect();
497 if (connectionManager.isConnected()) {
499 long startTime = System.currentTimeMillis();
500 if (requestMessage.isCommand()) {
501 writeCommandToDevice(requestMessage);
502 deviceReply = readReplyFromDevice(requestMessage);
504 writeSerialToDevice(requestMessage);
505 deviceReply = "successful";
507 long endTime = System.currentTimeMillis();
508 logger.debug("Transaction '{}' for thing {} at {} took {} ms",
509 requestMessage.getCommandName(), thingID(), getIP(), endTime - startTime);
511 } catch (IOException e) {
512 logger.error("Comm error for thing {} at {}: {}", thingID(), getIP(), e.getMessage());
513 deviceReply = "ERROR: " + e.getMessage();
514 connectionManager.setCommError(deviceReply);
515 connectionManager.disconnect();
518 deviceReply = "ERROR: " + "No connection to device";
521 logger.trace("Processor for thing {} queuing response message: {}", thingID(), deviceReply);
522 requestMessage.getReceiveQueue().put(new ResponseMessage(deviceReply));
525 } catch (InterruptedException e) {
526 logger.warn("Processor for thing {} was interrupted: {}", thingID(), e.getMessage());
527 Thread.currentThread().interrupt();
530 connectionManager.cancelConnectionMonitorJob();
531 connectionManager.disconnect();
532 connectionManager = null;
533 logger.debug("Command processor TERMINATING for thing {} at IP {}", thingID(), getIP());
537 * Write the command to the device.
539 private void writeCommandToDevice(RequestMessage requestMessage) throws IOException {
540 logger.trace("Processor for thing {} writing command to device", thingID());
542 if (connectionManager.getCommandOut() == null) {
543 logger.debug("Error writing to device because output stream object is null");
547 byte[] deviceCommand = (requestMessage.getDeviceCommand() + '\r').getBytes();
548 connectionManager.getCommandOut().write(deviceCommand);
549 connectionManager.getCommandOut().flush();
553 * Read command reply from the device, then remove the CR at the end of the line.
555 private String readReplyFromDevice(RequestMessage requestMessage) throws IOException {
556 logger.trace("Processor for thing {} reading reply from device", thingID());
558 if (connectionManager.getCommandIn() == null) {
559 logger.debug("Error reading from device because input stream object is null");
560 return "ERROR: BufferedReader is null!";
563 logger.trace("Processor for thing {} reading response from device", thingID());
564 return connectionManager.getCommandIn().readLine().trim();
568 * Write a serial command to the device
570 private void writeSerialToDevice(RequestMessage requestMessage) throws IOException {
571 DataOutputStream out = connectionManager.getSerialOut(requestMessage.getCommandType());
573 logger.warn("Can't send serial command; output stream is null!");
577 byte[] deviceCommand;
578 deviceCommand = URLDecoder.decode(requestMessage.getDeviceCommand(), StandardCharsets.ISO_8859_1)
579 .getBytes(StandardCharsets.ISO_8859_1);
581 logger.debug("Writing decoded deviceCommand byte array: {}", getAsHexString(deviceCommand));
582 out.write(deviceCommand);
587 * The {@link ConnectionManager} class is responsible for managing the state of the connections to the
588 * command port and the serial port(s) of the device.
590 * @author Mark Hilbush - Initial contribution
592 private class ConnectionManager {
593 private Logger logger = LoggerFactory.getLogger(ConnectionManager.class);
595 private DeviceConnection commandConnection;
596 private DeviceConnection serialPort1Connection;
597 private DeviceConnection serialPort2Connection;
599 private SerialPortReader serialReaderPort1;
600 private SerialPortReader serialReaderPort2;
602 private boolean deviceIsConnected;
604 private final String COMMAND_NAME = "command";
605 private final String SERIAL1_NAME = "serial-1";
606 private final String SERIAL2_NAME = "serial-2";
608 private final int COMMAND_PORT = 4998;
609 private final int SERIAL1_PORT = 4999;
610 private final int SERIAL2_PORT = 5000;
612 private final int SOCKET_CONNECT_TIMEOUT = 1500;
614 private ScheduledFuture<?> connectionMonitorJob;
615 private final int CONNECTION_MONITOR_FREQUENCY = 60;
616 private final int CONNECTION_MONITOR_START_DELAY = 15;
618 private Runnable connectionMonitorRunnable = () -> {
619 logger.trace("Performing connection check for thing {} at IP {}", thingID(), commandConnection.getIP());
623 public ConnectionManager() {
624 commandConnection = new DeviceConnection(COMMAND_NAME, COMMAND_PORT);
625 serialPort1Connection = new DeviceConnection(SERIAL1_NAME, SERIAL1_PORT);
626 serialPort2Connection = new DeviceConnection(SERIAL2_NAME, SERIAL2_PORT);
628 commandConnection.setIP(getIPAddress());
629 serialPort1Connection.setIP(getIPAddress());
630 serialPort2Connection.setIP(getIPAddress());
632 deviceIsConnected = false;
635 private String getIPAddress() {
636 String ipAddress = ((GlobalCacheHandler) thing.getHandler()).getIP();
637 if (ipAddress == null || ipAddress.isEmpty()) {
638 logger.debug("Handler for thing {} could not get IP address from config", thingID());
639 markThingOfflineWithError(ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR, "IP address not set");
645 * Connect to the command and serial port(s) on the device. The serial connections are established only for
646 * devices that support serial.
648 protected void connect() {
653 // Get a connection to the command port
654 if (!commandConnect(commandConnection)) {
658 // Get a connection to serial port 1
659 if (deviceSupportsSerialPort1()) {
660 if (!serialConnect(serialPort1Connection)) {
661 commandDisconnect(commandConnection);
666 // Get a connection to serial port 2
667 if (deviceSupportsSerialPort2()) {
668 if (!serialConnect(serialPort2Connection)) {
669 commandDisconnect(commandConnection);
670 serialDisconnect(serialPort1Connection);
676 * All connections opened successfully, so we can mark the thing online
677 * and start the serial port readers
680 deviceIsConnected = true;
681 startSerialPortReaders();
684 private boolean commandConnect(DeviceConnection conn) {
685 logger.debug("Connecting to {} port for thing {} at IP {}", conn.getName(), thingID(), conn.getIP());
686 if (!openSocket(conn)) {
691 conn.setCommandIn(new BufferedReader(new InputStreamReader(conn.getSocket().getInputStream())));
692 conn.setCommandOut(new DataOutputStream(conn.getSocket().getOutputStream()));
693 } catch (IOException e) {
694 logger.debug("Error getting streams to {} port for thing {} at {}, exception={}", conn.getName(),
695 thingID(), conn.getIP(), e.getMessage());
696 markThingOfflineWithError(ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, e.getMessage());
700 logger.info("Got a connection to {} port for thing {} at {}", conn.getName(), thingID(), conn.getIP());
705 private boolean serialConnect(DeviceConnection conn) {
706 logger.debug("Connecting to {} port for thing {} at {}", conn.getName(), thingID(), conn.getIP());
707 if (!openSocket(conn)) {
712 conn.setSerialIn(new BufferedInputStream(conn.getSocket().getInputStream()));
713 conn.setSerialOut(new DataOutputStream(conn.getSocket().getOutputStream()));
714 } catch (IOException e) {
715 logger.debug("Failed to get streams on {} port for thing {} at {}", conn.getName(), thingID(),
720 logger.info("Got a connection to {} port for thing {} at {}", conn.getName(), thingID(), conn.getIP());
725 private boolean openSocket(DeviceConnection conn) {
727 conn.setSocket(new Socket());
728 conn.getSocket().bind(new InetSocketAddress(ifAddress, 0));
729 conn.getSocket().connect(new InetSocketAddress(conn.getIP(), conn.getPort()), SOCKET_CONNECT_TIMEOUT);
730 } catch (IOException e) {
731 logger.debug("Failed to get socket on {} port for thing {} at {}", conn.getName(), thingID(),
738 private void closeSocket(DeviceConnection conn) {
739 if (conn.getSocket() != null) {
741 conn.getSocket().close();
742 } catch (IOException e) {
743 logger.debug("Failed to close socket on {} port for thing {} at {}", conn.getName(), thingID(),
750 * Disconnect from the command and serial port(s) on the device. Only disconnect the serial port
751 * connections if the devices have serial ports.
753 protected void disconnect() {
754 if (!isConnected()) {
757 commandDisconnect(commandConnection);
759 stopSerialPortReaders();
760 if (deviceSupportsSerialPort1()) {
761 serialDisconnect(serialPort1Connection);
763 if (deviceSupportsSerialPort2()) {
764 serialDisconnect(serialPort2Connection);
768 deviceIsConnected = false;
771 private void commandDisconnect(DeviceConnection conn) {
772 deviceDisconnect(conn);
775 private void serialDisconnect(DeviceConnection conn) {
776 deviceDisconnect(conn);
779 private void deviceDisconnect(DeviceConnection conn) {
780 logger.debug("Disconnecting from {} port for thing {} at IP {}", conn.getName(), thingID(), conn.getIP());
783 if (conn.getSerialOut() != null) {
784 conn.getSerialOut().close();
786 if (conn.getSerialIn() != null) {
787 conn.getSerialIn().close();
789 if (conn.getSocket() != null) {
790 conn.getSocket().close();
792 } catch (IOException e) {
793 logger.debug("Error closing {} port for thing {} at IP {}: exception={}", conn.getName(), thingID(),
794 conn.getIP(), e.getMessage());
799 private boolean isConnected() {
800 return deviceIsConnected;
803 public void setCommError(String errorMessage) {
804 markThingOfflineWithError(ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, errorMessage);
808 * Retrieve the input/output streams for command and serial connections.
810 protected BufferedReader getCommandIn() {
811 return commandConnection.getCommandIn();
814 protected DataOutputStream getCommandOut() {
815 return commandConnection.getCommandOut();
818 protected BufferedInputStream getSerialIn(CommandType commandType) {
819 if (commandType != CommandType.SERIAL1 && commandType != CommandType.SERIAL2) {
822 if (commandType == CommandType.SERIAL1) {
823 return serialPort1Connection.getSerialIn();
825 return serialPort2Connection.getSerialIn();
829 protected DataOutputStream getSerialOut(CommandType commandType) {
830 if (commandType != CommandType.SERIAL1 && commandType != CommandType.SERIAL2) {
833 if (commandType == CommandType.SERIAL1) {
834 return serialPort1Connection.getSerialOut();
836 return serialPort2Connection.getSerialOut();
840 private boolean deviceSupportsSerialPort1() {
841 ThingTypeUID typeUID = thing.getThingTypeUID();
843 if (typeUID.equals(THING_TYPE_ITACH_SL)) {
845 } else if (typeUID.equals(THING_TYPE_GC_100_06) || typeUID.equals(THING_TYPE_GC_100_12)) {
847 } else if (typeUID.equals(THING_TYPE_ITACH_FLEX) && getFlexActiveCable().equals(ACTIVE_CABLE_SERIAL)) {
853 private boolean deviceSupportsSerialPort2() {
854 if (thing.getThingTypeUID().equals(THING_TYPE_GC_100_12)) {
861 * Periodically validate the command connection to the device by executing a getversion command.
863 private void scheduleConnectionMonitorJob() {
864 logger.debug("Starting connection monitor job for thing {} at IP {}", thingID(), commandConnection.getIP());
865 connectionMonitorJob = scheduler.scheduleWithFixedDelay(connectionMonitorRunnable,
866 CONNECTION_MONITOR_START_DELAY, CONNECTION_MONITOR_FREQUENCY, TimeUnit.SECONDS);
869 private void cancelConnectionMonitorJob() {
870 if (connectionMonitorJob != null) {
871 logger.debug("Canceling connection monitor job for thing {} at IP {}", thingID(),
872 commandConnection.getIP());
873 connectionMonitorJob.cancel(true);
874 connectionMonitorJob = null;
878 private void checkConnection() {
879 CommandGetversion getversion = new CommandGetversion(thing, sendQueue);
880 getversion.executeQuiet();
882 if (getversion.isSuccessful()) {
883 logger.trace("Connection check successful for thing {} at IP {}", thingID(), commandConnection.getIP());
885 deviceIsConnected = true;
887 logger.debug("Connection check failed for thing {} at IP {}", thingID(), commandConnection.getIP());
892 private void startSerialPortReaders() {
893 if (deviceSupportsSerialPort1()) {
894 serialReaderPort1 = startSerialPortReader(CommandType.SERIAL1, CONFIG_ENABLE_TWO_WAY_PORT_1,
895 CONFIG_END_OF_MESSAGE_DELIMITER_PORT_1);
897 if (deviceSupportsSerialPort2()) {
898 serialReaderPort2 = startSerialPortReader(CommandType.SERIAL2, CONFIG_ENABLE_TWO_WAY_PORT_2,
899 CONFIG_END_OF_MESSAGE_DELIMITER_PORT_2);
903 private SerialPortReader startSerialPortReader(CommandType serialDevice, String enableTwoWayConfig,
904 String endOfMessageDelimiterConfig) {
905 Boolean enableTwoWay = (Boolean) thing.getConfiguration().get(enableTwoWayConfig);
906 logger.debug("Enable two-way is {} for thing {} {}", enableTwoWay, thingID(), serialDevice);
908 if (Boolean.TRUE.equals(enableTwoWay)) {
909 // Get the end of message delimiter from the config, URL decode it, and convert it to a byte array
910 String endOfMessageString = (String) thing.getConfiguration().get(endOfMessageDelimiterConfig);
911 if (endOfMessageString != null && !endOfMessageString.isEmpty()) {
912 logger.debug("End of message is {} for thing {} {}", endOfMessageString, thingID(), serialDevice);
913 byte[] endOfMessage = URLDecoder.decode(endOfMessageString, StandardCharsets.ISO_8859_1)
914 .getBytes(StandardCharsets.ISO_8859_1);
916 // Start the serial reader using the above end-of-message delimiter
917 SerialPortReader serialPortReader = new SerialPortReader(serialDevice, getSerialIn(serialDevice),
919 serialPortReader.start();
920 return serialPortReader;
922 logger.warn("End of message delimiter is not defined in configuration of thing {}", thingID());
928 private void stopSerialPortReaders() {
929 if (deviceSupportsSerialPort1() && serialReaderPort1 != null) {
930 logger.debug("Stopping serial port 1 reader for thing {} at IP {}", thingID(),
931 commandConnection.getIP());
932 serialReaderPort1.stop();
933 serialReaderPort1 = null;
935 if (deviceSupportsSerialPort2() && serialReaderPort2 != null) {
936 logger.debug("Stopping serial port 2 reader for thing {} at IP {}", thingID(),
937 commandConnection.getIP());
938 serialReaderPort2.stop();
939 serialReaderPort2 = null;
945 * The {@link SerialReader} class reads data from the serial connection. When data is
946 * received, the receive channel is updated with the data. Data is read up to the
947 * end-of-message delimiter defined in the Thing configuration.
949 * @author Mark Hilbush - Initial contribution
951 private class SerialPortReader {
952 private Logger logger = LoggerFactory.getLogger(SerialPortReader.class);
954 private CommandType serialPort;
955 private BufferedInputStream serialPortIn;
956 private ScheduledFuture<?> serialPortReaderJob;
957 private boolean terminateSerialPortReader;
959 private byte[] endOfMessage;
961 SerialPortReader(CommandType serialPort, BufferedInputStream serialIn, byte[] endOfMessage) {
962 if (serialIn == null) {
963 throw new IllegalArgumentException("Serial input stream is not set");
965 this.serialPort = serialPort;
966 this.serialPortIn = serialIn;
967 this.endOfMessage = endOfMessage;
968 serialPortReaderJob = null;
969 terminateSerialPortReader = false;
972 public void start() {
973 serialPortReaderJob = scheduledExecutorService.schedule(this::serialPortReader, 0, TimeUnit.SECONDS);
977 if (serialPortReaderJob != null) {
978 terminateSerialPortReader = true;
979 serialPortReaderJob.cancel(true);
980 serialPortReaderJob = null;
984 private void serialPortReader() {
985 logger.info("Serial reader RUNNING for {} on {}:{}", thingID(), getIP(), serialPort);
987 while (!terminateSerialPortReader) {
990 buffer = readUntilEndOfMessage(endOfMessage);
991 if (buffer == null) {
992 logger.debug("Received end-of-stream from {} on {}", getIP(), serialPort);
995 logger.debug("Rcv data from {} at {}:{}: {}", thingID(), getIP(), serialPort,
996 getAsHexString(buffer));
997 updateFeedbackChannel(buffer);
998 } catch (IOException e) {
999 logger.debug("Serial Reader got IOException: {}", e.getMessage());
1001 } catch (InterruptedException e) {
1002 logger.debug("Serial Reader got InterruptedException: {}", e.getMessage());
1006 logger.debug("Serial reader STOPPING for {} on {}:{}", thingID(), getIP(), serialPort);
1009 private byte[] readUntilEndOfMessage(byte[] endOfMessageDelimiter) throws IOException, InterruptedException {
1010 logger.debug("Serial reader waiting for available data");
1013 ByteArrayOutputStream buf = new ByteArrayOutputStream();
1015 // Read from the serial input stream until the endOfMessage delimiter is found
1017 val = serialPortIn.read();
1019 logger.debug("Serial reader got unexpected end of input stream");
1020 throw new IOException("Unexpected end of stream");
1024 if (findEndOfMessage(buf.toByteArray(), endOfMessageDelimiter)) {
1025 // Found the end-of-message delimiter in the serial input stream
1029 logger.debug("Serial reader returning a message");
1030 return buf.toByteArray();
1033 private boolean findEndOfMessage(byte[] buf, byte[] endOfMessage) {
1034 int lengthEOM = endOfMessage.length;
1035 int lengthBuf = buf.length;
1037 // Look for the end-of-message delimiter at the end of the buffer
1038 while (lengthEOM > 0) {
1041 if (lengthBuf < 0 || endOfMessage[lengthEOM] != buf[lengthBuf]) {
1042 // No match on end of message
1046 logger.debug("Serial reader found the end-of-message delimiter in the input buffer");
1050 private void updateFeedbackChannel(byte[] buffer) {
1052 if (serialPort.equals(CommandType.SERIAL1)) {
1053 channelId = CHANNEL_SL_M1_RECEIVE;
1054 } else if (serialPort.equals(CommandType.SERIAL2)) {
1055 channelId = CHANNEL_SL_M2_RECEIVE;
1057 logger.warn("Unknown serial port; can't update feedback channel: {}", serialPort);
1060 Channel channel = getThing().getChannel(channelId);
1061 if (channel != null && isLinked(channelId)) {
1062 logger.debug("Updating feedback channel for port {}", serialPort);
1063 String encodedReply = URLEncoder.encode(new String(buffer, StandardCharsets.ISO_8859_1),
1064 StandardCharsets.ISO_8859_1);
1065 logger.debug("encodedReply='{}'", encodedReply);
1066 updateState(channel.getUID(), new StringType(encodedReply));
1072 * The {@link DeviceConnection} class stores information about the connection to a globalcache device.
1073 * There can be two types of connections, command and serial. The command connection is used to
1074 * send all but the serial strings to the device. The serial connection is used exclusively to
1075 * send serial messages. These serial connections are applicable only to iTach SL and GC-100 devices.
1077 * @author Mark Hilbush - Initial contribution
1079 private class DeviceConnection {
1080 private String connectionName;
1082 private String ipAddress;
1083 private Socket socket;
1084 private BufferedReader commandIn;
1085 private DataOutputStream commandOut;
1086 private BufferedInputStream serialIn;
1087 private DataOutputStream serialOut;
1089 DeviceConnection(String connectionName, int port) {
1090 setName(connectionName);
1095 setCommandOut(null);
1100 public void reset() {
1103 setCommandOut(null);
1108 public String getName() {
1109 return connectionName;
1112 public void setName(String connectionName) {
1113 this.connectionName = connectionName;
1116 public int getPort() {
1120 public void setPort(int port) {
1124 public String getIP() {
1128 public void setIP(String ipAddress) {
1129 this.ipAddress = ipAddress;
1132 public Socket getSocket() {
1136 public void setSocket(Socket socket) {
1137 this.socket = socket;
1140 public BufferedReader getCommandIn() {
1144 public void setCommandIn(BufferedReader commandIn) {
1145 this.commandIn = commandIn;
1148 public DataOutputStream getCommandOut() {
1152 public void setCommandOut(DataOutputStream commandOut) {
1153 this.commandOut = commandOut;
1156 public BufferedInputStream getSerialIn() {
1160 public void setSerialIn(BufferedInputStream serialIn) {
1161 this.serialIn = serialIn;
1164 public DataOutputStream getSerialOut() {
1168 public void setSerialOut(DataOutputStream serialOut) {
1169 this.serialOut = serialOut;