100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Added Z-Wave protocol
Rainer Hitzfbd12d48e8b9
diff --git a/agent/src/main/java/org/openremote/agent/protocol/zwave/ChannelConsumerLink.java b/agent/src/main/java/org/openremote/agent/protocol/zwave/ChannelConsumerLink.javanew file mode 100644index 000000000..a3470ac14--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/zwave/ChannelConsumerLink.java@@ -0,0 +1,104 @@+/*+ * Copyright 2019, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.agent.protocol.zwave;++import org.openremote.protocol.zwave.model.Controller;+import org.openremote.protocol.zwave.model.ControllerListener;+import org.openremote.protocol.zwave.model.ZWaveNode;+import org.openremote.protocol.zwave.model.commandclasses.channel.Channel;+import org.openremote.protocol.zwave.model.commandclasses.channel.ChannelListener;+import org.openremote.protocol.zwave.model.commandclasses.channel.value.Value;++import java.util.function.Consumer;++public class ChannelConsumerLink implements ChannelListener, ControllerListener {++ public static ChannelConsumerLink createLink(int nodeId, int endpoint, String channelName, Consumer<Value> consumer, Controller controller) {+ Channel channel = null;+ channel = controller.findChannel(nodeId, endpoint, channelName);+ ChannelConsumerLink link = new ChannelConsumerLink(nodeId, endpoint, channelName, channel, consumer, controller);+ if (channel != null) {+ channel.addValueListener(link);+ }+ controller.addListener(link);+ return link;+ }++ private final Consumer<Value> consumer;+ private Channel channel;+ private final Controller controller;+ private final int nodeId;+ private final int endpoint;+ private final String channelName;++ private ChannelConsumerLink(int nodeId, int endpoint, String channelName, Channel channel, Consumer<Value> consumer, Controller controller) {+ this.nodeId = nodeId;+ this.endpoint = endpoint;+ this.channelName = channelName;+ this.channel = channel;+ this.consumer = consumer;+ this.controller = controller;+ }+++ // Implements ChannelListener -----------------------------------------------------------------++ @Override+ public synchronized void valueHasChanged(Channel channel, Value channelValue) {+ consumer.accept(channelValue);+ }+++ // Implements ControllerListener --------------------------------------------------------------++ @Override+ public synchronized void onNodeAdded(ZWaveNode node) {+ if (channel == null && nodeId == node.getNodeID()) {+ channel = controller.findChannel(nodeId, endpoint, channelName);+ if (channel != null) {+ channel.addValueListener(this);+ }+ }+ }++ @Override+ public synchronized void onNodeRemoved(ZWaveNode node) {+ if (nodeId == node.getNodeID()) {+ if (channel != null) {+ channel.removeValueListener(this);+ }+ controller.removeListener(this);+ }+ }+++ // Public Methods -----------------------------------------------------------------------------++ public synchronized Channel getChannel() {+ return channel;+ }++ public synchronized void unlink() {+ if (channel != null) {+ channel.removeValueListener(this);+ }+ controller.removeListener(this);+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/zwave/NettyConnectionManager.java b/agent/src/main/java/org/openremote/agent/protocol/zwave/NettyConnectionManager.javanew file mode 100644index 000000000..78f8bc14a--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/zwave/NettyConnectionManager.java@@ -0,0 +1,47 @@+/*+ * Copyright 2019, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.agent.protocol.zwave;++import org.openremote.agent.protocol.io.IoClient;+import org.openremote.protocol.zwave.DefaultZWConnectionManager;+import org.openremote.protocol.zwave.port.TransportLayer;+import org.openremote.protocol.zwave.port.ZWavePortConfiguration;++public class NettyConnectionManager extends DefaultZWConnectionManager {++ public static NettyConnectionManager create(ZWavePortConfiguration configuration, IoClient<SerialDataPacket> messageProcessor) {+ NettyConnectionManager mgr = new NettyConnectionManager(configuration, messageProcessor);+ mgr.createControllerAPI();+ mgr.addShutdownHook();+ return mgr;+ }++ private final IoClient<SerialDataPacket> ioClient;++ protected NettyConnectionManager(ZWavePortConfiguration configuration, IoClient<SerialDataPacket> ioClient) {+ super(configuration);+ this.ioClient = ioClient;+ }++ @Override+ protected TransportLayer createTransportLayer(ZWavePortConfiguration configuration) {+ return new NettyTransportLayer(ioClient);+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/zwave/NettyTransportLayer.java b/agent/src/main/java/org/openremote/agent/protocol/zwave/NettyTransportLayer.javanew file mode 100644index 000000000..761d49b0d--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/zwave/NettyTransportLayer.java@@ -0,0 +1,171 @@+/*+ * Copyright 2019, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.agent.protocol.zwave;++import org.openremote.agent.protocol.io.IoClient;+import org.openremote.controller.exception.ConfigurationException;+import org.openremote.controller.protocol.zwave.ZWaveCommandBuilder;+import org.openremote.controller.utils.Logger;+import org.openremote.model.asset.agent.ConnectionStatus;+import org.openremote.protocol.zwave.LoggerUtil;+import org.openremote.protocol.zwave.port.SessionLayer;+import org.openremote.protocol.zwave.port.TransportLayer;+import org.openremote.protocol.zwave.port.TransportLayerListener;++/**+ * Serial port implementation based on the Netty framework.+ *+ * @see TransportLayer+ * @see TransportLayerListener+ * @see SessionLayer+ *+ * @author <a href="mailto:[email protected]">Rainer Hitz</a>+ */+public class NettyTransportLayer implements TransportLayer {++ // Constants ----------------------------------------------------------------------------------++ public static final String SERIAL_PORT_LOG_HEADER = "Serial_Port : ";+++ // Class Members ------------------------------------------------------------------------------++ /**+ * Z-Wave logger. Uses a common category for all Z-Wave related logging.+ */+ private final static Logger log = Logger.getLogger(ZWaveCommandBuilder.ZWAVE_LOG_CATEGORY);+++ // Private Instance Fields --------------------------------------------------------------------++ private final IoClient<SerialDataPacket> ioClient;++ private volatile TransportLayerListener listener;+++ // Constructors -------------------------------------------------------------------------------++ public NettyTransportLayer(IoClient<SerialDataPacket> ioClient) {+ if (ioClient == null) {+ throw new IllegalArgumentException("Missing I/O client.");+ }+ this.ioClient = ioClient;+ this.ioClient.addMessageConsumer(this::onPacketReceived);+ this.ioClient.addConnectionStatusConsumer(this::onConnectionStatusUpdate);+ }+++ // Implements TransportLayer ------------------------------------------------------------------++ @Override+ public void open() throws ConfigurationException {+ try {+ ioClient.connect();+ } catch (Exception e) {+ String serialPort = "";+ if (ioClient instanceof ZWSerialClient) {+ serialPort = ((ZWSerialClient) ioClient).getSerialPort();+ }+ ConfigurationException configException = new ConfigurationException("Failed to open serial port " + serialPort, e);+ log.warn(configException.getMessage(), configException);+ throw configException;+ }+ }++ @Override+ public void close() {+ ioClient.disconnect();+ }++ @Override+ public void setListener(TransportLayerListener listener) {+ this.listener = listener;+ }++ @Override+ public void write(byte[] data) {+ if (ioClient.getConnectionStatus() == ConnectionStatus.CONNECTED) {+ logDataBytes(data, true);+ if (data.length > 0) {+ SerialDataPacket dataPacket = new SerialDataPacket(data);+ ioClient.sendMessage(dataPacket);+ }+ }+ }+++ // Protected Instance Methods -----------------------------------------------------------------++ protected void onPacketReceived(SerialDataPacket packet) {+ if (listener != null) {+ byte[] data = packet.getData();+ logDataBytes(data, false);+ listener.dataReceived(data);+ }+ }++ protected void onConnectionStatusUpdate(ConnectionStatus connectionStatus) {+ if (listener != null) {+ switch(connectionStatus) {+ case CONNECTING:+ listener.onConnectionStatusChanged(org.openremote.protocol.zwave.port.ConnectionStatus.CONNECTING);+ break;+ case CONNECTED:+ listener.onConnectionStatusChanged(org.openremote.protocol.zwave.port.ConnectionStatus.CONNECTED);+ break;+ case DISCONNECTING:+ listener.onConnectionStatusChanged(org.openremote.protocol.zwave.port.ConnectionStatus.DISCONNECTING);+ break;+ case DISCONNECTED:+ listener.onConnectionStatusChanged(org.openremote.protocol.zwave.port.ConnectionStatus.DISCONNECTED);+ break;+ case ERROR:+ listener.onConnectionStatusChanged(org.openremote.protocol.zwave.port.ConnectionStatus.ERROR);+ break;+ case ERROR_CONFIGURATION:+ listener.onConnectionStatusChanged(org.openremote.protocol.zwave.port.ConnectionStatus.ERROR_CONFIGURATION);+ break;+ }+ }+ }++ private void logDataBytes(byte[] data, boolean isTransmit) {+ if (data == null || data.length == 0) {+ return;+ }+ StringBuilder builder = new StringBuilder();+ builder.append("[");++ for(int i = 0; i < data.length; i++) {+ if (i > 0) {+ builder.append(", ");+ }+ builder.append(String.format("0x%02X", data[i] & 0xFF));+ }++ builder.append("]");++ LoggerUtil.debug(+ SERIAL_PORT_LOG_HEADER ++ (isTransmit ? "Data bytes transmitted (TX) : {0}" : "Data bytes received (RX) : {0}"),+ builder.toString()+ );+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/zwave/NettyZWControllerFactory.java b/agent/src/main/java/org/openremote/agent/protocol/zwave/NettyZWControllerFactory.javanew file mode 100644index 000000000..ce4430e96--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/zwave/NettyZWControllerFactory.java@@ -0,0 +1,56 @@+/*+ * Copyright 2019, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.agent.protocol.zwave;++import io.netty.channel.ChannelHandler;+import org.openremote.agent.protocol.ProtocolExecutorService;+import org.openremote.agent.protocol.io.AbstractNettyIoClient;+import org.openremote.agent.protocol.io.IoClient;+import org.openremote.protocol.zwave.model.Controller;+import org.openremote.protocol.zwave.port.ZWavePortConfiguration;++public class NettyZWControllerFactory implements ZWControllerFactory {++ private final ProtocolExecutorService executorService;+ private final ZWavePortConfiguration configuration;++ public NettyZWControllerFactory(ZWavePortConfiguration configuration, ProtocolExecutorService executorService) {+ this.configuration = configuration;+ this.executorService = executorService;+ }++ @Override+ public Controller createController(IoClient<SerialDataPacket> messageProcessor) {+ return new Controller(NettyConnectionManager.create(configuration, messageProcessor));+ }++ @Override+ public IoClient<SerialDataPacket> createMessageProcessor() {+ ZWSerialClient client = new ZWSerialClient(configuration.getComPort(), 115200, executorService);+ client.setEncoderDecoderProvider(+ () -> new ChannelHandler[] {+ new ZWPacketEncoder(),+ new ZWPacketDecoder(),+ new AbstractNettyIoClient.MessageToMessageDecoder<>(SerialDataPacket.class, client)+ }+ );+ return client;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/zwave/SerialDataPacket.java b/agent/src/main/java/org/openremote/agent/protocol/zwave/SerialDataPacket.javanew file mode 100644index 000000000..3a15c375c--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/zwave/SerialDataPacket.java@@ -0,0 +1,35 @@+/*+ * Copyright 2019, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.agent.protocol.zwave;++import java.util.Arrays;++public class SerialDataPacket {++ private final byte[] data;++ public SerialDataPacket(final byte[] data) {+ this.data = Arrays.copyOf(data, data.length);+ }++ public byte[] getData() {+ return data;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/zwave/TypeMapper.java b/agent/src/main/java/org/openremote/agent/protocol/zwave/TypeMapper.javanew file mode 100644index 000000000..b0a2d0bfa--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/zwave/TypeMapper.java@@ -0,0 +1,692 @@+/*+ * Copyright 2018, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.agent.protocol.zwave;++import org.openremote.model.Constants;+import org.openremote.model.attribute.AttributeValueDescriptor;+import org.openremote.model.attribute.AttributeValueType;+import org.openremote.model.attribute.MetaItem;+import org.openremote.model.attribute.MetaItemType;+import org.openremote.protocol.zwave.model.commandclasses.channel.ChannelType;++import java.util.ArrayList;+import java.util.Arrays;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.logging.Logger;++public class TypeMapper {++ private static final Logger LOG = Logger.getLogger(TypeMapper.class.getName());++ static private Map<ChannelType, AttributeValueDescriptor> typeMap = new HashMap<>();++ static private Map<ChannelType, List<MetaItem>> metaItemMap = new HashMap<>();++ static {++ // Basic types++ typeMap.put(ChannelType.INTEGER, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.NUMBER, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.STRING, AttributeValueType.STRING);+ typeMap.put(ChannelType.BOOLEAN, AttributeValueType.BOOLEAN);+ typeMap.put(ChannelType.ARRAY, AttributeValueType.ARRAY);++ // COMMAND_CLASS_SENSOR_MULTILEVEL++ typeMap.put(ChannelType.TEMPERATURE_CELSIUS, AttributeValueType.TEMPERATURE);+ typeMap.put(ChannelType.TEMPERATURE_FAHRENHEIT, AttributeValueType.TEMPERATURE);+ typeMap.put(ChannelType.PERCENTAGE, AttributeValueType.PERCENTAGE);+ typeMap.put(ChannelType.LUMINANCE_PERCENTAGE, AttributeValueType.PERCENTAGE);+ typeMap.put(ChannelType.LUMINANCE_LUX, AttributeValueType.BRIGHTNESS);+ typeMap.put(ChannelType.POWER_WATT, AttributeValueType.POWER);+ typeMap.put(ChannelType.POWER_BTU_H, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.HUMIDITY_PERCENTAGE, AttributeValueType.HUMIDITY);+ typeMap.put(ChannelType.HUMIDITY_ABSOLUTE, AttributeValueType.HUMIDITY);+ typeMap.put(ChannelType.SPEED_MS, AttributeValueType.SPEED);+ typeMap.put(ChannelType.SPEED_MPH, AttributeValueType.SPEED);+ typeMap.put(ChannelType.DIRECTION_DECIMAL_DEGREES, AttributeValueType.DIRECTION);+ typeMap.put(ChannelType.PRESSURE_KPA, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.PRESSURE_IN_HG, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.SOLAR_RADIATION_WATT_M2, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.DEW_POINT_CELSIUS, AttributeValueType.TEMPERATURE);+ typeMap.put(ChannelType.DEW_POINT_FAHRENHEIT, AttributeValueType.TEMPERATURE);+ typeMap.put(ChannelType.RAINFALL_MMPH, AttributeValueType.RAINFALL);+ typeMap.put(ChannelType.RAINFALL_INPH, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.TIDE_LEVEL_M, AttributeValueType.DISTANCE);+ typeMap.put(ChannelType.TIDE_LEVEL_FT, AttributeValueType.DISTANCE);+ typeMap.put(ChannelType.WEIGHT_KG, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.WEIGHT_LB, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.VOLTAGE_V, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.VOLTAGE_MV, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.CURRENT_A, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.CURRENT_MA, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.CO2_PPM, AttributeValueType.CO2);+ typeMap.put(ChannelType.AIR_FLOW_CMPH, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.AIR_FLOW_CFTPM, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.TANK_CAPACITY_L, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.TANK_CAPACITY_CBM, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.TANK_CAPACITY_GAL, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.DISTANCE_M, AttributeValueType.DISTANCE);+ typeMap.put(ChannelType.DISTANCE_CM, AttributeValueType.DISTANCE);+ typeMap.put(ChannelType.DISTANCE_FT, AttributeValueType.DISTANCE);+ typeMap.put(ChannelType.ANGLE_POSITION_PERCENT, AttributeValueType.PERCENTAGE);+ typeMap.put(ChannelType.ANGLE_POSITION_DEGREE_NORTH_POLE, AttributeValueType.DIRECTION);+ typeMap.put(ChannelType.ANGLE_POSITION_DEGREE_SOUTH_POLE, AttributeValueType.DIRECTION);+ typeMap.put(ChannelType.ROTATION_HZ, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.ROTATION_RPM, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.WATER_TEMPERATURE_CELSIUS, AttributeValueType.TEMPERATURE);+ typeMap.put(ChannelType.WATER_TEMPERATURE_FAHRENHEIT, AttributeValueType.TEMPERATURE);+ typeMap.put(ChannelType.SOIL_TEMPERATURE_CELSIUS, AttributeValueType.TEMPERATURE);+ typeMap.put(ChannelType.SOIL_TEMPERATURE_FAHRENHEIT, AttributeValueType.TEMPERATURE);+ typeMap.put(ChannelType.SEISMIC_INTENSITY_MERCALLI, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.SEISMIC_INTENSITY_EU_MACROSEISMIC, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.SEISMIC_INTENSITY_LIEDU, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.SEISMIC_INTENSITY_SHINDO, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.SEISMIC_MAGNITUDE_LOCAL, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.SEISMIC_MAGNITUDE_MOMENT, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.SEISMIC_MAGNITUDE_SURFACE_WAVE, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.SEISMIC_MAGNITUDE_BODY_WAVE, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.ULTRAVIOLET_UV_INDEX, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.RESISTIVITY_OHM, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.CONDUCTIVITY_SPM, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.LOUDNESS_DB, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.LOUDNESS_DBA, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.MOISTURE_PERCENTAGE, AttributeValueType.PERCENTAGE);+ typeMap.put(ChannelType.MOISTURE_VOLUME_WATER_CONTENT, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.MOISTURE_IMPEDANCE, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.MOISTURE_WATER_ACTIVITY, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.FREQUENCY_HZ, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.FREQUENCY_KHZ, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.TIME_SECONDS, AttributeValueType.TIMESTAMP);+ typeMap.put(ChannelType.TARGET_TEMPERATUE_CELSIUS, AttributeValueType.TEMPERATURE);+ typeMap.put(ChannelType.TARGET_TEMPERATUE_FAHRENHEIT, AttributeValueType.TEMPERATURE);+ typeMap.put(ChannelType.PARTICULATE_MATTER_2_5_MOLPCM, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.PARTICULATE_MATTER_2_5_MCGPCM, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.FORMALDEHYDE_LEVEL_MOLPCM, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.RADON_CONCENTRATION_BQPCM, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.RADON_CONCENTRATION_PCIPL, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.METHANE_DENSITY_MOLPCM, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.VOLATILE_ORGANIC_COMPOUND_MOLPCM, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.VOLATILE_ORGANIC_COMPOUND_PPM, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.CO_MOLPCM, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.CO_PPM, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.SOIL_HUMIDITY_PERCENTAGE, AttributeValueType.PERCENTAGE);+ typeMap.put(ChannelType.SOIL_REACTIVITY_PH, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.SOIL_SALINITY_MOLPCM, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.HEART_RATE_BPM, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.BLOOD_PRESSURE_SYSTOLIC, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.BLOOD_PRESSURE_DIASTOLIC, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.MUSCLE_MASS_KG, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.FAT_MASS_KG, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.BONE_MASS_KG, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.TOTAL_BODY_WATER_KG, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.BASIC_METABOLIC_RATE_JOULE, AttributeValueType.ENERGY);+ typeMap.put(ChannelType.BODY_MASS_INDEX, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.ACCELERATION_X_MPSS, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.ACCELERATION_Y_MPSS, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.ACCELERATION_Z_MPSS, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.SMOKE_DENSITY_PERCENTAGE, AttributeValueType.PERCENTAGE);+ typeMap.put(ChannelType.WATER_FLOW_LPH, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.WATER_PRESSURE_KPA, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.RF_SIGNAL_STRENGTH_RSSI, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.RF_SIGNAL_STRENGTH_DBM, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.PARTICULATE_MATTER_MOLPCM, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.PARTICULATE_MATTER_MCGPCM, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.RESPIRATORY_RATE_BPM, AttributeValueType.NUMBER);++ // COMMAND_CLASS_METER++ // Electric Meter+ typeMap.put(ChannelType.ELECTRIC_METER_ENERGY_KWH, AttributeValueType.ENERGY);+ typeMap.put(ChannelType.ELECTRIC_METER_ENERGY_KVAH, AttributeValueType.ENERGY);+ typeMap.put(ChannelType.ELECTRIC_METER_POWER_W, AttributeValueType.POWER);+ typeMap.put(ChannelType.ELECTRIC_METER_PULSE_COUNT, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.ELECTRIC_METER_VOLTAGE_V, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.ELECTRIC_METER_CURRENT_A, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.ELECTRIC_METER_POWER_FACTOR, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.ELECTRIC_METER_POWER_KVAR, AttributeValueType.POWER);+ typeMap.put(ChannelType.ELECTRIC_METER_ENERGY_KVARH, AttributeValueType.ENERGY);++ // Gas Meter+ typeMap.put(ChannelType.GAS_METER_VOLUME_CM, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.GAS_METER_VOLUME_CFT, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.GAS_METER_PULSE_COUNT, AttributeValueType.NUMBER);++ // Water Meter+ typeMap.put(ChannelType.WATER_METER_VOLUME_CM, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.WATER_METER_VOLUME_CFT, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.WATER_METER_VOLUME_GAL, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.WATER_METER_PULSE_COUNT, AttributeValueType.NUMBER);++ // COMMAND_CLASS_COLOR_CONTROL++ typeMap.put(ChannelType.COLOR_WARM_WHITE, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.COLOR_COLD_WHITE, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.COLOR_RED, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.COLOR_GREEN, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.COLOR_BLUE, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.COLOR_AMBER, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.COLOR_CYAN, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.COLOR_PURPLE, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.COLOR_INDEXED, AttributeValueType.NUMBER);+ typeMap.put(ChannelType.COLOR_RGB, AttributeValueType.COLOR_RGB);+ typeMap.put(ChannelType.COLOR_ARGB, AttributeValueType.COLOR_ARGB);++ // COMMAND_CLASS_SENSOR_ALARM++ typeMap.put(ChannelType.GENERAL_PURPOSE_ALARM, AttributeValueType.BOOLEAN);+ typeMap.put(ChannelType.SMOKE_ALARM, AttributeValueType.BOOLEAN);+ typeMap.put(ChannelType.CO_ALARM, AttributeValueType.BOOLEAN);+ typeMap.put(ChannelType.CO2_ALARM, AttributeValueType.BOOLEAN);+ typeMap.put(ChannelType.HEAT_ALARM, AttributeValueType.BOOLEAN);+ typeMap.put(ChannelType.WATER_LEAK_ALARM, AttributeValueType.BOOLEAN);+ typeMap.put(ChannelType.FIRST_SUPPORTED_ALARM, AttributeValueType.BOOLEAN);++ // COMMAND_CLASS_BATTERY++ typeMap.put(ChannelType.CHARGE_PERCENTAGE, AttributeValueType.PERCENTAGE);++ // COMMAND_CLASS_CLOCK++ typeMap.put(ChannelType.DATETIME, AttributeValueType.TIMESTAMP_ISO8601);++++ // Basic types++ metaItemMap.put(ChannelType.INTEGER, new ArrayList<>());+ metaItemMap.put(ChannelType.NUMBER, new ArrayList<>());+ metaItemMap.put(ChannelType.STRING, new ArrayList<>());+ metaItemMap.put(ChannelType.BOOLEAN, new ArrayList<>());+ metaItemMap.put(ChannelType.ARRAY, new ArrayList<>());++ // COMMAND_CLASS_SENSOR_MULTILEVEL++ metaItemMap.put(+ ChannelType.TEMPERATURE_CELSIUS,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue(Constants.UNITS_TEMPERATURE_CELCIUS)),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.1f C"))+ }+ )+ );+ metaItemMap.put(+ ChannelType.TEMPERATURE_FAHRENHEIT,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue("FAHRENHEIT")),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.1f F"))+ }+ )+ );+ metaItemMap.put(ChannelType.PERCENTAGE, new ArrayList<>());+ metaItemMap.put(ChannelType.LUMINANCE_PERCENTAGE, new ArrayList<>());+ metaItemMap.put(+ ChannelType.LUMINANCE_LUX,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue("LUX")),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%d lx"))+ }+ )+ );+ metaItemMap.put(+ ChannelType.POWER_WATT,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue("WATT")),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.5f W"))+ }+ )+ );+ metaItemMap.put(ChannelType.POWER_BTU_H, new ArrayList<>());+ metaItemMap.put(+ ChannelType.HUMIDITY_PERCENTAGE,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue("PERCENTAGE")),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%3d %%"))+ }+ )+ );+ metaItemMap.put(ChannelType.HUMIDITY_ABSOLUTE, new ArrayList<>());+ metaItemMap.put(+ ChannelType.SPEED_MS,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue(Constants.UNITS_SPEED_MPS)),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.3f m/s"))+ }+ )+ );+ metaItemMap.put(+ ChannelType.SPEED_MPH,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue("SPEED_MPH")),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.1f mi/h"))+ }+ )+ );+ metaItemMap.put(+ ChannelType.DIRECTION_DECIMAL_DEGREES,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue(Constants.UNITS_DIRECTION_DEGREES)),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.1f deg"))+ }+ )+ );+ metaItemMap.put(ChannelType.PRESSURE_KPA, new ArrayList<>());+ metaItemMap.put(ChannelType.PRESSURE_IN_HG, new ArrayList<>());+ metaItemMap.put(ChannelType.SOLAR_RADIATION_WATT_M2, new ArrayList<>());+ metaItemMap.put(+ ChannelType.DEW_POINT_CELSIUS,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue(Constants.UNITS_TEMPERATURE_CELCIUS)),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.1f C"))+ }+ )+ );+ metaItemMap.put(+ ChannelType.DEW_POINT_FAHRENHEIT,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue("FAHRENHEIT")),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.1f F"))+ }+ )+ );+ metaItemMap.put(+ ChannelType.RAINFALL_MMPH,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue("RAINFALL_MMPH")),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.1f mm/h"))+ }+ )+ );+ metaItemMap.put(ChannelType.RAINFALL_INPH, new ArrayList<>());+ metaItemMap.put(+ ChannelType.TIDE_LEVEL_M,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue("TIDE_LEVEL_M")),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.5f m"))+ }+ )+ );+ metaItemMap.put(+ ChannelType.TIDE_LEVEL_FT,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue("TIDE_LEVEL_FT")),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.5f '"))+ }+ )+ );+ metaItemMap.put(ChannelType.WEIGHT_KG, new ArrayList<>());+ metaItemMap.put(ChannelType.WEIGHT_LB, new ArrayList<>());+ metaItemMap.put(ChannelType.VOLTAGE_V, new ArrayList<>());+ metaItemMap.put(ChannelType.VOLTAGE_MV, new ArrayList<>());+ metaItemMap.put(ChannelType.CURRENT_A, new ArrayList<>());+ metaItemMap.put(ChannelType.CURRENT_MA, new ArrayList<>());+ metaItemMap.put(+ ChannelType.CO2_PPM,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue("CO2_PPM")),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%4d ppm"))+ }+ )+ );+ metaItemMap.put(ChannelType.AIR_FLOW_CMPH, new ArrayList<>());+ metaItemMap.put(ChannelType.AIR_FLOW_CFTPM, new ArrayList<>());+ metaItemMap.put(ChannelType.TANK_CAPACITY_L, new ArrayList<>());+ metaItemMap.put(ChannelType.TANK_CAPACITY_CBM, new ArrayList<>());+ metaItemMap.put(ChannelType.TANK_CAPACITY_GAL, new ArrayList<>());+ metaItemMap.put(+ ChannelType.DISTANCE_M,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue("METERS")),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.5f m"))+ }+ )+ );+ metaItemMap.put(+ ChannelType.DISTANCE_CM,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue("CENTIMETERS")),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.5f cm"))+ }+ )+ );+ metaItemMap.put(+ ChannelType.DISTANCE_FT,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue("FEET")),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.5f '"))+ }+ )+ );+ metaItemMap.put(ChannelType.ANGLE_POSITION_PERCENT, new ArrayList<>());+ metaItemMap.put(+ ChannelType.ANGLE_POSITION_DEGREE_NORTH_POLE,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue(Constants.UNITS_DIRECTION_DEGREES)),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.1f deg"))+ }+ )+ );+ metaItemMap.put(+ ChannelType.ANGLE_POSITION_DEGREE_SOUTH_POLE,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue(Constants.UNITS_DIRECTION_DEGREES)),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.1f deg"))+ }+ )+ );+ metaItemMap.put(ChannelType.ROTATION_HZ, new ArrayList<>());+ metaItemMap.put(ChannelType.ROTATION_RPM, new ArrayList<>());+ metaItemMap.put(+ ChannelType.WATER_TEMPERATURE_CELSIUS,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue(Constants.UNITS_TEMPERATURE_CELCIUS)),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.1f C"))+ }+ )+ );+ metaItemMap.put(+ ChannelType.WATER_TEMPERATURE_FAHRENHEIT,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue("FAHRENHEIT")),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.1f F"))+ }+ )+ );+ metaItemMap.put(+ ChannelType.SOIL_TEMPERATURE_CELSIUS,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue(Constants.UNITS_TEMPERATURE_CELCIUS)),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.1f C"))+ }+ )+ );+ metaItemMap.put(+ ChannelType.SOIL_TEMPERATURE_FAHRENHEIT,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue("FAHRENHEIT")),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.1f F"))+ }+ )+ );+ metaItemMap.put(ChannelType.SEISMIC_INTENSITY_MERCALLI, new ArrayList<>());+ metaItemMap.put(ChannelType.SEISMIC_INTENSITY_EU_MACROSEISMIC, new ArrayList<>());+ metaItemMap.put(ChannelType.SEISMIC_INTENSITY_LIEDU, new ArrayList<>());+ metaItemMap.put(ChannelType.SEISMIC_INTENSITY_SHINDO, new ArrayList<>());+ metaItemMap.put(ChannelType.SEISMIC_MAGNITUDE_LOCAL, new ArrayList<>());+ metaItemMap.put(ChannelType.SEISMIC_MAGNITUDE_MOMENT, new ArrayList<>());+ metaItemMap.put(ChannelType.SEISMIC_MAGNITUDE_SURFACE_WAVE, new ArrayList<>());+ metaItemMap.put(ChannelType.SEISMIC_MAGNITUDE_BODY_WAVE, new ArrayList<>());+ metaItemMap.put(ChannelType.ULTRAVIOLET_UV_INDEX, new ArrayList<>());+ metaItemMap.put(ChannelType.RESISTIVITY_OHM, new ArrayList<>());+ metaItemMap.put(ChannelType.CONDUCTIVITY_SPM, new ArrayList<>());+ metaItemMap.put(+ ChannelType.LOUDNESS_DB,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue(Constants.UNITS_SOUND_DECIBELS)),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%d dB"))+ }+ )+ );+ metaItemMap.put(+ ChannelType.LOUDNESS_DBA,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue(Constants.UNITS_SOUND_DECIBELS)),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%d dBA"))+ }+ )+ );+ metaItemMap.put(ChannelType.MOISTURE_PERCENTAGE, new ArrayList<>());+ metaItemMap.put(ChannelType.MOISTURE_VOLUME_WATER_CONTENT, new ArrayList<>());+ metaItemMap.put(ChannelType.MOISTURE_IMPEDANCE, new ArrayList<>());+ metaItemMap.put(ChannelType.MOISTURE_WATER_ACTIVITY, new ArrayList<>());+ metaItemMap.put(ChannelType.FREQUENCY_HZ, new ArrayList<>());+ metaItemMap.put(ChannelType.FREQUENCY_KHZ, new ArrayList<>());+ metaItemMap.put(+ ChannelType.TIME_SECONDS,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue("SECONDS")),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%d s"))+ }+ )+ );+ metaItemMap.put(+ ChannelType.TARGET_TEMPERATUE_CELSIUS,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue(Constants.UNITS_TEMPERATURE_CELCIUS)),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.1f C"))+ }+ )+ );+ metaItemMap.put(+ ChannelType.TARGET_TEMPERATUE_FAHRENHEIT,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue("FAHRENHEIT")),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.1f F"))+ }+ )+ );+ metaItemMap.put(ChannelType.PARTICULATE_MATTER_2_5_MOLPCM, new ArrayList<>());+ metaItemMap.put(ChannelType.PARTICULATE_MATTER_2_5_MCGPCM, new ArrayList<>());+ metaItemMap.put(ChannelType.FORMALDEHYDE_LEVEL_MOLPCM, new ArrayList<>());+ metaItemMap.put(ChannelType.RADON_CONCENTRATION_BQPCM, new ArrayList<>());+ metaItemMap.put(ChannelType.RADON_CONCENTRATION_PCIPL, new ArrayList<>());+ metaItemMap.put(ChannelType.METHANE_DENSITY_MOLPCM, new ArrayList<>());+ metaItemMap.put(ChannelType.VOLATILE_ORGANIC_COMPOUND_MOLPCM, new ArrayList<>());+ metaItemMap.put(ChannelType.VOLATILE_ORGANIC_COMPOUND_PPM, new ArrayList<>());+ metaItemMap.put(ChannelType.CO_MOLPCM, new ArrayList<>());+ metaItemMap.put(ChannelType.CO_PPM, new ArrayList<>());+ metaItemMap.put(ChannelType.SOIL_HUMIDITY_PERCENTAGE, new ArrayList<>());+ metaItemMap.put(ChannelType.SOIL_REACTIVITY_PH, new ArrayList<>());+ metaItemMap.put(ChannelType.SOIL_SALINITY_MOLPCM, new ArrayList<>());+ metaItemMap.put(ChannelType.HEART_RATE_BPM, new ArrayList<>());+ metaItemMap.put(ChannelType.BLOOD_PRESSURE_SYSTOLIC, new ArrayList<>());+ metaItemMap.put(ChannelType.BLOOD_PRESSURE_DIASTOLIC, new ArrayList<>());+ metaItemMap.put(ChannelType.MUSCLE_MASS_KG, new ArrayList<>());+ metaItemMap.put(ChannelType.FAT_MASS_KG, new ArrayList<>());+ metaItemMap.put(ChannelType.BONE_MASS_KG, new ArrayList<>());+ metaItemMap.put(ChannelType.TOTAL_BODY_WATER_KG, new ArrayList<>());+ metaItemMap.put(+ ChannelType.BASIC_METABOLIC_RATE_JOULE,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue("JOULE")),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.5f J"))+ }+ )+ );+ metaItemMap.put(ChannelType.BODY_MASS_INDEX, new ArrayList<>());+ metaItemMap.put(ChannelType.ACCELERATION_X_MPSS, new ArrayList<>());+ metaItemMap.put(ChannelType.ACCELERATION_Y_MPSS, new ArrayList<>());+ metaItemMap.put(ChannelType.ACCELERATION_Z_MPSS, new ArrayList<>());+ metaItemMap.put(ChannelType.SMOKE_DENSITY_PERCENTAGE, new ArrayList<>());+ metaItemMap.put(ChannelType.WATER_FLOW_LPH, new ArrayList<>());+ metaItemMap.put(ChannelType.WATER_PRESSURE_KPA, new ArrayList<>());+ metaItemMap.put(ChannelType.RF_SIGNAL_STRENGTH_RSSI, new ArrayList<>());+ metaItemMap.put(ChannelType.RF_SIGNAL_STRENGTH_DBM, new ArrayList<>());+ metaItemMap.put(ChannelType.PARTICULATE_MATTER_MOLPCM, new ArrayList<>());+ metaItemMap.put(ChannelType.PARTICULATE_MATTER_MCGPCM, new ArrayList<>());+ metaItemMap.put(ChannelType.RESPIRATORY_RATE_BPM, new ArrayList<>());++ // COMMAND_CLASS_METER++ // Electric Meter+ metaItemMap.put(+ ChannelType.ELECTRIC_METER_ENERGY_KWH,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue("ENERGY_KWH")),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.5f KWh"))+ }+ )+ );+ metaItemMap.put(+ ChannelType.ELECTRIC_METER_ENERGY_KVAH,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue("ENERGY_KVAH")),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.5f KVAh"))+ }+ )+ );+ metaItemMap.put(+ ChannelType.ELECTRIC_METER_POWER_W,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue("POWER_W")),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.5f W"))+ }+ )+ );+ metaItemMap.put(ChannelType.ELECTRIC_METER_PULSE_COUNT, new ArrayList<>());+ metaItemMap.put(ChannelType.ELECTRIC_METER_VOLTAGE_V, new ArrayList<>());+ metaItemMap.put(ChannelType.ELECTRIC_METER_CURRENT_A, new ArrayList<>());+ metaItemMap.put(ChannelType.ELECTRIC_METER_POWER_FACTOR, new ArrayList<>());+ metaItemMap.put(+ ChannelType.ELECTRIC_METER_POWER_KVAR,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue("POWER_KVAR")),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.5f W"))+ }+ )+ );+ metaItemMap.put(+ ChannelType.ELECTRIC_METER_ENERGY_KVARH,+ Arrays.asList(+ new MetaItem[] {+ new MetaItem(MetaItemType.UNIT_TYPE.withInitialValue("ENERGY_KVARH")),+ new MetaItem(MetaItemType.FORMAT.withInitialValue("%0.5f KW"))+ }+ )+ );++ // Gas Meter+ metaItemMap.put(ChannelType.GAS_METER_VOLUME_CM, new ArrayList<>());+ metaItemMap.put(ChannelType.GAS_METER_VOLUME_CFT, new ArrayList<>());+ metaItemMap.put(ChannelType.GAS_METER_PULSE_COUNT, new ArrayList<>());++ // Water Meter+ metaItemMap.put(ChannelType.WATER_METER_VOLUME_CM, new ArrayList<>());+ metaItemMap.put(ChannelType.WATER_METER_VOLUME_CFT, new ArrayList<>());+ metaItemMap.put(ChannelType.WATER_METER_VOLUME_GAL, new ArrayList<>());+ metaItemMap.put(ChannelType.WATER_METER_PULSE_COUNT, new ArrayList<>());++ // COMMAND_CLASS_COLOR_CONTROL++ metaItemMap.put(ChannelType.COLOR_WARM_WHITE, new ArrayList<>());+ metaItemMap.put(ChannelType.COLOR_COLD_WHITE, new ArrayList<>());+ metaItemMap.put(ChannelType.COLOR_RED, new ArrayList<>());+ metaItemMap.put(ChannelType.COLOR_GREEN, new ArrayList<>());+ metaItemMap.put(ChannelType.COLOR_BLUE, new ArrayList<>());+ metaItemMap.put(ChannelType.COLOR_AMBER, new ArrayList<>());+ metaItemMap.put(ChannelType.COLOR_CYAN, new ArrayList<>());+ metaItemMap.put(ChannelType.COLOR_PURPLE, new ArrayList<>());+ metaItemMap.put(ChannelType.COLOR_INDEXED, new ArrayList<>());+ metaItemMap.put(ChannelType.COLOR_RGB, new ArrayList<>());+ metaItemMap.put(ChannelType.COLOR_ARGB, new ArrayList<>());++ // COMMAND_CLASS_SENSOR_ALARM++ metaItemMap.put(ChannelType.GENERAL_PURPOSE_ALARM, new ArrayList<>());+ metaItemMap.put(ChannelType.SMOKE_ALARM, new ArrayList<>());+ metaItemMap.put(ChannelType.CO_ALARM, new ArrayList<>());+ metaItemMap.put(ChannelType.CO2_ALARM, new ArrayList<>());+ metaItemMap.put(ChannelType.HEAT_ALARM, new ArrayList<>());+ metaItemMap.put(ChannelType.WATER_LEAK_ALARM, new ArrayList<>());+ metaItemMap.put(ChannelType.FIRST_SUPPORTED_ALARM, new ArrayList<>());++ // COMMAND_CLASS_BATTERY++ metaItemMap.put(ChannelType.CHARGE_PERCENTAGE, new ArrayList<>());++ // COMMAND_CLASS_CLOCK++ metaItemMap.put(ChannelType.DATETIME, new ArrayList<>());+++ }++ static public AttributeValueDescriptor toAttributeType(ChannelType channelType) {++ AttributeValueDescriptor attributeType = AttributeValueType.STRING;++ if (typeMap.containsKey(channelType)) {+ attributeType = typeMap.get(channelType);+ } else {+ switch(channelType.getValueType()) {+ case INTEGER:+ attributeType = AttributeValueType.NUMBER;+ break;+ case NUMBER:+ attributeType = AttributeValueType.NUMBER;+ break;+ case BOOLEAN:+ attributeType = AttributeValueType.BOOLEAN;+ break;+ case STRING:+ attributeType = AttributeValueType.STRING;+ break;+ case ARRAY:+ attributeType = AttributeValueType.ARRAY;+ break;+ }+ }+ return attributeType;+ }++ static public List<MetaItem> toMetaItems(ChannelType channelType) {+ if (metaItemMap.containsKey(channelType)) {+ return metaItemMap.get(channelType);+ } else {+ return new ArrayList<>();+ }+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWConfiguration.java b/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWConfiguration.javanew file mode 100644index 000000000..284c0ae7b--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWConfiguration.java@@ -0,0 +1,140 @@+/*+ * Copyright 2017, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.agent.protocol.zwave;++import org.openremote.model.AbstractValueHolder;+import org.openremote.model.ValidationFailure;+import org.openremote.model.ValueHolder;+import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.attribute.AttributeValidationResult;+import org.openremote.model.attribute.AttributeValueType;+import org.openremote.model.attribute.MetaItem;+import org.openremote.model.util.TextUtil;+import org.openremote.model.value.ValueType;+import org.openremote.model.value.Values;++import static org.openremote.agent.protocol.zwave.ZWProtocol.META_ZWAVE_DEVICE_ENDPOINT;+import static org.openremote.agent.protocol.zwave.ZWProtocol.META_ZWAVE_DEVICE_NODE_ID;+import static org.openremote.agent.protocol.zwave.ZWProtocol.META_ZWAVE_DEVICE_VALUE_LINK;+import static org.openremote.agent.protocol.zwave.ZWProtocol.META_ZWAVE_SERIAL_PORT;+import static org.openremote.model.attribute.MetaItemType.PROTOCOL_CONFIGURATION;+import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo;+import static org.openremote.model.util.TextUtil.isNullOrEmpty;++public class ZWConfiguration {++ public static int getZWNodeId(AssetAttribute assetAttribute) {+ return assetAttribute+ .getMetaItem(META_ZWAVE_DEVICE_NODE_ID)+ .flatMap(AbstractValueHolder::getValueAsInteger)+ .orElse(0);+ }++ public static int getZWEndpoint(AssetAttribute assetAttribute) {+ return assetAttribute+ .getMetaItem(META_ZWAVE_DEVICE_ENDPOINT)+ .flatMap(AbstractValueHolder::getValueAsInteger)+ .orElse(0);+ }++ public static String getZWLinkName(AssetAttribute assetAttribute) {+ return assetAttribute+ .getMetaItem(META_ZWAVE_DEVICE_VALUE_LINK)+ .flatMap(AbstractValueHolder::getValueAsString)+ .map(String::toUpperCase)+ .orElse("");+ }++ public static String getEndpointIdAsString(AssetAttribute assetAttribute)+ {+ return getZWNodeId(assetAttribute) + ":" + getZWEndpoint(assetAttribute);+ }++ public static boolean validateSerialConfiguration(AssetAttribute protocolConfiguration, AttributeValidationResult result) {+ boolean failure = false;++ if (!isSerialConfiguration(protocolConfiguration)) {+ failure = true;+ if (result != null) {+ result.addAttributeFailure(+ new ValidationFailure(+ ValueHolder.ValueFailureReason.VALUE_MISMATCH,+ ZWProtocol.PROTOCOL_NAME));+ }+ }++ boolean portFound = false;++ if (protocolConfiguration.getMeta() != null && !protocolConfiguration.getMeta().isEmpty()) {+ for (int i = 0; i < protocolConfiguration.getMeta().size(); i++) {+ MetaItem metaItem = protocolConfiguration.getMeta().get(i);+ if (isMetaNameEqualTo(metaItem, ZWProtocol.META_ZWAVE_SERIAL_PORT)) {+ portFound = true;+ if (isNullOrEmpty(metaItem.getValueAsString().orElse(null))) {+ failure = true;+ if (result == null) {+ break;+ }+ result.addMetaFailure(i,+ new ValidationFailure(MetaItem.MetaItemFailureReason.META_ITEM_VALUE_IS_REQUIRED, ValueType.STRING.name()));+ }+ }+ }+ }++ if (!portFound) {+ failure = true;+ if (result != null) {+ result.addMetaFailure(+ new ValidationFailure(MetaItem.MetaItemFailureReason.META_ITEM_MISSING, META_ZWAVE_SERIAL_PORT)+ );+ }+ }++ return !failure;+ }++ public static boolean isSerialConfiguration(AssetAttribute attribute) {+ return attribute != null && attribute.getValueAsString().map(value -> value.equals(ZWProtocol.PROTOCOL_NAME)).orElse(false);+ }++ public static boolean isValidProtocolName(String protocolName) {+ return TextUtil.isValidURN(protocolName);+ }++ public static void isValidProtocolNameOrThrow(String protocolName) throws IllegalArgumentException {+ if (!isValidProtocolName(protocolName)) {+ throw new IllegalArgumentException("Protocol name must start with 'urn:' but is: " + protocolName);+ }+ }++ public static AssetAttribute initProtocolConfiguration(AssetAttribute attribute, String protocolName) throws IllegalArgumentException {+ if (attribute == null) {+ return null;+ }+ isValidProtocolNameOrThrow(protocolName);+ attribute.setReadOnly(true);+ attribute.setType(AttributeValueType.STRING);+ attribute.setValue(Values.create(protocolName));+ attribute.getMeta().add(new MetaItem(PROTOCOL_CONFIGURATION, Values.create(true)));+ attribute.getMeta().add(new MetaItem(META_ZWAVE_SERIAL_PORT, Values.create("/dev/ttyACM0")));+ return attribute;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWControllerFactory.java b/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWControllerFactory.javanew file mode 100644index 000000000..0d6628dfb--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWControllerFactory.java@@ -0,0 +1,28 @@+/*+ * Copyright 2019, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.agent.protocol.zwave;++import org.openremote.agent.protocol.io.IoClient;+import org.openremote.protocol.zwave.model.Controller;++public interface ZWControllerFactory {+ Controller createController(IoClient<SerialDataPacket> messageProcessor);+ IoClient<SerialDataPacket> createMessageProcessor();+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWNetwork.java b/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWNetwork.javanew file mode 100644index 000000000..9bdff23e3--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWNetwork.java@@ -0,0 +1,546 @@+/*+ * Copyright 2019, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.agent.protocol.zwave;++import org.openremote.agent.protocol.io.IoClient;+import org.openremote.controller.exception.ConfigurationException;+import org.openremote.model.asset.Asset;+import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.asset.AssetTreeNode;+import org.openremote.model.asset.AssetType;+import org.openremote.model.asset.agent.AgentLink;+import org.openremote.model.asset.agent.ConnectionStatus;+import org.openremote.model.attribute.AttributeValueType;+import org.openremote.model.attribute.MetaItem;+import org.openremote.model.attribute.MetaItemType;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;+import org.openremote.protocol.zwave.ConnectionException;+import org.openremote.protocol.zwave.model.Controller;+import org.openremote.protocol.zwave.model.ZWEndPoint;+import org.openremote.protocol.zwave.model.ZWManufacturerID;+import org.openremote.protocol.zwave.model.ZWaveNode;+import org.openremote.protocol.zwave.model.commandclasses.ZWCommandClass;+import org.openremote.protocol.zwave.model.commandclasses.ZWCommandClassID;+import org.openremote.protocol.zwave.model.commandclasses.ZWParameterByte;+import org.openremote.protocol.zwave.model.commandclasses.ZWParameterInt;+import org.openremote.protocol.zwave.model.commandclasses.ZWParameterItem;+import org.openremote.protocol.zwave.model.commandclasses.ZWParameterShort;+import org.openremote.protocol.zwave.model.commandclasses.channel.Channel;+import org.openremote.protocol.zwave.model.commandclasses.channel.value.ArrayValue;+import org.openremote.protocol.zwave.model.commandclasses.channel.value.BooleanValue;+import org.openremote.protocol.zwave.model.commandclasses.channel.value.NumberValue;+import org.openremote.protocol.zwave.model.commandclasses.channel.value.StringValue;+import org.openremote.protocol.zwave.model.commandclasses.channel.value.ValueType;++import java.util.ArrayList;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.function.Consumer;++import static java.util.stream.Collectors.toList;+import static org.openremote.agent.protocol.zwave.ZWProtocol.META_ZWAVE_DEVICE_ENDPOINT;+import static org.openremote.agent.protocol.zwave.ZWProtocol.META_ZWAVE_DEVICE_NODE_ID;+import static org.openremote.agent.protocol.zwave.ZWProtocol.META_ZWAVE_DEVICE_VALUE_LINK;+import static org.openremote.protocol.zwave.model.ZWNodeInitializerListener.NodeInitState.INITIALIZATION_FINISHED;++public class ZWNetwork {++ private final ZWControllerFactory controllerFactory;+ protected Controller controller;+ protected IoClient<SerialDataPacket> ioClient;+ private final List<Consumer<ConnectionStatus>> connectionStatusConsumers = new ArrayList<>();+ private final Map<Consumer<org.openremote.protocol.zwave.model.commandclasses.channel.value.Value>, ChannelConsumerLink> consumerLinkMap = new HashMap<>();++ public ZWNetwork(ZWControllerFactory controllerFactory) {+ if (controllerFactory == null) {+ throw new IllegalArgumentException("Missing controller factory.");+ }+ this.controllerFactory = controllerFactory;+ }++ public synchronized void connect() {+ if (controller != null) {+ return;+ }++ ioClient = controllerFactory.createMessageProcessor();+ ioClient.addConnectionStatusConsumer(this::onConnectionStatusChanged);+ controller = createController(ioClient);++ try {+ controller.connect();+ } catch (ConfigurationException e) {+ removeStatusChangedHandler(ioClient);+ controller = null;+ ioClient = null;+ onConnectionStatusChanged(ConnectionStatus.ERROR_CONFIGURATION);+ } catch (ConnectionException e) {+ removeStatusChangedHandler(ioClient);+ controller = null;+ ioClient = null;+ onConnectionStatusChanged(ConnectionStatus.ERROR_CONFIGURATION);+ }+ }++ public synchronized void disconnect() {+ if (controller == null) {+ return;+ }++ try {+ controller.disconnect();+ } catch (ConnectionException e) {++ } finally {+ removeStatusChangedHandler(ioClient);+ ioClient = null;+ controller = null;+ onConnectionStatusChanged(ConnectionStatus.DISCONNECTED);+ }+ }++ public synchronized ConnectionStatus getConnectionStatus() {+ if (ioClient != null) {+ return ioClient.getConnectionStatus();+ } else {+ return ConnectionStatus.DISCONNECTED;+ }+ }++ public synchronized void addConnectionStatusConsumer(Consumer<ConnectionStatus> connectionStatusConsumer) {+ connectionStatusConsumers.add(connectionStatusConsumer);+ }++ public synchronized void removeConnectionStatusConsumer(Consumer<ConnectionStatus> connectionStatusConsumer) {+ connectionStatusConsumers.remove(connectionStatusConsumer);+ }++ public synchronized void addSensorValueConsumer(int nodeId, int endpoint, String channelName, Consumer<org.openremote.protocol.zwave.model.commandclasses.channel.value.Value> consumer) {+ ChannelConsumerLink link = ChannelConsumerLink.createLink(nodeId, endpoint, channelName, consumer, controller);+ consumerLinkMap.put(consumer, link);+ }++ public synchronized void removeSensorValueConsumer(Consumer<org.openremote.protocol.zwave.model.commandclasses.channel.value.Value> consumer) {+ ChannelConsumerLink link = consumerLinkMap.get(consumer);+ if (link != null) {+ consumerLinkMap.remove(consumer);+ link.unlink();+ }+ }++ public synchronized void writeChannel(int nodeId, int endpoint, String linkName, Value value) {+ Channel channel = findChannel(nodeId, endpoint, linkName);+ if (channel != null && value != null) {+ org.openremote.protocol.zwave.model.commandclasses.channel.value.Value zwValue = null;+ ValueType type = channel.getValueType();+ switch(type) {+ case STRING:+ zwValue =Values.getString(value).map(val -> new StringValue(val)).orElse(null);+ break;+ case NUMBER:+ zwValue = Values.getNumber(value).map(val -> new NumberValue(val)).orElse(null);+ break;+ case INTEGER:+ zwValue = Values.getIntegerCoerced(value).map(val -> new NumberValue(val)).orElse(null);+ break;+ case BOOLEAN:+ zwValue = Values.getBoolean(value).map(val -> new BooleanValue(val)).orElse(null);+ break;+ case ARRAY:+ zwValue = toZWArray(Values.getArray(value).orElse(null));+ }++ if (zwValue != null) {+ channel.executeSetCommand(zwValue);+ }+ }+ }++ public synchronized AssetTreeNode[] discoverDevices(AssetAttribute protocolConfiguration) {+ if (controller == null) {+ return new AssetTreeNode[0];+ }++ MetaItem agentLink = AgentLink.asAgentLinkMetaItem(protocolConfiguration.getReferenceOrThrow());++ // Filter nodes++ List<ZWaveNode> nodes = controller.getNodes()+ .stream()+ .filter(node -> node.getState() == INITIALIZATION_FINISHED)+ .filter(node -> {+ // Do not add devices that have already been discovered+ List<ZWCommandClass> cmdClasses = new ArrayList<>();+ cmdClasses.addAll(node.getSupportedCommandClasses());+ for (ZWEndPoint curEndpoint : node.getEndPoints()) {+ cmdClasses.addAll(curEndpoint.getCmdClasses());+ }+ return cmdClasses+ .stream()+ .map(ZWCommandClass::getChannels)+ .flatMap(List<Channel>::stream)+ .noneMatch(channel ->+ consumerLinkMap.values().stream().anyMatch(link -> link.getChannel() == channel)+ );+ })+ .collect(toList());++ List<AssetTreeNode> assetNodes = nodes+ .stream()+ .map(node -> {++ // Root device++ AssetTreeNode deviceNode = createDeviceNode(+ agentLink,+ node.getSupportedCommandClasses(),+ node.getGenericDeviceClassID().getDisplayName(node.getSpecificDeviceClassID())+ );++ // Device Info++ Asset deviceInfoAsset = new Asset("Info", AssetType.THING);+ List<AssetAttribute> infoAttributes = createNodeInfoAttributes(node, agentLink);+ deviceInfoAsset.addAttributes(infoAttributes.toArray(new AssetAttribute[infoAttributes.size()]));+ deviceNode.addChild(new AssetTreeNode(deviceInfoAsset));++ // Sub device++ for (ZWEndPoint curEndpoint : node.getEndPoints()) {+ String subDeviceName = curEndpoint.getGenericDeviceClassID().getDisplayName(curEndpoint.getSpecificDeviceClassID()) ++ " - " + curEndpoint.getEndPointNumber();+ AssetTreeNode subDeviceNode = createDeviceNode(+ agentLink,+ curEndpoint.getCmdClasses(),+ subDeviceName+ );+ deviceNode.addChild(subDeviceNode);+ }++ // Parameters++ List<ZWParameterItem> parameters = node.getParameters();+ if (parameters.size() > 0) {+ AssetTreeNode parameterListNode = new AssetTreeNode(new Asset("Parameters", AssetType.THING));+ deviceNode.addChild(parameterListNode);++ List<AssetTreeNode> parameterNodes = parameters+ .stream()+ .filter(parameter -> parameter.getChannels().size() > 0)+ .map(parameter -> {+ Integer number = parameter.getNumber();+ String parameterLabel = number.toString() + " : " + parameter.getDisplayName();+ String description = parameter.getDescription();+ Asset parameterAsset = new Asset(parameterLabel, AssetType.THING);+ AssetTreeNode parameterNode = new AssetTreeNode(parameterAsset);++ List<AssetAttribute> attributes = parameter.getChannels()+ .stream()+ .map(channel -> {+ AssetAttribute attribute = new AssetAttribute(channel.getName(), TypeMapper.toAttributeType(channel.getChannelType()))+ .setMeta(+ agentLink,+ new MetaItem(MetaItemType.LABEL, Values.create(channel.getDisplayName()))+ )+ .addMeta(getMetaItems(channel));+ addValidRangeMeta(attribute, parameter);+ return attribute;+ })+ .collect(toList());+ if (description != null && description.length() > 0) {+ AssetAttribute descriptionAttribute = new AssetAttribute(+ "description", AttributeValueType.STRING, Values.create("-")+ ).setMeta(+ new MetaItem(MetaItemType.LABEL, Values.create("Description")),+ new MetaItem(MetaItemType.READ_ONLY, Values.create(true)),+ new MetaItem(MetaItemType.DESCRIPTION, Values.create(description))+ );+ attributes.add(descriptionAttribute);+ }+ parameterAsset.addAttributes(attributes.toArray(new AssetAttribute[attributes.size()]));+ return parameterNode;+ })+ .collect(toList());++ parameterNodes.forEach(parameterNode -> parameterListNode.addChild(parameterNode));+ }++ return deviceNode;+ })+ .collect(toList());++ // Z-Wave Controller++ Asset networkManagementAsset = new Asset("Z-Wave Controller", AssetType.THING);+ List<AssetAttribute> attributes = controller.getSystemCommandManager().getChannels()+ .stream()+ .filter(channel ->+ consumerLinkMap.values().stream().noneMatch(link -> link.getChannel() == channel))+ .map(channel -> {+ AssetAttribute attribute = new AssetAttribute(channel.getName(), TypeMapper.toAttributeType(channel.getChannelType()))+ .setMeta(+ agentLink,+ new MetaItem(MetaItemType.LABEL, Values.create(channel.getDisplayName()))+ )+ .addMeta(getMetaItems(channel));+ return attribute;+ })+ .collect(toList());+ if (attributes.size() > 0) {+ networkManagementAsset.addAttributes(attributes.toArray(new AssetAttribute[attributes.size()]));+ assetNodes.add(new AssetTreeNode(networkManagementAsset));+ }++ return assetNodes.toArray(new AssetTreeNode[assetNodes.size()]);+ }++ protected Controller createController(IoClient<SerialDataPacket> ioClient) {+ return controllerFactory.createController(ioClient);+ }++ protected synchronized void onConnectionStatusChanged(ConnectionStatus status) {+ connectionStatusConsumers.forEach(consumer ->consumer.accept(status));+ }++ private MetaItem[] getMetaItems(Channel channel) {+ int nodeId = channel.getCommandClass() != null ? channel.getCommandClass().getContext().getNodeID() : 0;+ int endpoint = channel.getCommandClass() != null ? channel.getCommandClass().getContext().getDestEndPoint() : 0;+ List<MetaItem> unitMetaItems = TypeMapper.toMetaItems(channel.getChannelType());+ List<MetaItem> metaItems = new ArrayList<>(3 + (channel.isReadOnly() ? 1 : 0) + unitMetaItems.size());+ metaItems.add(new MetaItem(META_ZWAVE_DEVICE_NODE_ID, Values.create(nodeId)));+ metaItems.add(new MetaItem(META_ZWAVE_DEVICE_ENDPOINT, Values.create(endpoint)));+ metaItems.add(new MetaItem(META_ZWAVE_DEVICE_VALUE_LINK, Values.create(channel.getLinkName())));+ if (channel.isReadOnly()) {+ metaItems.add(new MetaItem(MetaItemType.READ_ONLY, Values.create(true)));+ }+ metaItems.addAll(unitMetaItems);+ return metaItems.toArray(new MetaItem[metaItems.size()]);+ }++ private void removeStatusChangedHandler(IoClient<SerialDataPacket> ioClient) {+ if (ioClient != null) {+ ioClient.removeConnectionStatusConsumer(this::onConnectionStatusChanged);+ }+ }++ private Channel findChannel(int nodeId, int endpointNumber, String channelName) {+ Channel channel = null;+ if (controller != null) {+ channel = controller.findChannel(nodeId, endpointNumber, channelName);+ }+ return channel;+ }+++ private org.openremote.protocol.zwave.model.commandclasses.channel.value.ArrayValue toZWArray(org.openremote.model.value.ArrayValue arrValue) {+ if (arrValue == null) {+ return null;+ }+ ArrayValue zwArray = new ArrayValue();+ org.openremote.protocol.zwave.model.commandclasses.channel.value.Value[] arr = new org.openremote.protocol.zwave.model.commandclasses.channel.value.Value[arrValue.length()];+ zwArray.addAll(+ arrValue+ .stream()+ .map(arrItem -> toZWArrayItem(arrItem))+ .collect(toList())+ .toArray(arr)+ );+ for (int i = 0; i < zwArray.length(); i++) {+ if (zwArray.get(i) == null) {+ return null;+ }+ }+ return zwArray;+ }++ private org.openremote.protocol.zwave.model.commandclasses.channel.value.Value toZWArrayItem(org.openremote.model.value.Value value) {+ if (value == null) {+ return null;+ }+ org.openremote.protocol.zwave.model.commandclasses.channel.value.Value zwValue = null;+ switch(value.getType()) {+ case NUMBER:+ zwValue = Values.getNumber(value).map(val -> new NumberValue(val)).orElse(null);+ break;+ case BOOLEAN:+ zwValue = Values.getBoolean(value).map(val -> new BooleanValue(val)).orElse(null);+ break;+ case STRING:+ zwValue = Values.getString(value).map(val -> new StringValue(val)).orElse(null);+ break;+ }+ return zwValue;+ }++ private AssetTreeNode createDeviceNode(MetaItem agentLink, List<ZWCommandClass> cmdClasses, String name) {++ Asset device = new Asset(name, AssetType.THING);++ List<AssetAttribute> attributes = cmdClasses+ .stream()+ .filter(commandClass -> commandClass.getID().toRaw() != ZWCommandClassID.COMMAND_CLASS_CONFIGURATION.toRaw() &&+ commandClass.getID().toRaw() != ZWCommandClassID.COMMAND_CLASS_ZWAVEPLUS_INFO.toRaw() &&+ commandClass.getID().toRaw() != ZWCommandClassID.COMMAND_CLASS_BASIC.toRaw())+ .map(ZWCommandClass::getChannels)+ .flatMap(List<Channel>::stream)+ .map(channel -> {+ int endpoint = channel.getCommandClass().getContext().getDestEndPoint();+ String attributeName = channel.getName() + (endpoint == 0 ? "" : "_" + endpoint);+ String displayName = channel.getDisplayName() + (endpoint == 0 ? "" : " - " + endpoint);+ AssetAttribute attribute = new AssetAttribute(attributeName, TypeMapper.toAttributeType(channel.getChannelType()))+ .setMeta(+ agentLink,+ new MetaItem(MetaItemType.LABEL, Values.create(displayName))+ )+ .addMeta(getMetaItems(channel));+ return attribute;+ })+ .collect(toList());++ device.addAttributes(attributes.toArray(new AssetAttribute[attributes.size()]));++ return new AssetTreeNode(device);+ }++ private List<AssetAttribute> createNodeInfoAttributes(ZWaveNode node, MetaItem agentLink) {+ List<AssetAttribute> attributes = new ArrayList<>();++ AssetAttribute nodeIdAttrib = new AssetAttribute(+ "nodeId", AttributeValueType.NUMBER, Values.create(node.getNodeID()))+ .setMeta(+ new MetaItem(MetaItemType.LABEL, Values.create("Node ID")),+ new MetaItem(MetaItemType.READ_ONLY, Values.create(true))+ );+ attributes.add(nodeIdAttrib);++ AssetAttribute manufacturerIdAttrib = new AssetAttribute(+ "manufacturerId", AttributeValueType.STRING, Values.create(String.format("0x%04X",node.getManufacturerId())))+ .setMeta(+ new MetaItem(MetaItemType.LABEL, Values.create("Manufacturer ID")),+ new MetaItem(MetaItemType.READ_ONLY, Values.create(true))+ );+ attributes.add(manufacturerIdAttrib);++ AssetAttribute manufacturerAttrib = new AssetAttribute(+ "manufacturerName", AttributeValueType.STRING, Values.create(ZWManufacturerID.fromRaw(node.getManufacturerId()).getName()))+ .setMeta(+ new MetaItem(MetaItemType.LABEL, Values.create("Manufacturer")),+ new MetaItem(MetaItemType.READ_ONLY, Values.create(true))+ );+ attributes.add(manufacturerAttrib);++ AssetAttribute flirsAttrib = new AssetAttribute(+ "isFlirs", AttributeValueType.BOOLEAN, Values.create(node.getNodeInfo().isFLIRS()))+ .setMeta(+ new MetaItem(MetaItemType.LABEL, Values.create("FLIRS")),+ new MetaItem(MetaItemType.READ_ONLY, Values.create(true))+ );+ attributes.add(flirsAttrib);++ AssetAttribute routingAttrib = new AssetAttribute(+ "isRouting", AttributeValueType.BOOLEAN, Values.create(node.getNodeInfo().isRouting()))+ .setMeta(+ new MetaItem(MetaItemType.LABEL, Values.create("Routing")),+ new MetaItem(MetaItemType.READ_ONLY, Values.create(true))+ );+ attributes.add(routingAttrib);++ AssetAttribute listeningAttrib = new AssetAttribute(+ "isListening", AttributeValueType.BOOLEAN, Values.create(node.getNodeInfo().isListening()))+ .setMeta(+ new MetaItem(MetaItemType.LABEL, Values.create("Listening")),+ new MetaItem(MetaItemType.READ_ONLY, Values.create(true))+ );+ attributes.add(listeningAttrib);++ AssetAttribute productTypeIdAttrib = new AssetAttribute(+ "productTypeId", AttributeValueType.STRING, Values.create(String.format("0x%04X", node.getProductTypeID())))+ .setMeta(+ new MetaItem(MetaItemType.LABEL, Values.create("Product Type ID")),+ new MetaItem(MetaItemType.READ_ONLY, Values.create(true))+ );+ attributes.add(productTypeIdAttrib);++ AssetAttribute productIdAttrib = new AssetAttribute(+ "productId", AttributeValueType.STRING, Values.create(String.format("0x%04X", node.getProductID())))+ .setMeta(+ new MetaItem(MetaItemType.LABEL, Values.create("Product ID")),+ new MetaItem(MetaItemType.READ_ONLY, Values.create(true))+ );+ attributes.add(productIdAttrib);++ String modelName = node.getModelName();+ if (modelName != null) {+ AssetAttribute modelNameAttrib = new AssetAttribute(+ "modelName", AttributeValueType.STRING, Values.create(modelName))+ .setMeta(+ new MetaItem(MetaItemType.LABEL, Values.create("Model")),+ new MetaItem(MetaItemType.READ_ONLY, Values.create(true))+ );+ attributes.add(modelNameAttrib);+ }++ // Z-Wave Plus Info++ List<AssetAttribute> zwPlusAttributes = node.getSupportedCommandClasses()+ .stream()+ .filter(commandClass -> commandClass.getID().toRaw() == ZWCommandClassID.COMMAND_CLASS_ZWAVEPLUS_INFO.toRaw())+ .map(ZWCommandClass::getChannels)+ .flatMap(List<Channel>::stream)+ .map(channel -> {+ String attributeName = channel.getName();+ String displayName = channel.getDisplayName();+ AssetAttribute attribute = new AssetAttribute(attributeName, TypeMapper.toAttributeType(channel.getChannelType()))+ .setMeta(+ agentLink,+ new MetaItem(MetaItemType.LABEL, Values.create(displayName))+ )+ .addMeta(getMetaItems(channel));+ return attribute;+ })+ .collect(toList());++ attributes.addAll(zwPlusAttributes);++ return attributes;+ }++ private void addValidRangeMeta(AssetAttribute attribute, ZWParameterItem parameter) {+ Long min = null;+ Long max = null;+ if (parameter instanceof ZWParameterByte) {+ min = ((ZWParameterByte)parameter).getMinValue();+ max = ((ZWParameterByte)parameter).getMaxValue();+ } else if (parameter instanceof ZWParameterShort) {+ min = ((ZWParameterShort)parameter).getMinValue();+ max = ((ZWParameterShort)parameter).getMaxValue();+ } else if (parameter instanceof ZWParameterInt) {+ min = ((ZWParameterInt)parameter).getMinValue();+ max = ((ZWParameterInt)parameter).getMaxValue();+ }++ if (min != null && max != null) {+ String validRangString = "[" + min + " - " + max + "]";+ attribute.addMeta(new MetaItem(MetaItemType.DESCRIPTION, Values.create(validRangString)));+ }+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWPacketDecoder.java b/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWPacketDecoder.javanew file mode 100644index 000000000..d16943f40--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWPacketDecoder.java@@ -0,0 +1,45 @@+/*+ * Copyright 2020, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.agent.protocol.zwave;++import io.netty.buffer.ByteBuf;+import io.netty.channel.ChannelHandlerContext;+import io.netty.handler.codec.ByteToMessageDecoder;++import java.util.List;++public class ZWPacketDecoder extends ByteToMessageDecoder {++ @Override+ protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> messages) throws Exception {+ int size = buf.readableBytes();++ if (size > 0) {+ byte[] data = new byte[size];+ for (int i = 0; i < size; i++) {+ data[i] = buf.readByte();+ }+ buf.discardReadBytes();++ SerialDataPacket packet = new SerialDataPacket(data);+ messages.add(packet);+ }+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWPacketEncoder.java b/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWPacketEncoder.javanew file mode 100644index 000000000..1518088fb--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWPacketEncoder.java@@ -0,0 +1,32 @@+/*+ * Copyright 2020, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.agent.protocol.zwave;++import io.netty.buffer.ByteBuf;+import io.netty.channel.ChannelHandlerContext;+import io.netty.handler.codec.MessageToByteEncoder;++public class ZWPacketEncoder extends MessageToByteEncoder<SerialDataPacket> {++ @Override+ protected void encode(ChannelHandlerContext ctx, SerialDataPacket message, ByteBuf buf) throws Exception {+ buf.writeBytes(message.getData());+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWProtocol.javanew file mode 100644index 000000000..047ef0546--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWProtocol.java@@ -0,0 +1,470 @@+/*+ * Copyright 2017, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.agent.protocol.zwave;++import org.openremote.agent.protocol.AbstractProtocol;+import org.openremote.agent.protocol.ProtocolConfigurationDiscovery;+import org.openremote.agent.protocol.ProtocolLinkedAttributeDiscovery;+import org.openremote.agent.protocol.ProtocolLinkedAttributeImport;+import org.openremote.model.AbstractValueHolder;+import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.asset.AssetTreeNode;+import org.openremote.model.asset.agent.ConnectionStatus;+import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.attribute.AttributeState;+import org.openremote.model.attribute.AttributeValidationResult;+import org.openremote.model.attribute.AttributeValueType;+import org.openremote.model.attribute.MetaItem;+import org.openremote.model.attribute.MetaItemDescriptor;+import org.openremote.model.attribute.MetaItemDescriptorImpl;+import org.openremote.model.file.FileInfo;+import org.openremote.model.util.Pair;+import org.openremote.model.value.ArrayValue;+import org.openremote.model.value.Value;+import org.openremote.model.value.ValueType;+import org.openremote.model.value.Values;+import org.openremote.protocol.zwave.port.ZWavePortConfiguration;++import java.io.PrintWriter;+import java.io.StringWriter;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.Collections;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.Optional;+import java.util.function.Consumer;+import java.util.logging.Logger;++import static org.openremote.agent.protocol.zwave.ZWConfiguration.getEndpointIdAsString;+import static org.openremote.agent.protocol.zwave.ZWConfiguration.getZWEndpoint;+import static org.openremote.agent.protocol.zwave.ZWConfiguration.getZWLinkName;+import static org.openremote.agent.protocol.zwave.ZWConfiguration.getZWNodeId;+import static org.openremote.agent.protocol.zwave.ZWConfiguration.initProtocolConfiguration;+import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;+import static org.openremote.model.util.TextUtil.REGEXP_PATTERN_INTEGER_POSITIVE;++public class ZWProtocol extends AbstractProtocol implements ProtocolLinkedAttributeDiscovery,+ ProtocolConfigurationDiscovery, ProtocolLinkedAttributeImport {++ // Constants ------------------------------------------------------------------------------------++ public static final String PROTOCOL_NAME = PROTOCOL_NAMESPACE + ":zwave";+ public static final String PROTOCOL_DISPLAY_NAME = "Z-Wave";+ public static final String VERSION = "1.0";+ public static final String META_ZWAVE_SERIAL_PORT = PROTOCOL_NAME + ":port";+ public static final String META_ZWAVE_DEVICE_NODE_ID = PROTOCOL_NAME + ":deviceNodeId";+ public static final String META_ZWAVE_DEVICE_ENDPOINT = PROTOCOL_NAME + ":deviceEndpoint";+ public static final String META_ZWAVE_DEVICE_VALUE_LINK = PROTOCOL_NAME + ":deviceValueLink";+ public static final int DEFAULT_ENDPOINT = 0;+++ public static final List<MetaItemDescriptor> PROTOCOL_META_ITEM_DESCRIPTORS = Collections.singletonList(+ new MetaItemDescriptorImpl(+ META_ZWAVE_SERIAL_PORT,+ ValueType.STRING,+ true,+ null,+ null,+ 1,+ null,+ false,+ null, null, null+ )+ );++ public static final List<MetaItemDescriptor> ATTRIBUTE_META_ITEM_DESCRIPTORS = Arrays.asList(+ new MetaItemDescriptorImpl(+ META_ZWAVE_DEVICE_NODE_ID,+ ValueType.NUMBER,+ true,+ "^([1-9]\\d{0,1}|1[0-9][0-9]|2[0-2][0-9]|23[0-2])$", //1-232+ "1-232",+ 1,+ null,+ false,+ null, null, null+ ),+ new MetaItemDescriptorImpl(+ META_ZWAVE_DEVICE_ENDPOINT,+ ValueType.NUMBER,+ true,+ REGEXP_PATTERN_INTEGER_POSITIVE,+ MetaItemDescriptor.PatternFailure.INTEGER_POSITIVE_NON_ZERO.name(),+ 1,+ Values.create(DEFAULT_ENDPOINT),+ false,+ null, null, null+ ),+ new MetaItemDescriptorImpl(+ META_ZWAVE_DEVICE_VALUE_LINK,+ ValueType.STRING,+ true,+ null,+ null,+ 1,+ null,+ false,+ null, null, null+ )+ );++++ // Class Members --------------------------------------------------------------------------------++ public static final Logger LOG = Logger.getLogger(ZWProtocol.class.getName());+++ // Protected Instance Fields --------------------------------------------------------------------++ protected final Map<String, ZWNetwork> networkMap = new HashMap<>();+ protected final Map<AttributeRef, Pair<ZWNetwork, Consumer<ConnectionStatus>>> networkConfigurationMap = new HashMap<>();+ protected final Map<AttributeRef, Consumer<org.openremote.protocol.zwave.model.commandclasses.channel.value.Value>> sensorValueConsumerMap = new HashMap<>();+++ // Implements Protocol --------------------------------------------------------------------------++ @Override+ public String getProtocolName() {+ return PROTOCOL_NAME;+ }++ @Override+ public String getProtocolDisplayName() {+ return PROTOCOL_DISPLAY_NAME;+ }++ @Override+ public String getVersion() {+ return VERSION;+ }+++ // Implements AbstractProtocol ------------------------------------------------------------------++ @Override+ protected List<MetaItemDescriptor> getProtocolConfigurationMetaItemDescriptors() {+ List<MetaItemDescriptor> descriptors = new ArrayList<>(PROTOCOL_META_ITEM_DESCRIPTORS.size());+ descriptors.addAll(PROTOCOL_META_ITEM_DESCRIPTORS);+ return descriptors;+ }++ @Override+ public AttributeValidationResult validateProtocolConfiguration(AssetAttribute protocolConfiguration) {+ AttributeValidationResult result = super.validateProtocolConfiguration(protocolConfiguration);+ if (result.isValid()) {+ ZWConfiguration.validateSerialConfiguration(protocolConfiguration, result);+ }+ return result;+ }++ @Override+ public AssetAttribute getProtocolConfigurationTemplate() {+ return super.getProtocolConfigurationTemplate()+ .addMeta(new MetaItem(META_ZWAVE_SERIAL_PORT, null));+ }++ @Override+ protected List<MetaItemDescriptor> getLinkedAttributeMetaItemDescriptors() {+ List<MetaItemDescriptor> descriptors = new ArrayList<>(ATTRIBUTE_META_ITEM_DESCRIPTORS.size());+ descriptors.addAll(ATTRIBUTE_META_ITEM_DESCRIPTORS);+ return descriptors;+ }++ @Override+ protected void doLinkProtocolConfiguration(AssetAttribute protocolConfiguration) {+ AttributeRef protocolRef = protocolConfiguration.getReferenceOrThrow();+ Optional<String> networkId = getUniqueNetworkIdentifier(protocolConfiguration);++ if (!networkId.isPresent()) {+ LOG.severe("No serial port provided for Z-Wave protocol configuration: " + protocolConfiguration);+ updateStatus(protocolRef, ConnectionStatus.ERROR_CONFIGURATION);+ return;+ }++ Consumer<ConnectionStatus> statusConsumer = status -> executorService.execute(+ () -> updateStatus(protocolRef, status)+ );++ ZWNetwork zwNetwork = null;++ synchronized (this) {+ zwNetwork = networkMap.computeIfAbsent(+ networkId.get(),+ port -> {+ ZWControllerFactory factory = createControllerFactory(port);+ ZWNetwork network = new ZWNetwork(factory);+ network.addConnectionStatusConsumer(statusConsumer);+ return network;+ }+ );+ networkConfigurationMap.put(protocolRef, new Pair<>(zwNetwork, statusConsumer));+ }++ if (protocolConfiguration.isEnabled() && zwNetwork.getConnectionStatus() == ConnectionStatus.DISCONNECTED) {+ zwNetwork.connect();+ }+ }++ @Override+ protected void doUnlinkProtocolConfiguration(AssetAttribute protocolConfiguration) {+ AttributeRef protocolRef = protocolConfiguration.getReferenceOrThrow();+ String networkId = getUniqueNetworkIdentifier(protocolConfiguration).orElse("");++ // updateStatus(protocolRef, ConnectionStatus.DISCONNECTED);++ ZWNetwork zwNetworkToDisconnect = null;++ synchronized (this) {+ Pair<ZWNetwork, Consumer<ConnectionStatus>> zwNetworkAndConsumer= networkConfigurationMap.remove(protocolRef);++ if (zwNetworkAndConsumer != null) {+ zwNetworkAndConsumer.key.removeConnectionStatusConsumer(zwNetworkAndConsumer.value);++ // Check if network is no longer used+ if (networkConfigurationMap.isEmpty() ||+ networkConfigurationMap.values()+ .stream()+ .noneMatch(networkStatusConsumer -> zwNetworkAndConsumer.key.equals(networkStatusConsumer.key)))+ {+ networkMap.remove(networkId);+ zwNetworkToDisconnect = zwNetworkAndConsumer.key;+ }+ }+ }++ if (zwNetworkToDisconnect != null) {+ zwNetworkToDisconnect.disconnect();+ }+ }++ @Override+ protected synchronized void doLinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {+ Pair<ZWNetwork, Consumer<ConnectionStatus>> zwNetworkConsumerPair = networkConfigurationMap.get(protocolConfiguration.getReferenceOrThrow());++ if (zwNetworkConsumerPair == null) {+ LOG.info("Protocol Configuration doesn't have a valid ZWNetwork so cannot link");+ return;+ }++ ZWNetwork zwNetwork = zwNetworkConsumerPair.key;++ int nodeId = getZWNodeId(attribute);+ int endpoint = getZWEndpoint(attribute);+ String linkName = getZWLinkName(attribute);++ AttributeRef attributeRef = attribute.getReferenceOrThrow();+ ValueType valueType = attribute.getType().orElse(AttributeValueType.STRING).getValueType();+ LOG.fine("Linking attribute to device endpoint '" + getEndpointIdAsString(attribute) + "' and channel '" + linkName + "': " + attributeRef);++ Consumer<org.openremote.protocol.zwave.model.commandclasses.channel.value.Value> sensorValueConsumer = value ->+ updateLinkedAttribute(new AttributeState(attributeRef, toAttributeValue(value, valueType)));++ sensorValueConsumerMap.put(attributeRef, sensorValueConsumer);+ zwNetwork.addSensorValueConsumer(nodeId, endpoint, linkName, sensorValueConsumer);+ }++ @Override+ protected synchronized void doUnlinkAttribute(AssetAttribute attribute, AssetAttribute protocolConfiguration) {+ Pair<ZWNetwork, Consumer<ConnectionStatus>> zwNetworkConsumerPair = networkConfigurationMap.get(protocolConfiguration.getReferenceOrThrow());++ if (zwNetworkConsumerPair == null) {+ return;+ }++ ZWNetwork zwNetwork = zwNetworkConsumerPair.key;+ AttributeRef attributeRef = attribute.getReferenceOrThrow();+ Consumer<org.openremote.protocol.zwave.model.commandclasses.channel.value.Value> sensorValueConsumer = sensorValueConsumerMap.remove(attributeRef);+ zwNetwork.removeSensorValueConsumer(sensorValueConsumer);+ }++ @Override+ protected void processLinkedAttributeWrite(AttributeEvent event, Value processedValue, AssetAttribute protocolConfiguration) {+ Pair<ZWNetwork, Consumer<ConnectionStatus>> zwNetworkConsumerPair = networkConfigurationMap.get(protocolConfiguration.getReferenceOrThrow());++ if (zwNetworkConsumerPair == null) {+ return;+ }++ ZWNetwork zwNetwork = zwNetworkConsumerPair.key;+ AssetAttribute attribute = getLinkedAttribute(event.getAttributeRef());++ if (attribute == null) {+ return;+ }++ int nodeId = getZWNodeId(attribute);+ int endpoint = getZWEndpoint(attribute);+ String linkName = getZWLinkName(attribute);++ zwNetwork.writeChannel(nodeId, endpoint, linkName, processedValue);+ }+++ // Implements ProtocolConfigurationDiscovery --------------------------------------------------++ @Override+ public AssetAttribute[] discoverProtocolConfigurations() {+ return new AssetAttribute[] {+ initProtocolConfiguration(new AssetAttribute(), PROTOCOL_NAME)+ };+ }+++ // Implements ProtocolLinkedAttributeDiscovery ------------------------------------------------++ @Override+ public synchronized AssetTreeNode[] discoverLinkedAssetAttributes(AssetAttribute protocolConfiguration) {+ Pair<ZWNetwork, Consumer<ConnectionStatus>> zwNetworkConsumerPair = networkConfigurationMap.get(protocolConfiguration.getReferenceOrThrow());++ if (zwNetworkConsumerPair == null) {+ return new AssetTreeNode[0];+ }++ ZWNetwork zwNetwork = zwNetworkConsumerPair.key;+ try {+ return zwNetwork.discoverDevices(protocolConfiguration);+ } catch(Exception e) {+ StringWriter errors = new StringWriter();+ e.printStackTrace(new PrintWriter(errors));+ LOG.severe(errors.toString());+ throw e;+ }+ }+++ // Implements ProtocolLinkedAttributeImport ---------------------------------------------------++ @Override+ public AssetTreeNode[] discoverLinkedAssetAttributes(AssetAttribute protocolConfiguration, FileInfo fileInfo) throws IllegalStateException {+ // TODO : remove the ProtocolLinkedAttributeImport interface implementation. It has only been added because+ // the manager GUI doesn't (currently) work at all without it.+ return new AssetTreeNode[0];+ }+++ // Protected Instance Methods -----------------------------------------------------------------++ protected ZWControllerFactory createControllerFactory(String serialPort) {+ ZWavePortConfiguration configuration = new ZWavePortConfiguration();+ configuration.setCommLayer(ZWavePortConfiguration.CommLayer.NETTY);+ configuration.setComPort(serialPort);+ ZWControllerFactory factory = new NettyZWControllerFactory(configuration, executorService);+ return factory;+ }+++ // Private Instance Methods -------------------------------------------------------------------++ private Optional<String> getUniqueNetworkIdentifier(AssetAttribute protocolConfiguration) {++ // TODO : Z-Wave Home ID++ return protocolConfiguration+ .getMetaItem(META_ZWAVE_SERIAL_PORT)+ .flatMap(AbstractValueHolder::getValueAsString);+ }++ private org.openremote.model.value.Value toAttributeValue(org.openremote.protocol.zwave.model.commandclasses.channel.value.Value zwValue, ValueType type) {+ Value retValue = null;++ switch(type) {+ case OBJECT:+ break;+ case ARRAY:+ retValue = toAttributeArray(zwValue);+ break;+ case STRING:+ String strVal = zwValue.getString();+ if (strVal != null) {+ retValue = Values.create(strVal);+ }+ break;+ case NUMBER:+ Double d = zwValue.getNumber();+ if (d != null) {+ retValue = Values.create(d);+ }+ break;+ case BOOLEAN:+ Boolean b = zwValue.getBoolean();+ if (b != null) {+ retValue = Values.create(b);+ }+ break;+ }+ return retValue;+ }++ private org.openremote.model.value.ArrayValue toAttributeArray(org.openremote.protocol.zwave.model.commandclasses.channel.value.Value value) {+ if (value == null) {+ return null;+ }+ ArrayValue retArray = null;+ if (value instanceof org.openremote.protocol.zwave.model.commandclasses.channel.value.ArrayValue) {+ org.openremote.protocol.zwave.model.commandclasses.channel.value.ArrayValue zwArray = (org.openremote.protocol.zwave.model.commandclasses.channel.value.ArrayValue)value;+ retArray = Values.createArray();+ for (int i = 0; i < zwArray.length(); i++) {+ retArray.add(toAttributeArrayItem(zwArray.get(i)));+ }+ if (retArray.stream().anyMatch(val -> val == null)) {+ return null;+ }+ }+ return retArray;+ }++ private org.openremote.model.value.Value toAttributeArrayItem(org.openremote.protocol.zwave.model.commandclasses.channel.value.Value zwValue) {+ if (zwValue == null) {+ return null;+ }+ org.openremote.model.value.Value retValue = null;+ switch(zwValue.getType()) {+ case NUMBER:+ Double d = zwValue.getNumber();+ if (d != null) {+ retValue = Values.create(d);+ }+ break;+ case INTEGER:+ Integer i = zwValue.getInteger();+ if (i != null) {+ retValue = Values.create(Double.valueOf(i));+ }+ break;+ case BOOLEAN:+ Boolean b = zwValue.getBoolean();+ if (b != null) {+ retValue = Values.create(b);+ }+ break;+ case STRING:+ String s = zwValue.getString();+ if (s != null) {+ retValue = Values.create(s);+ }+ break;+ }+ return retValue;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWSerialClient.java b/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWSerialClient.javanew file mode 100644index 000000000..5c7e1008a--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWSerialClient.java@@ -0,0 +1,40 @@+/*+ * Copyright 2019, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.agent.protocol.zwave;++import org.openremote.agent.protocol.ProtocolExecutorService;+import org.openremote.agent.protocol.serial.SerialIoClient;+++public class ZWSerialClient extends SerialIoClient<SerialDataPacket> {++ // Constructors -----------------------------------------------------------------------------------++ public ZWSerialClient(String port, Integer baudRate, ProtocolExecutorService executorService) {+ super(port, baudRate, executorService);+ }+++ // Public Instance Methods --------------------------------------------------------------------++ public String getSerialPort() {+ return port;+ }+}diff --git a/agent/src/main/resources/META-INF/services/org.openremote.container.ContainerService b/agent/src/main/resources/META-INF/services/org.openremote.container.ContainerServiceindex 42d87e7b1..61811e6bb 100644--- a/agent/src/main/resources/META-INF/services/org.openremote.container.ContainerService+++ b/agent/src/main/resources/META-INF/services/org.openremote.container.ContainerService@@ -8,4 +8,5 @@ org.openremote.agent.protocol.http.HttpClientProtocolorg.openremote.agent.protocol.udp.UdpClientProtocolorg.openremote.agent.protocol.tcp.TcpClientProtocolorg.openremote.agent.protocol.serial.SerialClientProtocol-org.openremote.agent.protocol.websocket.WebsocketClientProtocol\ No newline at end of file+org.openremote.agent.protocol.websocket.WebsocketClientProtocol+org.openremote.agent.protocol.zwave.ZWProtocol\ No newline at end of filediff --git a/deployment/manager/logging.properties b/deployment/manager/logging.propertiesindex 98eed4fc8..edf93fbb6 100644--- a/deployment/manager/logging.properties+++ b/deployment/manager/logging.properties@@ -109,4 +109,15 @@ org.xnio.level=WARNINGorg.apache.camel.management.level=WARNINGorg.apache.camel.impl.converter.DefaultTypeConverter.level=WARNINGorg.apache.camel.impl.DefaultShutdownStrategy.level=SEVERE-org.apache.http.client.protocol.level=SEVERE\ No newline at end of file+org.apache.http.client.protocol.level=SEVERE++# Z-Wave log file+org.openremote.protocol.zwave.ZWaveFileHandler.level=FINEST+org.openremote.protocol.zwave.ZWaveFileHandler.pattern=/zwave/zwave.log+org.openremote.protocol.zwave.ZWaveFileHandler.formatter=org.openremote.container.util.LogFormatter+org.openremote.protocol.zwave.ZWaveFileHandler.count=10+org.openremote.protocol.zwave.ZWaveFileHandler.limit=10000000+org.openremote.protocol.zwave.ZWaveFileHandler.append=true++OpenRemote.Controller.protocol.zwave.level=FINEST+OpenRemote.Controller.protocol.zwave.handlers=org.openremote.protocol.zwave.ZWaveFileHandler\ No newline at end of filediff --git a/docker-compose.yml b/docker-compose.ymlindex f20bfca3d..130127ae7 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -45,6 +45,7 @@ volumes:proxy-data:deployment-data:postgresql-data:+ zwave-data:services:@@ -84,6 +85,9 @@ services:condition: service_healthyvolumes:- deployment-data:/deployment+ - zwave-data:/zwave+ # devices:+ # - /dev/ttyACM0:/dev/ttyS0keycloak:extends:diff --git a/manager/src/main/resources/logging.properties b/manager/src/main/resources/logging.propertiesindex 40653bef7..2216c401a 100644--- a/manager/src/main/resources/logging.properties+++ b/manager/src/main/resources/logging.properties@@ -102,4 +102,15 @@ org.apache.camel.management.level=WARNINGorg.apache.camel.impl.converter.DefaultTypeConverter.level=WARNINGorg.apache.camel.impl.DefaultShutdownStrategy.level=SEVEREorg.jeasy.rules.level=WARNING-org.apache.http.client.protocol.level=SEVERE\ No newline at end of file+org.apache.http.client.protocol.level=SEVERE++# Z-Wave log file+org.openremote.protocol.zwave.ZWaveFileHandler.level=FINEST+org.openremote.protocol.zwave.ZWaveFileHandler.pattern=/zwave/zwave.log+org.openremote.protocol.zwave.ZWaveFileHandler.formatter=org.openremote.container.util.LogFormatter+org.openremote.protocol.zwave.ZWaveFileHandler.count=10+org.openremote.protocol.zwave.ZWaveFileHandler.limit=10000000+org.openremote.protocol.zwave.ZWaveFileHandler.append=true++OpenRemote.Controller.protocol.zwave.level=FINEST+OpenRemote.Controller.protocol.zwave.handlers=org.openremote.protocol.zwave.ZWaveFileHandler\ No newline at end of file