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.powermax.internal.message;
15 import java.util.ArrayList;
16 import java.util.Calendar;
17 import java.util.EventObject;
18 import java.util.GregorianCalendar;
19 import java.util.HashMap;
20 import java.util.List;
22 import java.util.concurrent.ConcurrentLinkedQueue;
23 import java.util.concurrent.ScheduledExecutorService;
24 import java.util.concurrent.TimeUnit;
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.binding.powermax.internal.connector.PowermaxConnector;
29 import org.openhab.binding.powermax.internal.connector.PowermaxSerialConnector;
30 import org.openhab.binding.powermax.internal.connector.PowermaxTcpConnector;
31 import org.openhab.binding.powermax.internal.state.PowermaxArmMode;
32 import org.openhab.binding.powermax.internal.state.PowermaxPanelSettings;
33 import org.openhab.binding.powermax.internal.state.PowermaxPanelType;
34 import org.openhab.binding.powermax.internal.state.PowermaxState;
35 import org.openhab.binding.powermax.internal.state.PowermaxStateEvent;
36 import org.openhab.binding.powermax.internal.state.PowermaxStateEventListener;
37 import org.openhab.core.common.ThreadPoolManager;
38 import org.openhab.core.i18n.TimeZoneProvider;
39 import org.openhab.core.io.transport.serial.SerialPortManager;
40 import org.openhab.core.types.Command;
41 import org.openhab.core.util.HexUtils;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
46 * A class that manages the communication with the Visonic alarm system
48 * Visonic does not provide a specification of the RS232 protocol and, thus,
49 * the binding uses the available protocol specification given at the ​domoticaforum
50 * http://www.domoticaforum.eu/viewtopic.php?f=68&t=6581
52 * @author Laurent Garnier - Initial contribution
55 public class PowermaxCommManager implements PowermaxMessageEventListener {
57 private static final int DEFAULT_TCP_PORT = 80;
58 private static final int TCP_CONNECTION_TIMEOUT = 5000;
59 private static final int DEFAULT_BAUD_RATE = 9600;
60 private static final int WAITING_DELAY_FOR_RESPONSE = 750;
61 private static final long DELAY_BETWEEN_SETUP_DOWNLOADS = TimeUnit.SECONDS.toMillis(45);
63 private final Logger logger = LoggerFactory.getLogger(PowermaxCommManager.class);
65 private final ScheduledExecutorService scheduler;
67 private final TimeZoneProvider timeZoneProvider;
69 /** The object to store the current settings of the Powermax alarm system */
70 private final PowermaxPanelSettings panelSettings;
72 /** Panel type used when in standard mode */
73 private final PowermaxPanelType panelType;
75 private final boolean forceStandardMode;
76 private final boolean autoSyncTime;
78 private final List<PowermaxStateEventListener> listeners = new ArrayList<>();
80 /** The serial or TCP connecter used to communicate with the Powermax alarm system */
81 private final PowermaxConnector connector;
83 /** The last message sent to the the Powermax alarm system */
84 private @Nullable PowermaxBaseMessage lastSendMsg;
86 /** The message queue of messages to be sent to the the Powermax alarm system */
87 private ConcurrentLinkedQueue<PowermaxBaseMessage> msgQueue = new ConcurrentLinkedQueue<>();
89 /** The time in milliseconds the last download of the panel setup was requested */
90 private long lastTimeDownloadRequested;
92 /** The boolean indicating if the download of the panel setup is in progress or not */
93 private boolean downloadRunning;
95 /** The time in milliseconds used to set time and date */
96 private long syncTimeCheck;
99 * Constructor for Serial Connection
101 * @param sPort the serial port name
102 * @param panelType the panel type to be used when in standard mode
103 * @param forceStandardMode true to force the standard mode rather than trying using the Powerlink mode
104 * @param autoSyncTime true for automatic sync time
105 * @param serialPortManager the serial port manager
106 * @param threadName the prefix name of threads to be created
108 public PowermaxCommManager(String sPort, PowermaxPanelType panelType, boolean forceStandardMode,
109 boolean autoSyncTime, SerialPortManager serialPortManager, String threadName,
110 TimeZoneProvider timeZoneProvider) {
111 this.panelType = panelType;
112 this.forceStandardMode = forceStandardMode;
113 this.autoSyncTime = autoSyncTime;
114 this.timeZoneProvider = timeZoneProvider;
115 this.panelSettings = new PowermaxPanelSettings(panelType);
116 this.scheduler = ThreadPoolManager.getScheduledPool(threadName + "-sender");
117 this.connector = new PowermaxSerialConnector(serialPortManager, sPort.trim(), DEFAULT_BAUD_RATE,
118 threadName + "-reader");
122 * Constructor for TCP connection
124 * @param ip the IP address
125 * @param port TCP port number; default port is used if value <= 0
126 * @param panelType the panel type to be used when in standard mode
127 * @param forceStandardMode true to force the standard mode rather than trying using the Powerlink mode
128 * @param autoSyncTime true for automatic sync time
129 * @param serialPortManager
130 * @param threadName the prefix name of threads to be created
132 public PowermaxCommManager(String ip, int port, PowermaxPanelType panelType, boolean forceStandardMode,
133 boolean autoSyncTime, String threadName, TimeZoneProvider timeZoneProvider) {
134 this.panelType = panelType;
135 this.forceStandardMode = forceStandardMode;
136 this.autoSyncTime = autoSyncTime;
137 this.timeZoneProvider = timeZoneProvider;
138 this.panelSettings = new PowermaxPanelSettings(panelType);
139 this.scheduler = ThreadPoolManager.getScheduledPool(threadName + "-sender");
140 this.connector = new PowermaxTcpConnector(ip.trim(), port > 0 ? port : DEFAULT_TCP_PORT, TCP_CONNECTION_TIMEOUT,
141 threadName + "-reader");
147 * @param listener the listener to be added
149 public synchronized void addEventListener(PowermaxStateEventListener listener) {
150 listeners.add(listener);
151 connector.addEventListener(this);
155 * Remove event listener
157 * @param listener the listener to be removed
159 public synchronized void removeEventListener(PowermaxStateEventListener listener) {
160 connector.removeEventListener(this);
161 listeners.remove(listener);
165 * Connect to the Powermax alarm system
167 * @return true if connected or false if not
169 public void open() throws Exception {
172 msgQueue = new ConcurrentLinkedQueue<>();
176 * Close the connection to the Powermax alarm system.
178 * @return true if connected or false if not
180 public boolean close() {
182 lastTimeDownloadRequested = 0;
183 downloadRunning = false;
184 return isConnected();
188 * @return true if connected to the Powermax alarm system or false if not
190 public boolean isConnected() {
191 return connector.isConnected();
195 * @return the current settings of the Powermax alarm system
197 public PowermaxPanelSettings getPanelSettings() {
198 return panelSettings;
202 * Process and store all the panel settings from the raw buffers
204 * @param PowerlinkMode true if in Powerlink mode or false if in standard mode
206 * @return true if no problem encountered to get all the settings; false if not
208 public boolean processPanelSettings(boolean powerlinkMode) {
209 return panelSettings.process(powerlinkMode, panelType, powerlinkMode ? syncTimeCheck : 0);
213 * @return a new instance of PowermaxState
215 public PowermaxState createNewState() {
216 return new PowermaxState(panelSettings, timeZoneProvider);
220 * @return the last message sent to the Powermax alarm system
222 public synchronized @Nullable PowermaxBaseMessage getLastSendMsg() {
227 public void onNewMessageEvent(EventObject event) {
228 PowermaxMessageEvent messageEvent = (PowermaxMessageEvent) event;
229 PowermaxBaseMessage message = messageEvent.getMessage();
231 if (logger.isDebugEnabled()) {
232 logger.debug("onNewMessageReceived(): received message 0x{} ({})",
233 HexUtils.bytesToHex(message.getRawData()),
234 (message.getReceiveType() != null) ? message.getReceiveType()
235 : String.format("%02X", message.getCode()));
238 if (forceStandardMode && message instanceof PowermaxPowerlinkMessage) {
239 message = new PowermaxBaseMessage(message.getRawData());
242 PowermaxState updateState = message.handleMessage(this);
244 if (updateState == null) {
245 updateState = createNewState();
248 updateState.lastMessageTime.setValue(System.currentTimeMillis());
250 byte[] buffer = updateState.getUpdateSettings();
251 if (buffer != null) {
252 panelSettings.updateRawSettings(buffer);
254 if (!updateState.getUpdatedZoneNames().isEmpty()) {
255 for (Integer zoneIdx : updateState.getUpdatedZoneNames().keySet()) {
256 panelSettings.updateZoneName(zoneIdx, updateState.getUpdatedZoneNames().get(zoneIdx));
259 if (!updateState.getUpdatedZoneInfos().isEmpty()) {
260 for (Integer zoneIdx : updateState.getUpdatedZoneInfos().keySet()) {
261 panelSettings.updateZoneInfo(zoneIdx, updateState.getUpdatedZoneInfos().get(zoneIdx));
265 PowermaxStateEvent newEvent = new PowermaxStateEvent(this, updateState);
267 // send message to event listeners
268 listeners.forEach(listener -> listener.onNewStateEvent(newEvent));
272 public void onCommunicationFailure(String message) {
274 listeners.forEach(listener -> listener.onCommunicationFailure(message));
278 * Compute the CRC of a message
280 * @param data the buffer containing the message
281 * @param len the size of the message in the buffer
283 * @return the computed CRC
285 public static byte computeCRC(byte[] data, int len) {
287 for (int i = 1; i < (len - 2); i++) {
288 checksum = checksum + (data[i] & 0x000000FF);
290 checksum = 0xFF - (checksum % 0xFF);
291 if (checksum == 0xFF) {
294 return (byte) checksum;
298 * Send an ACK for a received message
300 * @param msg the received message object
301 * @param ackType the type of ACK to be sent
303 * @return true if the ACK was sent or false if not
305 public synchronized boolean sendAck(PowermaxBaseMessage msg, byte ackType) {
306 int code = msg.getCode();
307 byte[] rawData = msg.getRawData();
309 if ((code >= 0x80) || ((code < 0x10) && (rawData[rawData.length - 3] == 0x43))) {
310 ackData = new byte[] { 0x0D, ackType, 0x43, 0x00, 0x0A };
312 ackData = new byte[] { 0x0D, ackType, 0x00, 0x0A };
315 if (logger.isDebugEnabled()) {
316 logger.debug("sendAck(): sending message {}", HexUtils.bytesToHex(ackData));
318 boolean done = sendMessage(ackData);
320 logger.debug("sendAck(): failed");
326 * Send a message to the Powermax alarm panel to change arm mode
328 * @param armMode the arm mode
329 * @param pinCode the PIN code. A string of 4 characters is expected
331 * @return true if the message was sent or false if not
333 public boolean requestArmMode(PowermaxArmMode armMode, String pinCode) {
334 logger.debug("requestArmMode(): armMode = {}", armMode.getShortName());
336 boolean done = false;
337 if (!armMode.isAllowedCommand()) {
338 logger.debug("Powermax alarm binding: requested arm mode {} rejected", armMode.getShortName());
339 } else if (pinCode.length() != 4) {
340 logger.debug("Powermax alarm binding: requested arm mode {} rejected due to invalid PIN code",
341 armMode.getShortName());
344 byte[] dynPart = new byte[3];
345 dynPart[0] = armMode.getCommandCode();
346 dynPart[1] = (byte) Integer.parseInt(pinCode.substring(0, 2), 16);
347 dynPart[2] = (byte) Integer.parseInt(pinCode.substring(2, 4), 16);
349 done = sendMessage(new PowermaxBaseMessage(PowermaxSendType.ARM, dynPart), false, 0, true);
350 } catch (NumberFormatException e) {
351 logger.debug("Powermax alarm binding: requested arm mode {} rejected due to invalid PIN code",
352 armMode.getShortName());
359 * Send a message to the Powermax alarm panel to change PGM or X10 zone state
361 * @param action the requested action. Allowed values are: OFF, ON, DIM, BRIGHT
362 * @param device the X10 device number. null is expected for PGM
364 * @return true if the message was sent or false if not
366 public boolean sendPGMX10(Command action, @Nullable Byte device) {
367 logger.debug("sendPGMX10(): action = {}, device = {}", action, device);
369 boolean done = false;
371 Map<String, Byte> codes = new HashMap<>();
372 codes.put("OFF", (byte) 0x00);
373 codes.put("ON", (byte) 0x01);
374 codes.put("DIM", (byte) 0x0A);
375 codes.put("BRIGHT", (byte) 0x0B);
377 Byte code = codes.get(action.toString());
379 logger.debug("Powermax alarm binding: invalid PGM/X10 command: {}", action);
380 } else if ((device != null) && ((device < 1) || (device >= panelSettings.getNbPGMX10Devices()))) {
381 logger.debug("Powermax alarm binding: invalid X10 device id: {}", device);
383 int val = (device == null) ? 1 : (1 << device);
384 byte[] dynPart = new byte[3];
386 dynPart[1] = (byte) (val & 0x000000FF);
387 dynPart[2] = (byte) (val >> 8);
389 done = sendMessage(new PowermaxBaseMessage(PowermaxSendType.X10PGM, dynPart), false, 0);
395 * Send a message to the Powermax alarm panel to bypass a zone or to not bypass a zone
397 * @param bypass true to bypass the zone; false to not bypass the zone
398 * @param zone the zone number (first zone is number 1)
399 * @param pinCode the PIN code. A string of 4 characters is expected
401 * @return true if the message was sent or false if not
403 public boolean sendZoneBypass(boolean bypass, byte zone, String pinCode) {
404 logger.debug("sendZoneBypass(): bypass = {}, zone = {}", bypass ? "true" : "false", zone);
406 boolean done = false;
408 if (pinCode.length() != 4) {
409 logger.debug("Powermax alarm binding: zone bypass rejected due to invalid PIN code");
410 } else if ((zone < 1) || (zone > panelSettings.getNbZones())) {
411 logger.debug("Powermax alarm binding: invalid zone number: {}", zone);
414 int val = (1 << (zone - 1));
416 byte[] dynPart = new byte[10];
417 dynPart[0] = (byte) Integer.parseInt(pinCode.substring(0, 2), 16);
418 dynPart[1] = (byte) Integer.parseInt(pinCode.substring(2, 4), 16);
420 for (i = 2; i < 10; i++) {
424 dynPart[i++] = (byte) (val & 0x000000FF);
425 dynPart[i++] = (byte) ((val >> 8) & 0x000000FF);
426 dynPart[i++] = (byte) ((val >> 16) & 0x000000FF);
427 dynPart[i++] = (byte) ((val >> 24) & 0x000000FF);
429 done = sendMessage(new PowermaxBaseMessage(PowermaxSendType.BYPASS, dynPart), false, 0, true);
431 done = sendMessage(new PowermaxBaseMessage(PowermaxSendType.BYPASSTAT), false, 0);
433 } catch (NumberFormatException e) {
434 logger.debug("Powermax alarm binding: zone bypass rejected due to invalid PIN code");
441 * Send a message to set the alarm time and date using the system time and date
443 * @return true if the message was sent or false if not
445 public boolean sendSetTime() {
446 logger.debug("sendSetTime()");
448 boolean done = false;
451 GregorianCalendar cal = new GregorianCalendar();
452 if (cal.get(Calendar.YEAR) >= 2000) {
453 logger.debug("sendSetTime(): sync time {}",
454 String.format("%02d/%02d/%04d %02d:%02d:%02d", cal.get(Calendar.DAY_OF_MONTH),
455 cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR), cal.get(Calendar.HOUR_OF_DAY),
456 cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND)));
458 byte[] dynPart = new byte[6];
459 dynPart[0] = (byte) cal.get(Calendar.SECOND);
460 dynPart[1] = (byte) cal.get(Calendar.MINUTE);
461 dynPart[2] = (byte) cal.get(Calendar.HOUR_OF_DAY);
462 dynPart[3] = (byte) cal.get(Calendar.DAY_OF_MONTH);
463 dynPart[4] = (byte) (cal.get(Calendar.MONTH) + 1);
464 dynPart[5] = (byte) (cal.get(Calendar.YEAR) - 2000);
466 done = sendMessage(new PowermaxBaseMessage(PowermaxSendType.SETTIME, dynPart), false, 0);
468 cal.set(Calendar.MILLISECOND, 0);
469 syncTimeCheck = cal.getTimeInMillis();
472 "Powermax alarm binding: time not synchronized; please correct the date/time of your openHAB server");
482 * Send a message to the Powermax alarm panel to get all the event logs
484 * @param pinCode the PIN code. A string of 4 characters is expected
486 * @return true if the message was sent or false if not
488 public boolean requestEventLog(String pinCode) {
489 logger.debug("requestEventLog()");
491 boolean done = false;
493 if (pinCode.length() != 4) {
494 logger.debug("Powermax alarm binding: requested event log rejected due to invalid PIN code");
497 byte[] dynPart = new byte[3];
498 dynPart[0] = (byte) Integer.parseInt(pinCode.substring(0, 2), 16);
499 dynPart[1] = (byte) Integer.parseInt(pinCode.substring(2, 4), 16);
501 done = sendMessage(new PowermaxBaseMessage(PowermaxSendType.EVENTLOG, dynPart), false, 0, true);
502 } catch (NumberFormatException e) {
503 logger.debug("Powermax alarm binding: requested event log rejected due to invalid PIN code");
510 * Start downloading panel setup
512 * @return true if the message was sent or the sending is delayed; false in other cases
514 public synchronized boolean startDownload() {
515 if (downloadRunning) {
518 lastTimeDownloadRequested = System.currentTimeMillis();
519 downloadRunning = true;
520 return sendMessage(PowermaxSendType.DOWNLOAD);
525 * Act the exit of the panel setup
527 public synchronized void exitDownload() {
528 downloadRunning = false;
531 public void retryDownloadSetup(int remainingAttempts) {
532 long now = System.currentTimeMillis();
533 if ((remainingAttempts > 0) && !isDownloadRunning() && ((lastTimeDownloadRequested == 0)
534 || ((now - lastTimeDownloadRequested) >= DELAY_BETWEEN_SETUP_DOWNLOADS))) {
535 // We wait at least 45 seconds before each retry to download the panel setup
536 logger.debug("Powermax alarm binding: try again downloading setup");
541 public void getInfosWhenInStandardMode() {
542 sendMessage(PowermaxSendType.ZONESNAME);
543 sendMessage(PowermaxSendType.ZONESTYPE);
544 sendMessage(PowermaxSendType.STATUS);
547 public void sendRestoreMessage() {
548 sendMessage(PowermaxSendType.RESTORE);
552 * @return true if a download of the panel setup is in progress
554 public boolean isDownloadRunning() {
555 return downloadRunning;
559 * @return the time in milliseconds the last download of the panel setup was requested or 0 if not yet requested
561 public long getLastTimeDownloadRequested() {
562 return lastTimeDownloadRequested;
566 * Send an ENROLL message
568 * @return true if the message was sent or the sending is delayed; false in other cases
570 public boolean enrollPowerlink() {
571 return sendMessage(new PowermaxBaseMessage(PowermaxSendType.ENROLL), true, 0);
575 * Send a message or delay the sending if time frame for receiving response is not ended
577 * @param msgType the message type to be sent
579 * @return true if the message was sent or the sending is delayed; false in other cases
581 public boolean sendMessage(PowermaxSendType msgType) {
582 return sendMessage(new PowermaxBaseMessage(msgType), false, 0);
586 * Delay the sending of a message
588 * @param msgType the message type to be sent
589 * @param waitTime the delay in seconds to wait
591 * @return true if the sending is delayed; false in other cases
593 public boolean sendMessageLater(PowermaxSendType msgType, int waitTime) {
594 return sendMessage(new PowermaxBaseMessage(msgType), false, waitTime);
597 private synchronized boolean sendMessage(@Nullable PowermaxBaseMessage msg, boolean immediate, int waitTime) {
598 return sendMessage(msg, immediate, waitTime, false);
602 * Send a message or delay the sending if time frame for receiving response is not ended
604 * @param msg the message to be sent
605 * @param immediate true if the message has to be send without considering timing
606 * @param waitTime the delay in seconds to wait
607 * @param doNotLog true if the message contains data that must not be logged
609 * @return true if the message was sent or the sending is delayed; false in other cases
611 @SuppressWarnings("PMD.CompareObjectsWithEquals")
612 private synchronized boolean sendMessage(@Nullable PowermaxBaseMessage msg, boolean immediate, int waitTime,
614 if ((waitTime > 0) && (msg != null)) {
615 logger.debug("sendMessage(): delay ({} s) sending message (type {})", waitTime, msg.getSendType());
616 // Don't queue the message
617 PowermaxBaseMessage msgToSendLater = new PowermaxBaseMessage(msg.getRawData());
618 msgToSendLater.setSendType(msg.getSendType());
619 scheduler.schedule(() -> {
620 sendMessage(msgToSendLater, false, 0);
621 }, waitTime, TimeUnit.SECONDS);
626 msg = msgQueue.peek();
628 logger.debug("sendMessage(): nothing to send");
633 // Delay sending if time frame for receiving response is not ended
634 long delay = WAITING_DELAY_FOR_RESPONSE - (System.currentTimeMillis() - connector.getWaitingForResponse());
636 PowermaxBaseMessage msgToSend = msg;
639 msgToSend = msgQueue.peek();
640 if (msgToSend != msg) {
641 logger.debug("sendMessage(): add message in queue (type {})", msg.getSendType());
643 msgToSend = msgQueue.peek();
645 if ((msgToSend != msg) && (delay > 0)) {
647 } else if ((msgToSend == msg) && (delay > 0)) {
651 logger.debug("sendMessage(): delay ({} ms) sending message (type {})", delay, msgToSend.getSendType());
652 scheduler.schedule(() -> {
653 sendMessage(null, false, 0);
654 }, delay, TimeUnit.MILLISECONDS);
657 msgToSend = msgQueue.poll();
661 if (logger.isDebugEnabled()) {
662 logger.debug("sendMessage(): sending {} message {}", msgToSend.getSendType(),
663 doNotLog ? "***" : HexUtils.bytesToHex(msgToSend.getRawData()));
665 boolean done = sendMessage(msgToSend.getRawData());
667 lastSendMsg = msgToSend;
668 connector.setWaitingForResponse(System.currentTimeMillis());
670 if (!immediate && (msgQueue.peek() != null)) {
671 logger.debug("sendMessage(): delay sending next message (type {})", msgQueue.peek().getSendType());
672 scheduler.schedule(() -> {
673 sendMessage(null, false, 0);
674 }, WAITING_DELAY_FOR_RESPONSE, TimeUnit.MILLISECONDS);
677 logger.debug("sendMessage(): failed");
684 * Send a message to the Powermax alarm panel
686 * @param data the data buffer containing the message to be sent
688 * @return true if the message was sent or false if not
690 private boolean sendMessage(byte[] data) {
691 boolean done = false;
693 data[data.length - 2] = computeCRC(data, data.length);
694 connector.sendMessage(data);
695 done = connector.isConnected();
697 logger.debug("sendMessage(): aborted (not connected)");