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
Initial Bluetooth Mesh protocol implementation commit
Rainer Hitzf566e919fcca
diff --git a/agent/build.gradle b/agent/build.gradleindex 815311dcb..0385fc607 100644--- a/agent/build.gradle+++ b/agent/build.gradle@@ -31,6 +31,14 @@ dependencies {}compile "com.hivemq:hivemq-mqtt-client:$hiveMQClientVersion"++ compile ("com.github.weliem.blessed-bluez:blessed:$bluetoothVersion") {+ // Libraries should not depend on a logging implementation and/or alpha versions!+ exclude group: "org.slf4j"++ // Conflicts with asm version bundled with GWT+ exclude group: "org.ow2.asm"+ }}jar {diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/AddressRange.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/AddressRange.javanew file mode 100644index 000000000..6430a0e80--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/AddressRange.java@@ -0,0 +1,133 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import java.util.ArrayList;+import java.util.List;++public abstract class AddressRange extends Range {++ int lowAddress;++ int highAddress;++ /**+ * Returns the low address of the allocated group address+ *+ * @return low address+ */+ public abstract int getLowAddress();++ /**+ * Returns the high address of the allocated group range+ *+ * @return highAddress of the group range+ */+ public abstract int getHighAddress();++ @Override+ public int range() {+ return highAddress - lowAddress;+ }++ @Override+ public boolean overlaps(final Range otherRange) {+ if (otherRange instanceof AddressRange) {+ final AddressRange otherAddressRange = (AddressRange) otherRange;+ return overlaps(lowAddress, highAddress, otherAddressRange.getLowAddress(), otherAddressRange.getHighAddress());+ }+ return false;+ }++ /**+ * Subtracts a range from a list of ranges+ *+ * @param ranges ranges to be subtracted+ * @param other {@link AllocatedGroupRange} range+ * @return a resulting {@link AllocatedGroupRange} or null otherwise+ */+ public static List<AllocatedGroupRange> minus(final List<AllocatedGroupRange> ranges, final AllocatedGroupRange other) {+ List<AllocatedGroupRange> results = new ArrayList<>();+ for (AllocatedGroupRange range : ranges) {+ results.addAll(range.minus(other));+ results = mergeGroupRanges(results);+ }+ /*ranges.clear();+ ranges.addAll(results);*/+ return results;+ }++ /**+ * Deducts a range from another+ *+ * @param other right {@link AllocatedGroupRange}+ * @return a resulting {@link AllocatedGroupRange} or null otherwise+ */+ List<AllocatedGroupRange> minus(final AllocatedGroupRange other) {+ final List<AllocatedGroupRange> results = new ArrayList<>();+ // Left: |------------| |-----------| |---------|+ // - - -+ // Right: |-----------------| or |---| or |----|+ // = = =+ // Result: |---| |-----------| |--|+ if (other.lowAddress > lowAddress) {+ final AllocatedGroupRange leftSlice = new AllocatedGroupRange(lowAddress, (Math.min(highAddress, other.lowAddress - 1)));+ results.add(leftSlice);+ }++ // Left: |----------| |-----------| |--------|+ // - - -+ // Right: |----------------| or |----| or |---|+ // = = =+ // Result: |--| |--| |--------|+ if (other.highAddress < highAddress) {+ final AllocatedGroupRange rightSlice = new AllocatedGroupRange(Math.max(other.highAddress + 1, lowAddress), highAddress);+ results.add(rightSlice);+ }+ return results;+ }++ /**+ * Subtracts a range from a list of ranges+ *+ * @param ranges ranges to be subtracted+ * @param other {@link AllocatedUnicastRange} range+ * @return a resulting {@link AllocatedUnicastRange} or null otherwise+ */+ public static List<AllocatedUnicastRange> minus(final List<AllocatedUnicastRange> ranges, final AllocatedUnicastRange other) {+ List<AllocatedUnicastRange> results = new ArrayList<>();+ for (AllocatedUnicastRange range : ranges) {+ results.addAll(range.minus(other));+ results = mergeUnicastRanges(results);+ }+ return results;+ }++ /**+ * Deducts a range from another+ *+ * @param other right {@link AllocatedUnicastRange}+ * @return a resulting {@link AllocatedUnicastRange} or null otherwise+ */+ List<AllocatedUnicastRange> minus(final AllocatedUnicastRange other) {+ final List<AllocatedUnicastRange> results = new ArrayList<>();+ // Left: |------------| |-----------| |---------|+ // - - -+ // Right: |-----------------| or |---| or |----|+ // = = =+ // Result: |---| |-----------| |--|+ if (other.lowAddress > lowAddress) {+ final AllocatedUnicastRange leftSlice = new AllocatedUnicastRange(lowAddress, (Math.min(highAddress, other.lowAddress - 1)));+ results.add(leftSlice);+ }++ // Left: |----------| |-----------| |--------|+ // - - -+ // Right: |----------------| or |----| or |---|+ // = = =+ // Result: |--| |--| |--------|+ if (other.highAddress < highAddress) {+ final AllocatedUnicastRange rightSlice = new AllocatedUnicastRange(Math.max(other.highAddress + 1, lowAddress), highAddress);+ results.add(rightSlice);+ }+ return results;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/AllocatedGroupRange.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/AllocatedGroupRange.javanew file mode 100644index 000000000..a888232a2--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/AllocatedGroupRange.java@@ -0,0 +1,69 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;++public class AllocatedGroupRange extends AddressRange {++ @Override+ public final int getLowerBound() {+ return MeshAddress.START_GROUP_ADDRESS;+ }++ @Override+ public final int getUpperBound() {+ return MeshAddress.END_GROUP_ADDRESS;+ }++ /**+ * Constructs {@link AllocatedGroupRange} for provisioner+ *+ * @param lowAddress low address of group range+ * @param highAddress high address of group range+ */+ public AllocatedGroupRange(final int lowAddress, final int highAddress) {+ lowerBound = MeshAddress.START_GROUP_ADDRESS;+ upperBound = MeshAddress.END_GROUP_ADDRESS;+ if (!MeshAddress.isValidGroupAddress(lowAddress))+ throw new IllegalArgumentException("Low address must range from 0xC000 to 0xFEFF");++ if (!MeshAddress.isValidGroupAddress(highAddress))+ throw new IllegalArgumentException("High address must range from 0xC000 to 0xFEFF");++ /*if(lowAddress > highAddress)+ throw new IllegalArgumentException("low address must be lower than the high address");*/++ this.lowAddress = lowAddress;+ this.highAddress = highAddress;+ }++ AllocatedGroupRange() {+ }++ @Override+ public int getLowAddress() {+ return lowAddress;+ }++ /**+ * Sets the low address of the allocated group address+ *+ * @param lowAddress of the group range+ */+ public void setLowAddress(final int lowAddress) {+ this.lowAddress = lowAddress;+ }++ @Override+ public int getHighAddress() {+ return highAddress;+ }++ /**+ * Sets the high address of the group address+ *+ * @param highAddress of the group range+ */+ public void setHighAddress(final int highAddress) {+ this.highAddress = highAddress;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/AllocatedSceneRange.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/AllocatedSceneRange.javanew file mode 100644index 000000000..26adaa339--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/AllocatedSceneRange.java@@ -0,0 +1,148 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import java.util.ArrayList;+import java.util.List;++public class AllocatedSceneRange extends Range {++ private int firstScene;++ private int lastScene;++ @Override+ public final int getLowerBound() {+ return lowerBound;+ }++ @Override+ public final int getUpperBound() {+ return upperBound;+ }++ public List<Range> minus(final Range left, final Range right) {+ return null;+ }++ /**+ * Constructs {@link AllocatedSceneRange} for provisioner+ *+ * @param firstScene high address of group range+ * @param lastScene low address of group range+ */+ public AllocatedSceneRange(final int firstScene, final int lastScene) {+ lowerBound = 0x0001;+ upperBound = 0xFFFF;+ if (firstScene < lowerBound || firstScene > upperBound)+ throw new IllegalArgumentException("firstScene value must range from 0x0000 to 0xFFFF");++ if (lastScene < lowerBound || lastScene > upperBound)+ throw new IllegalArgumentException("lastScene value must range from 0x0000 to 0xFFFF");++ /*if (firstScene > lastScene)+ throw new IllegalArgumentException("firstScene value must be lower than the lastScene value");*/++ this.firstScene = firstScene;+ this.lastScene = lastScene;+ }++ AllocatedSceneRange() {+ }++ /**+ * Returns the low address of the allocated group address+ *+ * @return low address+ */+ public int getLastScene() {+ return lastScene;+ }++ /**+ * Sets the low address of the allocated group address+ *+ * @param lastScene of the group range+ */+ public void setLastScene(final int lastScene) {+ this.lastScene = lastScene;+ }++ /**+ * Returns the high address of the allocated group range+ *+ * @return firstScene of the group range+ */+ public int getFirstScene() {+ return firstScene;+ }++ /**+ * Sets the high address of the group address+ *+ * @param firstScene of the group range+ */+ public void setFirstScene(final int firstScene) {+ this.firstScene = firstScene;+ }++ @Override+ public int range() {+ return lastScene - firstScene;+ }++ @Override+ public boolean overlaps(final Range otherRange) {+ if (otherRange instanceof AllocatedSceneRange) {+ final AllocatedSceneRange otherSceneRange = (AllocatedSceneRange) otherRange;+ return overlaps(firstScene, lastScene, otherSceneRange.getFirstScene(), otherSceneRange.getLastScene());+ }+ return false;+ }++ /**+ * Subtracts a range from a list of ranges+ *+ * @param ranges ranges to be subtracted+ * @param other {@link AllocatedSceneRange} range+ * @return a resulting {@link AllocatedSceneRange} or null otherwise+ */+ public static List<AllocatedSceneRange> minus(final List<AllocatedSceneRange> ranges, final AllocatedSceneRange other) {+ List<AllocatedSceneRange> results = new ArrayList<>();+ for (AllocatedSceneRange range : ranges) {+ results.addAll(range.minus(other));+ results = mergeSceneRanges(results);+ }+ /*ranges.clear();+ ranges.addAll(results);*/+ return results;+ }++ /**+ * Deducts a range from another+ *+ * @param other right {@link AllocatedSceneRange}+ * @return a resulting {@link AllocatedSceneRange} or null otherwise+ */+ private List<AllocatedSceneRange> minus(final AllocatedSceneRange other) {+ final List<AllocatedSceneRange> results = new ArrayList<>();+ // Left: |------------| |-----------| |---------|+ // - - -+ // Right: |-----------------| or |---| or |----|+ // = = =+ // Result: |---| |-----------| |--|+ if (other.firstScene > firstScene) {+ final AllocatedSceneRange leftSlice = new AllocatedSceneRange(firstScene, (Math.min(lastScene, other.firstScene - 1)));+ results.add(leftSlice);+ }++ // Left: |----------| |-----------| |--------|+ // - - -+ // Right: |----------------| or |----| or |---|+ // = = =+ // Result: |--| |--| |--------|+ if (other.lastScene < lastScene) {+ final AllocatedSceneRange rightSlice = new AllocatedSceneRange(Math.max(other.lastScene + 1, firstScene), lastScene);+ results.add(rightSlice);+ }+ return results;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/AllocatedUnicastRange.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/AllocatedUnicastRange.javanew file mode 100644index 000000000..cfc8e120e--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/AllocatedUnicastRange.java@@ -0,0 +1,73 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;++public class AllocatedUnicastRange extends AddressRange {++ /**+ * Constructs {@link AllocatedUnicastRange} for provisioner+ *+ * @param lowAddress low address of unicast range+ * @param highAddress high address of unicast range+ */+ public AllocatedUnicastRange(final int lowAddress, final int highAddress) {+ lowerBound = MeshAddress.START_UNICAST_ADDRESS;+ upperBound = MeshAddress.END_UNICAST_ADDRESS;+ if (!MeshAddress.isValidUnicastAddress(lowAddress))+ throw new IllegalArgumentException("Low address must range from 0x0001 to 0x7FFF");++ if (!MeshAddress.isValidUnicastAddress(highAddress))+ throw new IllegalArgumentException("High address must range from 0x0001 to 0x7FFF");++ /*if(lowAddress > highAddress)+ throw new IllegalArgumentException("low address must be lower than the high address");*/++ this.lowAddress = lowAddress;+ this.highAddress = highAddress;+ }++ AllocatedUnicastRange() {+ }++ @Override+ public final int getLowerBound() {+ return lowAddress;+ }++ @Override+ public final int getUpperBound() {+ return upperBound;+ }++ @Override+ public int getLowAddress() {+ return lowAddress;+ }++ /**+ * Sets the low address of the allocated unicast address+ *+ * @param lowAddress of the unicast range+ */+ public void setLowAddress(final int lowAddress) {+ if (!MeshAddress.isValidUnicastAddress(lowAddress))+ throw new IllegalArgumentException("Low address must range from 0x0000 to 0x7FFF");+ this.lowAddress = lowAddress;+ }++ @Override+ public int getHighAddress() {+ return highAddress;+ }++ /**+ * Sets the high address of the allocated unicast address+ *+ * @param highAddress of the group range+ */+ public void setHighAddress(final int highAddress) {+ if (!MeshAddress.isValidUnicastAddress(lowAddress))+ throw new IllegalArgumentException("High address must range from 0x0000 to 0x7FFF");+ this.highAddress = highAddress;+ }+}\ No newline at end of filediff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/ApplicationKey.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/ApplicationKey.javanew file mode 100644index 000000000..fde7fb778--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/ApplicationKey.java@@ -0,0 +1,70 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import org.openremote.agent.protocol.bluetooth.mesh.utils.SecureUtils;++import javax.validation.constraints.NotNull;++/**+ * Wrapper class for application key+ */+public final class ApplicationKey extends MeshKey {++ private int boundNetKeyIndex = 0;+ private int aid;+ private int oldAid;++ /**+ * Constructs a ApplicationKey object with a given key index and network key+ *+ * @param keyIndex 12-bit app key index+ * @param key 16-byte app key+ */+ public ApplicationKey(final int keyIndex, @NotNull final byte[] key) {+ super(keyIndex, key);+ name = "Application Key " + (keyIndex + 1);+ aid = SecureUtils.calculateK4(key);+ }++ /**+ * Returns the index of the associated netkey+ *+ * @return network key index+ */+ public int getBoundNetKeyIndex() {+ return boundNetKeyIndex;+ }++ /**+ * Set the net key index to which the app key is associated with+ *+ * @param boundNetKeyIndex network key index+ */+ public void setBoundNetKeyIndex(final int boundNetKeyIndex) {+ this.boundNetKeyIndex = boundNetKeyIndex;+ }++ @Override+ public void setKey(@NotNull final byte[] key) {+ super.setKey(key);+ aid = SecureUtils.calculateK4(key);+ }++ @Override+ public void setOldKey(final byte[] oldKey) {+ super.setOldKey(oldKey);+ if (oldKey != null)+ oldAid = SecureUtils.calculateK4(oldKey);+ }++ public int getAid() {+ return aid;+ }++ public int getOldAid() {+ return oldAid;+ }++ public ApplicationKey clone() throws CloneNotSupportedException {+ return (ApplicationKey) super.clone();+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/ApplicationKeysConfig.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/ApplicationKeysConfig.javanew file mode 100644index 000000000..33f4250ce--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/ApplicationKeysConfig.java@@ -0,0 +1,46 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import java.util.List;++/**+ * Contains the configuration required when exporting a selected number of Application Keys in a mesh network.+ */+public class ApplicationKeysConfig extends ExportConfig {++ public static class ExportAll implements Builder {+ @Override+ public ApplicationKeysConfig build() {+ return new ApplicationKeysConfig(this);+ }+ }++ /**+ * Use this class to configure when exporting all the Application Keys.+ */+ public static class ExportSome implements Builder {++ private final List<ApplicationKey> keys;++ /**+ * Constructs ExportSome to export only a selected number of Application Keys when exporting a mesh network.+ *+ * @param keys List of Application Keys to export.+ */+ public ExportSome(final List<ApplicationKey> keys) {+ this.keys = keys;+ }++ protected List<ApplicationKey> getKeys() {+ return keys;+ }++ @Override+ public ApplicationKeysConfig build() {+ return new ApplicationKeysConfig(this);+ }+ }++ ApplicationKeysConfig(final Builder config) {+ super(config);+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BaseMeshNetwork.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BaseMeshNetwork.javanew file mode 100644index 000000000..f066658d1--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BaseMeshNetwork.java@@ -0,0 +1,972 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import org.openremote.agent.protocol.bluetooth.mesh.transport.ProvisionedMeshNode;+import org.openremote.agent.protocol.bluetooth.mesh.transport.ConfigNetKeyUpdate;+import org.openremote.agent.protocol.bluetooth.mesh.transport.ConfigAppKeyUpdate;+import org.openremote.agent.protocol.bluetooth.mesh.transport.ConfigKeyRefreshPhaseSet;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;+import org.openremote.agent.protocol.bluetooth.mesh.utils.ProxyFilter;+import org.openremote.agent.protocol.bluetooth.mesh.utils.SecureUtils;+import org.openremote.agent.protocol.bluetooth.mesh.NetworkKey;++import java.util.ArrayList;+import java.util.Arrays;+import java.util.Calendar;+import java.util.Collections;+import java.util.Comparator;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.UUID;+import java.util.logging.Logger;+++abstract public class BaseMeshNetwork {++ public static final Logger LOG = Logger.getLogger(BaseMeshNetwork.class.getName());++ // Key refresh phases+ public static final int NORMAL_OPERATION = 0; //Normal operation+ public static final int IV_UPDATE_ACTIVE = 1; //IV Update active++ final String meshUUID;+ protected final Comparator<ApplicationKey> appKeyComparator = (key1, key2) -> Integer.compare(key1.getKeyIndex(), key2.getKeyIndex());+ protected final Comparator<NetworkKey> netKeyComparator = (key1, key2) -> Integer.compare(key1.getKeyIndex(), key2.getKeyIndex());+ protected MeshNetworkCallbacks mCallbacks;+ String schema = "http://json-schema.org/draft-04/schema#";+ String id = "http://www.bluetooth.com/specifications/assigned-numbers/mesh-profile/cdb-schema.json#";+ String version = "1.0";+ String meshName = "nRF Mesh Network";+ long timestamp = System.currentTimeMillis();+ boolean partial = false;+ IvIndex ivIndex = new IvIndex(0, false, Calendar.getInstance());+ List<NetworkKey> netKeys = new ArrayList<>();+ List<ApplicationKey> appKeys = new ArrayList<>();+ List<Provisioner> provisioners = new ArrayList<>();+ List<ProvisionedMeshNode> nodes = new ArrayList<>();+ List<Group> groups = new ArrayList<>();+ List<Scene> scenes = new ArrayList<>();+ protected Map<Integer, ArrayList<Integer>> networkExclusions = new HashMap<>();+ //Library related attributes+ int unicastAddress = 0x0001;+ boolean lastSelected;+ //protected SparseIntArray sequenceNumbers = new SparseIntArray();+ protected Map<Integer, Integer> sequenceNumbers = new HashMap<>();+ private ProxyFilter proxyFilter;+ protected final Comparator<ProvisionedMeshNode> nodeComparator = (node1, node2) ->+ Integer.compare(node1.getUnicastAddress(), node2.getUnicastAddress());+ protected final Comparator<Group> groupComparator = (group1, group2) ->+ Integer.compare(group1.getAddress(), group2.getAddress());+ // protected final Comparator<Scene> sceneComparator = (scene1, scene2) ->+ // Integer.compare(scene1.getNumber(), scene2.getNumber());+ protected final Comparator<AllocatedUnicastRange> unicastRangeComparator = (range1, range2) ->+ Integer.compare(range1.getLowAddress(), range2.getLowAddress());+ protected final Comparator<AllocatedGroupRange> groupRangeComparator = (range1, range2) ->+ Integer.compare(range1.getLowAddress(), range2.getLowAddress());+ protected final Comparator<AllocatedSceneRange> sceneRangeComparator = (range1, range2) ->+ Integer.compare(range1.getFirstScene(), range2.getFirstScene());++ BaseMeshNetwork(final String meshUUID) {+ this.meshUUID = meshUUID;+ }++ private boolean isNetKeyExists(final byte[] key) {+ for (int i = 0; i < netKeys.size(); i++) {+ if (Arrays.equals(key, netKeys.get(i).getKey())) {+ return true;+ }+ }+ return false;+ }++ /**+ * Creates an Network key+ *+ * @return {@link NetworkKey}+ * @throws IllegalArgumentException in case the generated application key already exists+ */+ public synchronized NetworkKey createNetworkKey() throws IllegalArgumentException {+ final NetworkKey key = new NetworkKey(getAvailableNetKeyIndex(), MeshParserUtils.toByteArray(SecureUtils.generateRandomNetworkKey()));+ key.setMeshUuid(meshUUID);+ return key;+ }++ /**+ * Adds a Net key to the list of net keys with the given key index+ *+ * @param newNetKey Network key+ * @throws IllegalArgumentException if the key already exists.+ */+ public synchronized boolean addNetKey(final NetworkKey newNetKey) {+ if (isNetKeyExists(newNetKey.getKey())) {+ throw new IllegalArgumentException("Net key already exists, check the contents of the key!");+ } else {+ newNetKey.setMeshUuid(meshUUID);+ netKeys.add(newNetKey);+ notifyNetKeyAdded(newNetKey);+ }+ return true;+ }++ private int getAvailableNetKeyIndex() {+ if (netKeys.isEmpty()) {+ return 0;+ } else {+ Collections.sort(netKeys, netKeyComparator);+ final int index = netKeys.size() - 1;+ return netKeys.get(index).getKeyIndex() + 1;+ }+ }++ /**+ * Update a network key with the given 16-byte hexadecimal string in the mesh network.+ *+ * <p>+ * Updating a NetworkKey's key value requires initiating a Key Refresh Procedure. A NetworkKey that's in use+ * would require a Key Refresh Procedure to update it's key contents. However a NetworkKey that's not in could+ * be updated without this procedure. If the key is in use, call {@link #distributeNetKey(NetworkKey, byte[])}+ * to initiate the Key Refresh Procedure.+ * </p>+ *+ * @param networkKey Network key+ * @param newNetKey 16-byte hexadecimal string+ * @throws IllegalArgumentException if the key is already in use+ */+ public synchronized boolean updateNetKey(final NetworkKey networkKey, final String newNetKey) throws IllegalArgumentException {+ if (MeshParserUtils.validateKeyInput(newNetKey)) {+ final byte[] key = MeshParserUtils.toByteArray(newNetKey);+ if (isNetKeyExists(key)) {+ throw new IllegalArgumentException("Net key value is already in use.");+ }++ final int keyIndex = networkKey.getKeyIndex();+ final NetworkKey netKey = getNetKey(keyIndex);+ if (!isKeyInUse(netKey)) {+ //We check if the contents of the key are the same+ //This will return true only if the key index and the key are the same+ if (netKey.equals(networkKey)) {+ netKey.setKey(key);+ return updateMeshKey(netKey);+ } else {+ return false;+ }+ } else {+ throw new IllegalArgumentException("Unable to update a network key that's already in use. ");+ }+ }+ return false;+ }++ /**+ * Update a network key in the mesh network.+ *+ * <p>+ * Updating a NetworkKey's key value requires initiating a Key Refresh Procedure. A NetworkKey that's in use+ * would require a Key Refresh Procedure to update it's key contents. However a NetworkKey that's not in could+ * be updated without this procedure. If the key is in use, call {@link #distributeNetKey(NetworkKey, byte[])}+ * to initiate the Key Refresh Procedure.+ * </p>+ *+ * @param networkKey Network key+ * @throws IllegalArgumentException if the key is already in use+ */+ public synchronized boolean updateNetKey(final NetworkKey networkKey) throws IllegalArgumentException {+ final int keyIndex = networkKey.getKeyIndex();+ final NetworkKey key = getNetKey(keyIndex);+ //We check if the contents of the key are the same+ //This will return true only if the key index and the key are the same+ if (key.equals(networkKey)) {+ // The name might be updated so we must update the key.+ return updateMeshKey(networkKey);+ } else {+ //If the keys are not the same we check if its in use before updating the key+ if (!isKeyInUse(key)) {+ //We check if the contents of the key are the same+ //This will return true only if the key index and the key are the same+ return updateMeshKey(networkKey);+ } else {+ throw new IllegalArgumentException("Unable to update a network key that's already in use.");+ }+ }+ }++ /**+ * Distribute Net Key will start the key refresh procedure and return the newly updated key.+ *+ * <p>+ * This process contains three phases.+ * {@link NetworkKey#KEY_DISTRIBUTION} - Distribution of the new Keys {@link #distributeNetKey(NetworkKey, byte[])}.+ * {@link NetworkKey#USING_NEW_KEYS} - Switching to the new keys {@link #switchToNewKey(NetworkKey)}.+ * {@link NetworkKey#REVOKE_OLD_KEYS} - Revoking old keys {@link #revokeOldKey(NetworkKey)}.+ * The new key is distributed to the provisioner node by setting the currently used key as the old key and setting the+ * currently used key to the new key value. This will change the phase of the network key to{@link NetworkKey#KEY_DISTRIBUTION}.+ * During this phase a node will transmit using the old key but may receive using both old and the new key. After a successful+ * distribution to the provisioner, the user may start sending {@link ConfigNetKeyUpdate} messages to the respective nodes in the+ * network that requires updating. In addition if the user wishes to update the AppKey call {@link #distributeAppKey(ApplicationKey, byte[])}+ * to update the Application Key on the provisioner and then distribute it to other nodes by sending {@link ConfigAppKeyUpdate} to+ * update an AppKey. However it shall be only successfully processed if the NetworkKey bound to the Application Key is in+ * {@link NetworkKey#KEY_DISTRIBUTION} and the received app key value is different or when the received AppKey value is the same as+ * previously received value. Also note that sending a ConfigNetKeyUpdate during {@link NetworkKey#NORMAL_OPERATION} will switch the+ * phase to {@link NetworkKey#KEY_DISTRIBUTION}. Once distribution is completed, call {@link #switchToNewKey(NetworkKey)} and+ * send {@link ConfigKeyRefreshPhaseSet} to other nodes.+ * </p>+ *+ * @param networkKey Network key+ * @param newNetKey 16-byte key+ * @throws IllegalArgumentException the key value is already in use.+ */+ public synchronized NetworkKey distributeNetKey(final NetworkKey networkKey, final byte[] newNetKey) throws IllegalArgumentException {+ if (validateKey(newNetKey)) {+ if (isNetKeyExists(newNetKey)) {+ throw new IllegalArgumentException("Net key value is already in use.");+ }++ final int keyIndex = networkKey.getKeyIndex();+ final NetworkKey netKey = getNetKey(keyIndex);+ if (netKey.equals(networkKey)) {+ if (netKey.distributeKey(newNetKey)) {+ updateNodeKeyStatus(netKey);+ if (updateMeshKey(netKey)) {+ return netKey;+ }+ }+ }+ }+ return null;+ }++ /**+ * Updates the NodeKey object for Network or Application Keys+ *+ * @param meshKey Updated Key+ */+ private void updateNodeKeyStatus(final MeshKey meshKey) {+ for (Provisioner provisioner : provisioners) {+ for (ProvisionedMeshNode node : nodes) {+ if (node.getUuid().equalsIgnoreCase(provisioner.getProvisionerUuid())) {+ if (meshKey instanceof NetworkKey) {+ for (NodeKey key : node.getAddedNetKeys()) {+ if (key.getIndex() == meshKey.getKeyIndex()) {+ key.setUpdated(true);+ }+ }+ } else {+ for (NodeKey key : node.getAddedAppKeys()) {+ if (key.getIndex() == meshKey.getKeyIndex()) {+ key.setUpdated(true);+ }+ }+ }+ }+ }+ }+ }++ /**+ * Switches the new key, this will initiate the provisioner node transmitting messages using the new keys but will+ * support receiving messages using both old and the new key.+ *+ * <p>+ * This must be called after {@link #distributeNetKey(NetworkKey, byte[])}+ * </p>+ *+ * @param networkKey Network key to switch too+ * @return true if success or false otherwise+ * @throws IllegalArgumentException if the provided key is not the same as the distributed key.+ */+ public synchronized boolean switchToNewKey(final NetworkKey networkKey) throws IllegalArgumentException {+ if (!netKeys.contains(networkKey)) {+ throw new IllegalArgumentException("Network Key not distributed");+ }+ return networkKey.switchToNewKey();+ }++ /**+ * Revokes the old key.+ * <p>+ * This initiates {@link NetworkKey#REVOKE_OLD_KEYS} of the Key Refresh Procedure in which user must send {@link ConfigKeyRefreshPhaseSet}+ * message with transition set to {@link NetworkKey#REVOKE_OLD_KEYS} to the other nodes going through the Key Refresh Procedure.+ * The library at this point will set the given Network Key's Phase to {@link NetworkKey#NORMAL_OPERATION}.+ * </p>+ *+ * @param networkKey Network key that was distributed+ * @return true if success or false otherwise+ */+ public boolean revokeOldKey(final NetworkKey networkKey) {+ if (netKeys.contains(networkKey)) {+ return networkKey.revokeOldKey();+ }+ return false;+ }+++ /**+ * Removes a network key from the network key list+ *+ * @param networkKey key to be removed+ * @throws IllegalArgumentException if the key is in use or if it does not exist in the list of keys+ */+ public synchronized boolean removeNetKey(final NetworkKey networkKey) throws IllegalArgumentException {+ if (!isKeyInUse(networkKey)) {+ if (netKeys.remove(networkKey)) {+ notifyNetKeyDeleted(networkKey);+ return true;+ } else {+ throw new IllegalArgumentException("Key does not exist.");+ }+ }+ throw new IllegalArgumentException("Unable to delete a network key that's already in use.");+ }++ /**+ * Returns an application key with a given key index+ *+ * @param keyIndex index+ */+ public synchronized NetworkKey getNetKey(final int keyIndex) {+ for (NetworkKey key : netKeys) {+ if (keyIndex == key.getKeyIndex()) {+ try {+ return key.clone();+ } catch (CloneNotSupportedException e) {+ LOG.severe("Error while cloning key: " + e.getMessage());+ }+ }+ }+ return null;+ }++ /**+ * Creates an application key+ *+ * @return {@link ApplicationKey}+ * @throws IllegalArgumentException in case the generated application key already exists+ */+ public synchronized ApplicationKey createAppKey() throws IllegalArgumentException {+ if (netKeys.isEmpty()) {+ throw new IllegalStateException("Cannot create an App Key without a Network key. Consider creating a network key first");+ }++ final ApplicationKey key = new ApplicationKey(getAvailableAppKeyIndex(), MeshParserUtils.toByteArray(SecureUtils.generateRandomApplicationKey()));+ key.setMeshUuid(meshUUID);+ return key;+ }++ /**+ * Adds an app key to the list of keys with the given key index. If there is an existing key with the same index,+ * an illegal argument exception is thrown.+ *+ * @param newAppKey application key+ * @throws IllegalArgumentException if app key already exists+ */+ public synchronized boolean addAppKey(final ApplicationKey newAppKey) {+ if (netKeys.isEmpty()) {+ throw new IllegalStateException("Cannot create an App Key without a Network key. Consider creating a network key first");+ }++ if (isAppKeyExists(newAppKey.getKey())) {+ throw new IllegalArgumentException("App key already exists, check the contents of the key!");+ } else {+ newAppKey.setMeshUuid(meshUUID);+ appKeys.add(newAppKey);+ notifyAppKeyAdded(newAppKey);+ }+ return true;+ }++ private int getAvailableAppKeyIndex() {+ if (appKeys.isEmpty()) {+ return 0;+ } else {+ Collections.sort(appKeys, appKeyComparator);+ final int index = appKeys.size() - 1;+ return appKeys.get(index).getKeyIndex() + 1;+ }+ }++ /**+ * Returns an application key with a given key index+ *+ * @param keyIndex index+ */+ public synchronized ApplicationKey getAppKey(final int keyIndex) {+ for (ApplicationKey key : appKeys) {+ if (keyIndex == key.getKeyIndex()) {+ try {+ return key.clone();+ } catch (CloneNotSupportedException e) {+ LOG.severe("Error while cloning key: " + e.getMessage());+ }+ }+ }+ return null;+ }++ /**+ * Returns a list of application keys bound to a Network key+ *+ * @param boundNetKeyIndex Network Key index+ */+ protected synchronized List<ApplicationKey> getAppKeys(final int boundNetKeyIndex) {+ final List<ApplicationKey> applicationKeys = new ArrayList<>();+ for (ApplicationKey applicationKey : appKeys) {+ if (applicationKey.getBoundNetKeyIndex() == boundNetKeyIndex) {+ applicationKeys.add(applicationKey);+ }+ }+ return applicationKeys;+ }++ private boolean isAppKeyExists(final byte[] appKey) {+ for (int i = 0; i < appKeys.size(); i++) {+ final ApplicationKey applicationKey = appKeys.get(i);+ if (Arrays.equals(applicationKey.getKey(), appKey)) {+ return true;+ }+ }+ return false;+ }++ /**+ * Updates an app key with a given key in the mesh network.+ *+ * <p>+ * Updates the Key if it is not use, if not Updating a Key's key value requires initiating a Key Refresh Procedure.+ * This requires the bound NetworkKey of the AppKey to be updated. A NetworkKey that's in use would require a+ * Key Refresh Procedure to update it's key contents. However a NetworkKey that's not in could be updated without this+ * procedure. If the key is in use, call {@link #distributeNetKey(NetworkKey, byte[])} to initiate the Key Refresh Procedure.+ * </p>+ *+ * @param applicationKey {@link ApplicationKey}+ * @param newAppKey Application key+ * @throws IllegalArgumentException if the key is in use.+ */+ public synchronized boolean updateAppKey(final ApplicationKey applicationKey, final String newAppKey) throws IllegalArgumentException {+ if (MeshParserUtils.validateKeyInput(newAppKey)) {+ final byte[] key = MeshParserUtils.toByteArray(newAppKey);+ if (isNetKeyExists(key)) {+ throw new IllegalArgumentException("Net key already in use");+ }++ final int keyIndex = applicationKey.getKeyIndex();+ final ApplicationKey appKey = getAppKey(keyIndex);+ if (!isKeyInUse(appKey)) {+ //We check if the contents of the key are the same+ //This will return true only if the key index and the key are the same+ if (appKey.equals(applicationKey)) {+ appKey.setKey(key);+ return updateMeshKey(appKey);+ } else {+ return false;+ }+ } else {+ throw new IllegalArgumentException("Unable to update a application key that's already in use.");+ }+ }+ return false;+ }++ /**+ * Updates an app key in the mesh network.+ *+ * <p>+ * Updates the Key if it is not use, if not Updating a Key's key value requires initiating a Key Refresh Procedure. This requires+ * the bound NetworkKey of the AppKey to be updated. A NetworkKey that's in use would require aKey Refresh Procedure to update+ * it's key contents. However a NetworkKey that's not in could be updated without this procedure. If the key is in use, call+ * {@link #distributeNetKey(NetworkKey, byte[])} to initiate the Key Refresh Procedure. After distributing the NetworkKey bound to+ * the Application Key, user may call {@link #distributeAppKey(ApplicationKey, byte[])} to update the corresponding ApplicationKey.+ * </p>+ *+ * @param applicationKey {@link ApplicationKey}+ * @throws IllegalArgumentException if the key is already in use+ */+ public synchronized boolean updateAppKey(final ApplicationKey applicationKey) throws IllegalArgumentException {+ final int keyIndex = applicationKey.getKeyIndex();+ final ApplicationKey key = getAppKey(keyIndex);+ //If the keys are not the same we check if its in use before updating the key+ if (!isKeyInUse(key)) {+ //We check if the contents of the key are the same+ //This will return true only if the key index and the key are the same+ return updateMeshKey(applicationKey);+ } else {+ throw new IllegalArgumentException("Unable to update a application key that's already in use.");+ }+ }++ /**+ * Distributes/updates the provisioner node's the application key and returns the updated Application Key.+ *+ * <p>+ * This will only work if the NetworkKey bound to this ApplicationKey is in Phase 1 of the Key Refresh Procedure. Therefore the NetworkKey+ * must be updated first before updating it's bound application key. Call {@link #distributeNetKey(NetworkKey, byte[])} to initiate the+ * Key Refresh Procedure to update a Network Key that's in use by the provisioner or the nodes, if it has not been started already.+ * To update a key that's not in use call {@link #updateAppKey(ApplicationKey, String)}+ * <p>+ * Once the provisioner nodes' AppKey is updated user must distribute the updated AppKey to the nodes. This can be done by sending+ * {@link ConfigAppKeyUpdate} message with the new key.+ * </p>+ *+ * @param applicationKey Network key+ * @param newAppKey 16-byte key+ * @throws IllegalArgumentException the key value is already in use.+ */+ public synchronized ApplicationKey distributeAppKey(final ApplicationKey applicationKey, final byte[] newAppKey) throws IllegalArgumentException {+ if (validateKey(newAppKey)) {+ if (isAppKeyExists(newAppKey)) {+ throw new IllegalArgumentException("App key value is already in use.");+ }++ final int keyIndex = applicationKey.getKeyIndex();+ final ApplicationKey appKey = getAppKey(keyIndex);+ if (appKey.equals(applicationKey)) {+ if(appKey.distributeKey(newAppKey)){+ updateNodeKeyStatus(appKey);+ if (updateMeshKey(appKey)) {+ return appKey;+ }+ }+ }+ }+ return null;+ }++ private boolean updateMeshKey(final MeshKey key) {+ if (key instanceof ApplicationKey) {+ ApplicationKey appKey = null;+ for (int i = 0; i < appKeys.size(); i++) {+ final ApplicationKey tempKey = appKeys.get(i);+ if (tempKey.getKeyIndex() == key.getKeyIndex()) {+ appKey = (ApplicationKey) key;+ appKeys.set(i, appKey);+ break;+ }+ }+ if (appKey != null) {+ notifyAppKeyUpdated(appKey);+ return true;+ }+ } else {+ NetworkKey netKey = null;+ for (int i = 0; i < netKeys.size(); i++) {+ final NetworkKey tempKey = netKeys.get(i);+ if (tempKey.getKeyIndex() == key.getKeyIndex()) {+ netKey = (NetworkKey) key;+ netKeys.set(i, netKey);+ break;+ }+ }+ if (netKey != null) {+ netKey.setTimestamp(System.currentTimeMillis());+ notifyNetKeyUpdated(netKey);+ return true;+ }+ }+ return false;+ }++ /**+ * Removes an app key from the app key list+ *+ * @param appKey app key to be removed+ * @throws IllegalArgumentException if the key is in use or if it does not exist in the list of keys+ */+ public synchronized boolean removeAppKey(final ApplicationKey appKey) throws IllegalArgumentException {+ if (isKeyInUse(appKey)) {+ throw new IllegalArgumentException("Unable to delete an app key that's in use.");+ } else {+ if (appKeys.remove(appKey)) {+ notifyAppKeyDeleted(appKey);+ return true;+ } else {+ throw new IllegalArgumentException("Key does not exist.");+ }+ }+ }++ /**+ * Checks if the app key is in use.+ *+ * <p>+ * This will check if the specified app key is added to a node other than the selected provisioner node+ * </p>+ *+ * @param meshKey {@link MeshKey}+ */+ public synchronized boolean isKeyInUse(final MeshKey meshKey) {+ for (ProvisionedMeshNode node : nodes) {+ if (!node.getUuid().equalsIgnoreCase(getSelectedProvisioner().getProvisionerUuid())) {+ final int index = meshKey.getKeyIndex();+ //We need to check if a key index is in use by checking in the added net/app key indexes+ if (meshKey instanceof ApplicationKey) {+ return MeshParserUtils.isNodeKeyExists(node.getAddedAppKeys(), index);+ } else {+ return MeshParserUtils.isNodeKeyExists(node.getAddedNetKeys(), index);+ }+ }+ }+ return false;+ }++ /**+ * Creates a provisioner+ *+ * @param name Provisioner name+ * @param unicastRange {@link AllocatedUnicastRange} for the provisioner+ * @param groupRange {@link AllocatedGroupRange} for the provisioner+ * @param sceneRange {@link AllocatedSceneRange} for the provisioner+ * @return {@link Provisioner}+ * @throws IllegalArgumentException if the name is empty+ */+ public synchronized Provisioner createProvisioner(final String name,+ final AllocatedUnicastRange unicastRange,+ final AllocatedGroupRange groupRange,+ final AllocatedSceneRange sceneRange) throws IllegalArgumentException {+ if (name == null || name.length() == 0) {+ throw new IllegalArgumentException("Name cannot be empty.");+ }+ final List<AllocatedUnicastRange> unicastRanges = new ArrayList<>();+ final List<AllocatedGroupRange> groupRanges = new ArrayList<>();+ final List<AllocatedSceneRange> sceneRanges = new ArrayList<>();+ unicastRanges.add(unicastRange != null ? unicastRange : new AllocatedUnicastRange(0x0001, 0x7FFF));+ groupRanges.add(groupRange != null ? groupRange : new AllocatedGroupRange(0xC000, 0xFEFF));+ sceneRanges.add(sceneRange != null ? sceneRange : new AllocatedSceneRange(0x0001, 0xFFFF));+ final Provisioner provisioner = new Provisioner(UUID.randomUUID().toString(), unicastRanges, groupRanges, sceneRanges, meshUUID);+ provisioner.setProvisionerName(name);+ return provisioner;+ }++ /**+ * Selects a provisioner if there are multiple provisioners.+ *+ * @param provisioner {@link Provisioner}+ */+ public synchronized final void selectProvisioner(final Provisioner provisioner) {+ provisioner.setLastSelected(true);+ for (Provisioner prov : provisioners) {+ if (!prov.getProvisionerUuid().equalsIgnoreCase(provisioner.getProvisionerUuid())) {+ prov.setLastSelected(false);+ }+ }+ notifyProvisionersUpdated(provisioners);+ }++ /**+ * Adds a provisioner to the network+ *+ * @param provisioner {@link Provisioner}+ * @throws IllegalArgumentException if unicast address is invalid, in use by a node+ */+ public synchronized boolean addProvisioner(final Provisioner provisioner) throws IllegalArgumentException {++ if (provisioner.allocatedUnicastRanges.isEmpty()) {+ if (provisioner.getProvisionerAddress() != null) {+ throw new IllegalArgumentException("Provisioner has no allocated unicast range assigned.");+ }+ }++ for (Provisioner other : provisioners) {+ if (provisioner.hasOverlappingUnicastRanges(other.getAllocatedUnicastRanges())+ || provisioner.hasOverlappingGroupRanges(other.getAllocatedGroupRanges())+ || provisioner.hasOverlappingSceneRanges(other.getAllocatedSceneRanges())) {+ throw new IllegalArgumentException("Provisioner ranges overlap.");+ }+ }++ if (!provisioner.isAddressWithinAllocatedRange(provisioner.getProvisionerAddress())) {+ throw new IllegalArgumentException("Unicast address assigned to a provisioner must be within an allocated unicast address range.");+ }++ if (isAddressInUse(provisioner.getProvisionerAddress())) {+ throw new IllegalArgumentException("Unicast address is in use by another node.");+ }++ if (provisioner.isNodeAddressInUse(nodes)) {+ throw new IllegalArgumentException("Unicast address is already in use.");+ }++ if (isProvisionerUuidInUse(provisioner.getProvisionerUuid())) {+ throw new IllegalArgumentException("Provisioner uuid already in use.");+ }++ provisioner.assignProvisionerAddress(provisioner.getProvisionerAddress());+ provisioners.add(provisioner);+ notifyProvisionerAdded(provisioner);+ if (provisioner.isLastSelected()) {+ selectProvisioner(provisioner);+ }+ if (provisioner.getProvisionerAddress() != null) {+ final ProvisionedMeshNode node = new ProvisionedMeshNode(provisioner, netKeys, appKeys);+ nodes.add(node);+ notifyNodeAdded(node);+ }+ return true;+ }++ /**+ * Returns the mesh node with the corresponding unicast address+ *+ * @param unicastAddress unicast address of the node+ */+ public synchronized ProvisionedMeshNode getNode(final int unicastAddress) {+ for (ProvisionedMeshNode node : nodes) {+ if (node.hasUnicastAddress(unicastAddress)) {+ return node;+ }+ }+ return null;+ }++ /**+ * Returns the mesh node with the corresponding unicast address+ *+ * @param uuid unicast address of the node+ */+ public synchronized ProvisionedMeshNode getNode(final String uuid) {+ for (ProvisionedMeshNode node : nodes) {+ if (node.getUuid().equalsIgnoreCase(uuid)) {+ return node;+ }+ }+ return null;+ }++ /**+ * Loads the sequence numbers known to the network+ */+ protected synchronized void loadSequenceNumbers() {+ for (ProvisionedMeshNode node : nodes) {+ sequenceNumbers.put(node.getUnicastAddress(), node.getSequenceNumber());+ }+ }++ private boolean isAddressInUse(final Integer address) {+ if (address == null)+ return false;++ for (ProvisionedMeshNode node : nodes) {+ if (address == node.getUnicastAddress()) {+ return true;+ }+ }+ return false;+ }++ protected synchronized boolean isProvisionerUuidInUse(final String uuid) {+ for (Provisioner provisioner : provisioners) {+ if (provisioner.getProvisionerUuid().equalsIgnoreCase(uuid)) {+ return true;+ }+ }+ return false;+ }+++++ final synchronized void notifyProvisionersUpdated(final List<Provisioner> provisioner) {+ if (mCallbacks != null) {+ mCallbacks.onProvisionersUpdated(provisioner);+ }+ }++ final synchronized void notifyProvisionerAdded(final Provisioner provisioner) {+ if (mCallbacks != null) {+ mCallbacks.onProvisionerAdded(provisioner);+ }+ }++ final synchronized void notifyNodeAdded(final ProvisionedMeshNode node) {+ if (mCallbacks != null) {+ mCallbacks.onNodeAdded(node);+ }+ }++ final synchronized void notifyNodeDeleted(final ProvisionedMeshNode meshNode) {+ if (mCallbacks != null) {+ mCallbacks.onNodeDeleted(meshNode);+ }+ }++ final synchronized void notifyProvisionerDeleted(final Provisioner provisioner) {+ if (mCallbacks != null) {+ mCallbacks.onProvisionerDeleted(provisioner);+ }+ }++ final synchronized void notifyNodeUpdated(final ProvisionedMeshNode node) {+ if (mCallbacks != null) {+ mCallbacks.onNodeUpdated(node);+ }+ }++ final synchronized void notifyNetworkUpdated() {+ if (mCallbacks != null) {+ mCallbacks.onMeshNetworkUpdated();+ }+ }++ final synchronized void notifyNetKeyAdded(final NetworkKey networkKey) {+ if (mCallbacks != null) {+ mCallbacks.onNetworkKeyAdded(networkKey);+ }+ }++ final synchronized void notifyNetKeyDeleted(final NetworkKey networkKey) {+ if (mCallbacks != null) {+ mCallbacks.onNetworkKeyDeleted(networkKey);+ }+ }++ final synchronized void notifyAppKeyAdded(final ApplicationKey appKey) {+ if (mCallbacks != null) {+ mCallbacks.onApplicationKeyAdded(appKey);+ }+ }++ final synchronized void notifyAppKeyUpdated(final ApplicationKey appKey) {+ if (mCallbacks != null) {+ mCallbacks.onApplicationKeyUpdated(appKey);+ }+ }++ final synchronized void notifyNetKeyUpdated(final NetworkKey networkKey) {+ if (mCallbacks != null) {+ mCallbacks.onNetworkKeyUpdated(networkKey);+ }+ }++ final synchronized void notifyAppKeyDeleted(final ApplicationKey appKey) {+ if (mCallbacks != null) {+ mCallbacks.onApplicationKeyDeleted(appKey);+ }+ }++ private boolean validateKey(final byte[] key) {+ if (key.length != 16)+ throw new IllegalArgumentException("Key must be 16 bytes");+ return true;+ }+++ /**+ * Returns the list of {@link Provisioner}+ */+ public synchronized List<Provisioner> getProvisioners() {+ return Collections.unmodifiableList(provisioners);+ }++ /**+ * Returns the selected provisioner in the network+ */+ public synchronized Provisioner getSelectedProvisioner() {+ for (Provisioner provisioner : provisioners) {+ if (provisioner.isLastSelected()) {+ return provisioner;+ }+ }+ return null;+ }++ /**+ * Returns the list of {@link ProvisionedMeshNode}+ */+ public synchronized List<ProvisionedMeshNode> getNodes() {+ return Collections.unmodifiableList(nodes);+ }++ /**+ * Returns the map of network exclusions+ */+ public synchronized Map<Integer, ArrayList<Integer>> getNetworkExclusions() {+ return Collections.unmodifiableMap(networkExclusions);+ }++ /**+ * Returns the {@link ProxyFilter} set on the proxy+ */+ /* @Nullable */+ public synchronized ProxyFilter getProxyFilter() {+ return proxyFilter;+ }++ /**+ * Sets the {@link ProxyFilter} settings on the proxy+ * <p>+ * Please note that this is not persisted within the node since the filter is reinitialized to a whitelist filter upon connecting to a proxy node.+ * Therefore after setting a proxy filter and disconnecting users will have to manually+ * <p/>+ */+ public synchronized void setProxyFilter(final ProxyFilter proxyFilter) {+ this.proxyFilter = proxyFilter;+ }++ /**+ * Deletes a mesh node from the list of provisioned nodes+ *+ * <p>+ * Note that deleting a node manually will not reset the node, but only be deleted from the stored list of provisioned nodes.+ * However you may still be able to connect to the same node, if it was not reset since the network may still exist. This+ * would be useful to in case if a node was physically reset and needs to be removed from the mesh network/db+ * </p>+ *+ * @param meshNode node to be deleted+ * @return true if deleted and false otherwise+ */+ public synchronized boolean deleteNode(ProvisionedMeshNode meshNode) {+ //Let's go through the nodes and delete if a node exists+ boolean nodeDeleted = false;+ for (ProvisionedMeshNode node : nodes) {+ if (node.getUuid().equalsIgnoreCase(meshNode.getUuid())) {+ excludeNode(node);+ nodes.remove(node);+ notifyNodeDeleted(node);+ nodeDeleted = true;+ break;+ }+ }+ //We must also check if there is a provisioner based on the node we deleted+ if (nodeDeleted) {+ for (Provisioner provisioner : provisioners) {+ if (provisioner.getProvisionerUuid().equalsIgnoreCase(meshNode.getUuid())) {+ provisioners.remove(provisioner);+ notifyProvisionerDeleted(provisioner);+ break;+ }+ }+ }++ return nodeDeleted;+ }++ /**+ * Excludes a node from the mesh network.+ * The given node will marked as excluded and added to the exclusion list and the node will be removed once+ * the Key Refresh Procedure is completed. After the IV update procedure, when the network transitions to an+ * IV Normal Operation state with a higher IV index, the exclusionList object that has the ivIndex property+ * value that is lower by a count of two (or more) than the current IV index of the network is removed from+ * the networkExclusions property array.+ *+ * @param node Provisioned mesh node.+ */+ private void excludeNode(final ProvisionedMeshNode node) {+ //Exclude node+ node.setExcluded(true);+ notifyNodeUpdated(node);+ ArrayList<Integer> addresses = networkExclusions.get(ivIndex.getIvIndex());+ if (addresses == null) {+ addresses = new ArrayList<>();+ }++ for (Integer address : node.getElements().keySet()) {+ if (!addresses.contains(address)) {+ addresses.add(address);+ }+ }++ networkExclusions.put(ivIndex.getIvIndex(), addresses);+ notifyNetworkUpdated();+ }++++}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshAgent.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshAgent.javanew file mode 100644index 000000000..7612f810c--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshAgent.java@@ -0,0 +1,104 @@+/*+ * Copyright 2021, 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.bluetooth.mesh;++import org.openremote.model.asset.agent.Agent;+import org.openremote.model.asset.agent.AgentDescriptor;+import org.openremote.model.value.AttributeDescriptor;+import org.openremote.model.value.ValueType;++import javax.persistence.Entity;+import java.util.Optional;++@Entity+public class BluetoothMeshAgent extends Agent<BluetoothMeshAgent, BluetoothMeshProtocol, BluetoothMeshAgentLink> {++ public static final AttributeDescriptor<String> NETWORK_KEY = new AttributeDescriptor<String>("networkKey", ValueType.TEXT);+ public static final AttributeDescriptor<String> APPLICATION_KEY = new AttributeDescriptor<String>("applicationKey", ValueType.TEXT);+ public static final AttributeDescriptor<String> SOURCE_ADDRESS = new AttributeDescriptor<String>("sourceAddress", ValueType.TEXT);+ public static final AttributeDescriptor<Integer> SEQUENCE_NUMBER = new AttributeDescriptor<Integer>("sequenceNumber", ValueType.POSITIVE_INTEGER);+ public static final AttributeDescriptor<Integer> MTU = new AttributeDescriptor<Integer>("mtu", ValueType.POSITIVE_INTEGER);++ public static AgentDescriptor<BluetoothMeshAgent, BluetoothMeshProtocol, BluetoothMeshAgentLink> DESCRIPTOR = new AgentDescriptor<>(+ BluetoothMeshAgent.class, BluetoothMeshProtocol.class, BluetoothMeshAgentLink.class, null+ );++ /**+ * For use by hydrators (i.e. JPA/Jackson)+ */+ protected BluetoothMeshAgent() {++ }++ public BluetoothMeshAgent(String name) {+ super(name);++ }++ @Override+ public BluetoothMeshProtocol getProtocolInstance() {+ return new BluetoothMeshProtocol(this);+ }++ public Optional<String> getNetworkKey() {+ return getAttributes().getValue(NETWORK_KEY);+ }++ public BluetoothMeshAgent setNetworkKey(String value) {+ getAttributes().getOrCreate(NETWORK_KEY).setValue(value);+ return this;+ }++ public Optional<String> getApplicationKey() {+ return getAttributes().getValue(APPLICATION_KEY);+ }++ public BluetoothMeshAgent setApplicationKey(String value) {+ getAttributes().getOrCreate(APPLICATION_KEY).setValue(value);+ return this;+ }++ public Optional<String> getSourceAddress() {+ return getAttributes().getValue(SOURCE_ADDRESS);+ }++ public BluetoothMeshAgent setSourceAddress(String value) {+ getAttributes().getOrCreate(SOURCE_ADDRESS).setValue(value);+ return this;+ }++ public Optional<Integer> getSequenceNumber() {+ return getAttributes().getValue(SEQUENCE_NUMBER);+ }++ public BluetoothMeshAgent setSequenceNumber(Integer value) {+ getAttributes().getOrCreate(SEQUENCE_NUMBER).setValue(value);+ return this;+ }++ public Optional<Integer> getMtu() {+ return getAttributes().getValue(MTU);+ }++ public BluetoothMeshAgent setMtu(Integer value) {+ getAttributes().getOrCreate(MTU).setValue(value);+ return this;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshAgentLink.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshAgentLink.javanew file mode 100644index 000000000..63d4987c2--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshAgentLink.java@@ -0,0 +1,66 @@+/*+ * Copyright 2021, 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.bluetooth.mesh;++import org.openremote.model.asset.agent.AgentLink;++import javax.validation.constraints.Max;+import javax.validation.constraints.Min;+import javax.validation.constraints.NotBlank;+import javax.validation.constraints.NotNull;+import javax.validation.constraints.Pattern;+import java.util.Optional;++public class BluetoothMeshAgentLink extends AgentLink<BluetoothMeshAgentLink> {++ @Min(0)+ @Max(2147483647)+ @NotNull+ protected Integer appKeyIndex;++ @Pattern(regexp = "^([0-9A-Fa-f]{4})$")+ protected String address;++ @NotBlank+ protected String modelName;++ // For Hydrators+ protected BluetoothMeshAgentLink() {+ }++ public BluetoothMeshAgentLink(String id, Integer appKeyIndex, String address, String modelName) {+ super(id);+ this.appKeyIndex = appKeyIndex;+ this.address = address;+ this.modelName = modelName;+ }++ public Optional<Integer> getAppKeyIndex() {+ return Optional.ofNullable(appKeyIndex);+ }++ public Optional<String> getAddress() {+ return Optional.ofNullable(address);+ }++ public Optional<String> getModelName() {+ return Optional.ofNullable(modelName);+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshNetwork.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshNetwork.javanew file mode 100644index 000000000..eb85b7151--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshNetwork.java@@ -0,0 +1,518 @@+/*+ * Copyright 2021, 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.bluetooth.mesh;++import com.welie.blessed.BluetoothCentralManager;+import com.welie.blessed.BluetoothCentralManagerCallback;+import com.welie.blessed.BluetoothCommandStatus;+import com.welie.blessed.BluetoothPeripheral;+import com.welie.blessed.ScanResult;+import org.openremote.agent.protocol.bluetooth.mesh.models.SigModel;+import org.openremote.agent.protocol.bluetooth.mesh.models.SigModelParser;+import org.openremote.agent.protocol.bluetooth.mesh.provisionerstates.UnprovisionedMeshNode;+import org.openremote.agent.protocol.bluetooth.mesh.transport.ControlMessage;+import org.openremote.agent.protocol.bluetooth.mesh.transport.Element;+import org.openremote.agent.protocol.bluetooth.mesh.transport.MeshMessage;+import org.openremote.agent.protocol.bluetooth.mesh.transport.MeshModel;+import org.openremote.agent.protocol.bluetooth.mesh.transport.ProvisionedMeshNode;+import org.openremote.model.asset.agent.ConnectionStatus;+import org.openremote.model.syslog.SyslogCategory;++import java.util.ArrayList;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.concurrent.ScheduledExecutorService;+import java.util.function.Consumer;+import java.util.logging.Logger;++public class BluetoothMeshNetwork extends BluetoothCentralManagerCallback implements MeshManagerCallbacks, MeshStatusCallbacks, BluetoothMeshProxyRxCallback{++ // Class Members ------------------------------------------------------------------------------++ public static final Logger LOG = SyslogCategory.getLogger(SyslogCategory.PROTOCOL, BluetoothMeshNetwork.class.getName());+++ // Constants ----------------------------------------------------------------------------------++ public static final int SCAN_DURATION = 10000;+++ // Private Instance Fields --------------------------------------------------------------------++ private volatile BluetoothMeshProxyScanner proxyScanner;+ private volatile BluetoothMeshProxy bluetoothMeshProxy;+ private volatile MeshManagerApi meshManagerApi;+ private volatile boolean isConnected = false;++ private final ScheduledExecutorService executorService;+ private final BluetoothCentralManager bluetoothCentral;+ private final SequenceNumberPersistencyManager sequenceNumberManager;+ private final MainThreadManager mainThreadManager;+ private final Consumer<ConnectionStatus> statusConsumer;+ private final NetworkKey networkKey;+ private final int sourceUnicastAddress;+ private final Map<Integer, ApplicationKey> applicationKeyMap;+ private final Integer mtu;+ private final Map<Integer, ShadowMeshElement> elementMap = new HashMap<>();+++ // Constructors -------------------------------------------------------------------------------++ public BluetoothMeshNetwork(BluetoothCentralManager bluetoothCentral, SequenceNumberPersistencyManager sequenceNumberManager, MainThreadManager mainThread,+ int unicastAddress, NetworkKey networkKey, Map<Integer, ApplicationKey> applicationKeyMap,+ int mtu, int sequenceNumber, ScheduledExecutorService executorService, Consumer<ConnectionStatus> statusConsumer) {+ this.bluetoothCentral = bluetoothCentral;+ this.sequenceNumberManager = sequenceNumberManager;+ this.mainThreadManager = mainThread;+ this.networkKey = networkKey;+ this.sourceUnicastAddress = unicastAddress;+ this.applicationKeyMap = applicationKeyMap;+ this.mtu = mtu;+ this.executorService = executorService;+ this.statusConsumer = statusConsumer;++ this.meshManagerApi = new MeshManagerApi(executorService);+ this.meshManagerApi.setMeshManagerCallbacks(this);+ this.meshManagerApi.setMeshStatusCallbacks(this);++ this.meshManagerApi.resetMeshNetwork(unicastAddress);+ MeshNetwork network = this.meshManagerApi.getMeshNetwork();+ network.addNetKey(networkKey);+ for (Map.Entry<Integer, ApplicationKey> keyEntry : applicationKeyMap.entrySet()) {+ network.addAppKey(keyEntry.getValue());+ }+ int provisionerAddress = getMeshNetwork().getSelectedProvisioner().getProvisionerAddress();+ ProvisionedMeshNode provisionerNode = getMeshNetwork().getNode(provisionerAddress);+ provisionerNode.setSequenceNumber(sequenceNumber);+ }+++ // Implements BluetoothCentralManagerCallback -------------------------------------------------++ @Override+ public synchronized void onConnectedPeripheral(BluetoothPeripheral peripheral) {+ if (proxyScanner != null) {+ proxyScanner.onConnectedPeripheral(peripheral);+ }+ if (bluetoothMeshProxy != null) {+ bluetoothMeshProxy.onConnectedPeripheral(peripheral);+ }+ }++ @Override+ public synchronized void onConnectionFailed(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {+ if (proxyScanner != null) {+ proxyScanner.onConnectionFailed(peripheral, status);+ }+ if (bluetoothMeshProxy != null) {+ bluetoothMeshProxy.onConnectionFailed(peripheral, status);+ }+ }++ @Override+ public synchronized void onDisconnectedPeripheral(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {+ if (proxyScanner != null) {+ proxyScanner.onDisconnectedPeripheral(peripheral, status);+ }+ if (bluetoothMeshProxy != null) {+ bluetoothMeshProxy.onDisconnectedPeripheral(peripheral, status);+ }+ }++ @Override+ public synchronized void onDiscoveredPeripheral(BluetoothPeripheral peripheral, ScanResult scanResult) {+ if (proxyScanner != null) {+ proxyScanner.onDiscoveredPeripheral(peripheral, scanResult);+ }+ if (bluetoothMeshProxy != null) {+ bluetoothMeshProxy.onDiscoveredPeripheral(peripheral, scanResult);+ }+ }++ @Override+ public synchronized void onScanFailed(int errorCode) {+ if (proxyScanner != null) {+ proxyScanner.onScanFailed(errorCode);+ }+ if (bluetoothMeshProxy != null) {+ bluetoothMeshProxy.onScanFailed(errorCode);+ }+ }+++ // Implements MeshManagerCallbacks ------------------------------------------------------------++ @Override+ public void onNetworkLoaded(MeshNetwork meshNetwork) {++ }++ @Override+ public void onNetworkUpdated(MeshNetwork meshNetwork) {++ }++ @Override+ public void onNetworkLoadFailed(String error) {++ }++ @Override+ public void onNetworkImported(MeshNetwork meshNetwork) {++ }++ @Override+ public void onNetworkImportFailed(String error) {++ }++ @Override+ public void sendProvisioningPdu(UnprovisionedMeshNode meshNode, byte[] pdu) {++ }++ @Override+ public synchronized void onMeshPduCreated(byte[] pdu) {+ LOG.info("Sending PDU to mesh proxy: [data:" + dataAsHexString(pdu) + "]");+ if (bluetoothMeshProxy != null) {+ bluetoothMeshProxy.sendData(getMtu(), pdu, (proxy, data, isSuccess) -> {+ if (isSuccess) {+ LOG.info("Succeeded to send PDU to mesh proxy: [data:" + dataAsHexString(pdu) + "]");+ meshManagerApi.handleWriteCallbacks(getMtu(), data);+ } else {+ LOG.warning("Failed to send PDU to mesh proxy: [data:" + dataAsHexString(pdu) + "]");+ }+ });+ Integer sourceAddress = getMeshNetwork().getSelectedProvisioner().getProvisionerAddress();+ if (sourceAddress != null) {+ ProvisionedMeshNode sourceNode = getMeshNetwork().getNode(sourceAddress);+ if (sourceNode != null) {+ final int newSequenceNumber = sourceNode.getSequenceNumber();+ executorService.execute(() -> sequenceNumberManager.save(networkKey, sourceUnicastAddress, newSequenceNumber));+ }+ }+ }+ }++ @Override+ public int getMtu() {+ return mtu;+ }+++ // Implements BluetoothMeshProxyRxCallback ----------------------------------------------------++ @Override+ public synchronized void onRxData(byte[] data) {+ if (meshManagerApi != null) {+ meshManagerApi.handleNotifications(getMtu(), data);+ }+ }+++ // Implements MeshStatusCallbacks -------------------------------------------------------------++ @Override+ public void onTransactionFailed(int dst, boolean hasIncompleteTimerExpired) {++ }++ @Override+ public void onUnknownPduReceived(int src, byte[] accessPayload) {++ }++ @Override+ public void onBlockAcknowledgementProcessed(int dst, ControlMessage message) {++ }++ @Override+ public void onBlockAcknowledgementReceived(int src, ControlMessage message) {++ }++ @Override+ public void onMeshMessageProcessed(int dst, MeshMessage meshMessage) {++ }++ @Override+ public synchronized void onMeshMessageReceived(int src, MeshMessage meshMessage) {+ LOG.info("Received mesh message: address='" + String.format("0x%04X", src) + "', message='" + meshMessage.getClass().getName() + "'");+ ShadowMeshElement element = elementMap.get(src);+ if (element != null) {+ element.onMeshMessageReceived(meshMessage);+ } else {+ LOG.info(+ "Could not find element to process the received mesh message: address='" + String.format("0x%04X", src) ++ "', message='" + meshMessage.getClass().getName() + "'"+ );+ }+ }++ @Override+ public void onMessageDecryptionFailed(String meshLayer, String errorMessage) {+ LOG.warning("Failed to decrypt Bluetooth mesh message: [meshLayer: '" + meshLayer+ "', errorMessage: '" + errorMessage + "']");+ }+++ // Public Instance Methods --------------------------------------------------------------------++ public synchronized void connect() {+ if (isConnected) {+ return;+ }+ isConnected = true;+ bluetoothMeshProxy = null;+ proxyScanner = new BluetoothMeshProxyScanner(mainThreadManager, bluetoothCentral, executorService);+ proxyScanner.start(networkKey, SCAN_DURATION, new BluetoothMeshProxyScannerCallback() {+ @Override+ public void onMeshProxiesScanned(List<BluetoothMeshProxy> meshProxies, Integer errorCode) {+ LOG.info("Finished scanning Bluetooth mesh proxies.");+ if (errorCode == null) {+ for (BluetoothMeshProxy curMeshProxy : meshProxies) {+ LOG.info("Scan found Bluetooth mesh proxy: [Name=" + curMeshProxy.getPeripheral().getName() + ", Address=" + curMeshProxy.getPeripheral().getAddress() + ", Rssi=" + curMeshProxy.getRssi() + "]");+ }+ if (meshProxies.size() > 0) {+ synchronized (BluetoothMeshNetwork.this) {+ // TODO: consider rssi and choose proxy in close proximity+ BluetoothMeshNetwork.this.bluetoothMeshProxy = meshProxies.get(0);+ BluetoothMeshNetwork.this.bluetoothMeshProxy.setRxDataCallback(BluetoothMeshNetwork.this);+ BluetoothMeshNetwork.this.bluetoothMeshProxy.connect(statusConsumer, new BluetoothMeshProxyConnectCallback() {+ @Override+ public void onMeshProxyConnected(BluetoothPeripheral peripheral, boolean isSuccess) {+ synchronized (BluetoothMeshNetwork.this) {+ if (isSuccess) {+ LOG.info("Successfully connected to Bluetooth mesh proxy: [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + "]");+ } else {+ LOG.warning("Failed to connect to Bluetooth mesh proxy: [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + "]");+ BluetoothMeshNetwork.this.bluetoothMeshProxy.disconnect();+ BluetoothMeshNetwork.this.bluetoothMeshProxy = null;+ }+ }+ }+ });+ }+ } else {+ LOG.info("No Bluetooth mesh proxy found!");+ executorService.execute(() -> statusConsumer.accept(ConnectionStatus.ERROR));+ }+ } else {+ LOG.info("Failed to scan Bluetooth mesh proxies: [error code=" + errorCode + "]");+ executorService.execute(() -> statusConsumer.accept(ConnectionStatus.ERROR));+ }+ }+ });+ }++ public synchronized void disconnect() {+ isConnected = false;+ if (proxyScanner != null) {+ proxyScanner.stop();+ proxyScanner = null;+ }+ if (bluetoothMeshProxy != null) {+ bluetoothMeshProxy.disconnect();+ bluetoothMeshProxy = null;+ }+ bluetoothMeshProxy = null;+ }++ public synchronized boolean isConnected() {+ boolean isConnected = false;+ if (bluetoothMeshProxy != null) {+ isConnected = bluetoothMeshProxy.isConnected();+ }+ return isConnected;+ }++ public synchronized MeshManagerApi getMeshManagerApi() {+ return meshManagerApi;+ }++ public ApplicationKey getApplicationKey(int keyIndex) {+ return applicationKeyMap.get(keyIndex);+ }++ public NetworkKey getNetworkKey() {+ return networkKey;+ }++ public synchronized MeshNetwork getMeshNetwork() {+ MeshNetwork network = null;+ MeshManagerApi api = getMeshManagerApi();+ if (api != null) {+ network = api.getMeshNetwork();+ }+ return network;+ }++ public synchronized ProvisionedMeshNode getNode(int sourceAddress) {+ ProvisionedMeshNode node = null;+ MeshNetwork network = getMeshNetwork();+ if (network != null) {+ node = network.getNode(sourceAddress);+ }+ return node;+ }++ public synchronized void addMeshModel(int address, int modelId, int appKeyIndex) {+ MeshNetwork network = getMeshNetwork();+ MeshModel model = SigModelParser.getSigModel(modelId);+ if (model == null) {+ LOG.severe("Bluetooth Mesh model with ID='" + String.format("0x%04X", modelId) + "' is not supported.");+ return;+ }+ // TODO: proper handling of unicast and group addresses+ if (address < 0xC000) {+ ProvisionedMeshNode node = getNode(address);+ if (node == null) {+ List<NetworkKey> networkKeys = new ArrayList<>(1);+ networkKeys.add(networkKey);+ List<ApplicationKey> applicationKeys = new ArrayList<>(applicationKeyMap.size());+ applicationKeys.addAll(applicationKeyMap.values());+ node = new ProvisionedMeshNode(network.getSelectedProvisioner(), networkKeys, applicationKeys);+ node.setUnicastAddress(address);+ }+ Map<Integer, Element> oldElementMap = node.getElements();+ Map<Integer, Element> newElementMap = new HashMap<>();+ Map<Integer, MeshModel> newModelMap = new HashMap<>();+ Element oldElement = oldElementMap.get(address);+ if (oldElement != null) {+ newModelMap.putAll(oldElement.getMeshModels());+ }+ int locationDescriptor = 0;+ model.setBoundAppKeyIndex(appKeyIndex);+ newModelMap.put(modelId, model);+ Element newElement = new Element(address, locationDescriptor, newModelMap);+ newElementMap.putAll(oldElementMap);+ newElementMap.put(address, newElement);+ node.setElements(newElementMap);+ if (getNode(address) == null) {+ network.nodes.add(node);+ network.sequenceNumbers.put(node.getUnicastAddress(), node.getSequenceNumber());+ network.unicastAddress = network.nextAvailableUnicastAddress(node.getNumberOfElements(), network.getSelectedProvisioner());+ node.setMeshUuid(network.getMeshUUID());+ network.loadSequenceNumbers();+ }+ }+ addShadowModel(address, modelId, appKeyIndex);+ }++ public synchronized void addSensorValueConsumer(int address, int modelId, Consumer<Object> consumer) {+ ShadowMeshModel model = searchShadowModel(address, modelId);+ if (model != null) {+ model.addSensorValueConsumer(consumer);+ }+ }++ public synchronized void removeSensorValueConsumer(int address, int modelId, Consumer<Object> consumer) {+ ShadowMeshModel model = searchShadowModel(address, modelId);+ if (model != null) {+ model.removeSensorValueConsumer(consumer);+ }+ }++ public synchronized void sendMeshSetCommand(int address, int modelId, Object value) {+ if (isConnected()) {+ ShadowMeshModel model = searchShadowModel(address, modelId);+ if (model != null) {+ model.sendSetCommand(value);+ } else {+ SigModel sigModel = SigModelParser.getSigModel(modelId);+ String modelName = sigModel != null ? sigModel.getModelName() : String.format("0x%04X", modelId);+ LOG.warning(+ "Failed to send mesh command value '" + value + "' because couldn't find mesh model: address:'" ++ String.format("0x%04X", address) + "', model: '" + modelName + '"'+ );+ }+ }+ }++ public synchronized void sendMeshGetCommand(int address, int modelId) {+ if (isConnected()) {+ ShadowMeshModel model = searchShadowModel(address, modelId);+ if (model != null) {+ model.sendGetCommand();+ } else {+ SigModel sigModel = SigModelParser.getSigModel(modelId);+ String modelName = sigModel != null ? sigModel.getModelName() : String.format("0x%04X", modelId);+ LOG.warning(+ "Failed to send mesh get status command because couldn't find mesh model: address:'" ++ String.format("0x%04X", address) + "', model: '" + modelName + '"'+ );+ }+ }+ }++ public synchronized void sendMeshGetCommands(int address) {+ if (isConnected()) {+ ShadowMeshElement element = elementMap.get(address);+ if (element != null) {+ List<ShadowMeshModel> models = element.getMeshModels();+ for (ShadowMeshModel curModel : models) {+ sendMeshGetCommand(address, curModel.getModelId());+ }+ }+ }+ }++ public synchronized void sendMeshGetCommands() {+ if (isConnected()) {+ for (Integer address : elementMap.keySet()) {+ sendMeshGetCommands(address);+ }+ }+ }+++ // Private Instance Methods -------------------------------------------------------------------++ private ShadowMeshModel searchShadowModel(int address, int modelId) {+ ShadowMeshModel model = null;+ ShadowMeshElement element = elementMap.get(address);+ if (element != null) {+ model = element.searchShadowModel(modelId);+ }+ return model;+ }++ private void addShadowModel(int address, int modelId, int appKeyIndex) {+ if (!elementMap.containsKey(address)) {+ elementMap.put(address, new ShadowMeshElement(executorService,this, address));+ }+ ShadowMeshElement element = elementMap.get(address);+ element.addShadowModel(modelId, appKeyIndex);+ }++ private String dataAsHexString(byte[] data) {+ if (data == null) {+ return "";+ }+ StringBuilder builder = new StringBuilder();+ for (int i = 0; i < data.length; i++) {+ builder.append(String.format("0x%02X%s", data[i] & 0xFF, i == (data.length - 1) ? "" : ", "));+ }+ return builder.toString();+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProtocol.javanew file mode 100644index 000000000..ac39e489a--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProtocol.java@@ -0,0 +1,439 @@+/*+ * Copyright 2021, 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.bluetooth.mesh;++import com.welie.blessed.BluetoothCentralManager;+import com.welie.blessed.BluetoothCentralManagerCallback;+import com.welie.blessed.BluetoothCommandStatus;+import com.welie.blessed.BluetoothPeripheral;+import com.welie.blessed.ScanResult;+import org.openremote.agent.protocol.AbstractProtocol;+import org.openremote.agent.protocol.bluetooth.mesh.models.SigModelParser;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;+import org.openremote.model.Container;+import org.openremote.model.asset.Asset;+import org.openremote.model.asset.AssetTreeNode;+import org.openremote.model.asset.agent.ConnectionStatus;+import org.openremote.model.asset.impl.ThingAsset;+import org.openremote.model.attribute.Attribute;+import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.attribute.AttributeState;+import org.openremote.model.attribute.MetaItem;+import org.openremote.model.protocol.ProtocolAssetDiscovery;+import org.openremote.model.syslog.SyslogCategory;+import org.openremote.model.value.MetaItemType;+import org.openremote.model.value.ValueFormat;+import org.openremote.model.value.ValueType;++import java.util.HashMap;+import java.util.Map;+import java.util.concurrent.Future;+import java.util.concurrent.ScheduledExecutorService;+import java.util.concurrent.ScheduledFuture;+import java.util.concurrent.TimeUnit;+import java.util.function.Consumer;+import java.util.logging.Logger;++import static org.openremote.model.asset.agent.AgentLink.getOrThrowAgentLinkProperty;+import static org.openremote.model.value.MetaItemType.AGENT_LINK;++public class BluetoothMeshProtocol extends AbstractProtocol<BluetoothMeshAgent, BluetoothMeshAgentLink> implements ProtocolAssetDiscovery {++ // Constants ------------------------------------------------------------------------------------++ public static final String PROTOCOL_DISPLAY_NAME = "Bluetooth Mesh";+ public static final int DEFAULT_MTU = 20;+ public static final int DEFAULT_SEQUENCE_NUMBER = 1;+++ // Class Members --------------------------------------------------------------------------------++ public static final Logger LOG = SyslogCategory.getLogger(SyslogCategory.PROTOCOL, BluetoothMeshProtocol.class.getName());+++ // Private Instance Fields --------------------------------------------------------------------++ private volatile BluetoothCentralManager bluetoothCentral;+ private volatile BluetoothMeshNetwork meshNetwork;+ private volatile ScheduledFuture<?> mainThreadFuture;+ private final Map<AttributeRef, Consumer<Object>> sensorValueConsumerMap = new HashMap<>();+ private final MainThreadManager mainThread = new MainThreadManager();+ private final SequenceNumberPersistencyManager sequenceNumberManager = new SequenceNumberPersistencyManager();++ private final BluetoothCentralManagerCallback bluetoothManagerCallback = new BluetoothCentralManagerCallback() {+ @Override+ public void onConnectedPeripheral(BluetoothPeripheral peripheral) {+ LOG.fine("BluetoothCentralManager::onConnectedPeripheral: [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + "]");++ synchronized (BluetoothMeshProtocol.this) {+ if (meshNetwork != null) {+ meshNetwork.onConnectedPeripheral(peripheral);+ }+ }+ }++ @Override+ public void onConnectionFailed(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {+ LOG.fine("BluetoothCentralManager::onConnectionFailed: [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + ", Status=" + status +"]");++ synchronized (BluetoothMeshProtocol.this) {+ if (meshNetwork != null) {+ meshNetwork.onConnectionFailed(peripheral, status);+ }+ }+ }++ @Override+ public void onDisconnectedPeripheral(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {+ LOG.fine("BluetoothCentralManager::onDisconnectedPeripheral: [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + ", Status=" + status +"]");++ synchronized (BluetoothMeshProtocol.this) {+ if (meshNetwork != null) {+ meshNetwork.onDisconnectedPeripheral(peripheral, status);+ }+ }+ }++ @Override+ public void onDiscoveredPeripheral(BluetoothPeripheral peripheral, ScanResult scanResult) {+ LOG.fine("BluetoothCentralManager::onDiscoveredPeripheral: [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + ", ScanResult=" + scanResult +"]");++ synchronized (BluetoothMeshProtocol.this) {+ if (meshNetwork != null) {+ meshNetwork.onDiscoveredPeripheral(peripheral, scanResult);+ }+ }+ }++ @Override+ public void onScanFailed(int errorCode) {+ LOG.fine("BluetoothCentralManager::onScanFailed: [errorCode=" + errorCode + "]");++ synchronized (BluetoothMeshProtocol.this) {+ if (meshNetwork != null) {+ meshNetwork.onScanFailed(errorCode);+ }+ }+ }+ };+++ // Constructors -------------------------------------------------------------------------------++ public BluetoothMeshProtocol(BluetoothMeshAgent agent) {+ super(agent);+ }+++ // Implements Protocol --------------------------------------------------------------------------++ @Override+ public String getProtocolName() {+ return PROTOCOL_DISPLAY_NAME;+ }++ @Override+ public String getProtocolInstanceUri() {+ return "bluetoothmesh://" + ((meshNetwork != null && meshNetwork.getNetworkKey() != null) ?+ MeshParserUtils.bytesToHex(meshNetwork.getNetworkKey().getKey(), false) : "");++ }+++ // Implements AbstractProtocol ------------------------------------------------------------------++ @Override+ protected synchronized void doStart(Container container) throws Exception {+ LOG.info("Starting Bluetooth Mesh protocol.");+ String meshNetKeyParam = agent.getNetworkKey().orElseThrow(() -> {+ String msg = "No Bluetooth Mesh network key provided for protocol: " + this;+ LOG.warning(msg);+ return new IllegalArgumentException(msg);+ });+ String meshAppKeyParam = agent.getApplicationKey().orElseThrow(() -> {+ String msg = "No Bluetooth Mesh application key provided for protocol: " + this;+ LOG.warning(msg);+ return new IllegalArgumentException(msg);+ });+ String sourceAddressParam = agent.getSourceAddress().orElseThrow(() -> {+ String msg = "No Bluetooth Mesh unicast source address provided for protocol: " + this;+ LOG.warning(msg);+ return new IllegalArgumentException(msg);+ });+ final Integer sourceAddress = toIntegerAddress(sourceAddressParam, null);+ if (sourceAddress == null) {+ String msg = "Format of Bluetooth Mesh unicast source address '" + sourceAddressParam + "' is invalid for protocol: " + this;+ throw new IllegalArgumentException(msg);+ }+ int sequenceNumberParam = agent.getSequenceNumber().orElse(DEFAULT_SEQUENCE_NUMBER);+ final int mtuParam = agent.getMtu().orElse(DEFAULT_MTU);++ // TODO: add network key index configuration+ int netKeyIndex = 0;+ NetworkKey networkKey = new NetworkKey(netKeyIndex, MeshParserUtils.toByteArray(meshNetKeyParam));+ // TODO: add application key index configuration+ int appKeyIndex = 0;+ ApplicationKey applicationKey = new ApplicationKey(appKeyIndex, MeshParserUtils.toByteArray(meshAppKeyParam));+ Map<Integer, ApplicationKey> applicationKeyMap = new HashMap<>();+ applicationKeyMap.put(appKeyIndex, applicationKey);+ final ScheduledExecutorService finalExecutorService = executorService;+ Consumer<ConnectionStatus> statusConsumer = new Consumer<ConnectionStatus>() {+ @Override+ public void accept(ConnectionStatus connectionStatus) {+ setConnectionStatus(connectionStatus);+ if (connectionStatus == ConnectionStatus.CONNECTED) {+ finalExecutorService.execute(() -> updateAllAttributes());+ }+ }+ };+ sequenceNumberManager.load();+ Integer oldSequenceNumber = sequenceNumberManager.getSequenceNumber(networkKey, sourceAddress);+ if (oldSequenceNumber == null) {+ oldSequenceNumber = sequenceNumberParam;+ sequenceNumberManager.save(networkKey, sourceAddress, oldSequenceNumber);+ }+ final int sequenceNumber = oldSequenceNumber;+ Runnable runnable = () -> {+ synchronized (BluetoothMeshProtocol.this) {+ if (bluetoothCentral == null) {+ bluetoothCentral = new BluetoothCentralManager(bluetoothManagerCallback);+ }+ sequenceNumberManager.load();+ meshNetwork = new BluetoothMeshNetwork(+ bluetoothCentral, sequenceNumberManager, mainThread, sourceAddress, networkKey,+ applicationKeyMap, mtuParam, sequenceNumber, executorService, statusConsumer+ );+ meshNetwork.connect();+ }+ };+ if (mainThreadFuture == null) {+ mainThreadFuture = executorService.schedule(mainThread, 0, TimeUnit.MILLISECONDS);+ }+ mainThread.enqueue(runnable);+ }++ @Override+ protected synchronized void doStop(Container container) throws Exception {+ LOG.info("Stopping Bluetooth Mesh protocol.");+ if (meshNetwork != null) {+ meshNetwork.disconnect();+ meshNetwork = null;+ }+ }++ @Override+ protected synchronized void doLinkAttribute(String assetId, Attribute<?> attribute, BluetoothMeshAgentLink agentLink) throws RuntimeException {+ if (meshNetwork == null) {+ return;+ }+ final AttributeRef attributeRef = new AttributeRef(assetId, attribute.getName());+ Integer appKeyIndex = getOrThrowAgentLinkProperty(agentLink.getAppKeyIndex(), "Bluetooth Mesh Application Key Index");+ String modelName = getOrThrowAgentLinkProperty(agentLink.getModelName(), "Bluetooth Mesh Model Name");+ Integer modelId = toModelId(modelName, attributeRef);+ if (modelId == null) {+ return;+ }+ String addressAsString = getOrThrowAgentLinkProperty(agentLink.getAddress(), "Bluetooth Mesh Address");+ Integer address = toIntegerAddress(addressAsString, attributeRef);+ if (address == null) {+ return;+ }+ LOG.info(+ "Linking Bluetooth Mesh attribute: [address: '" + String.format("0x%04X", address) + "', model: '" ++ modelName + "', appKeyIndex: '" + appKeyIndex + "'] - " + attributeRef+ );+ Class<?> clazz = (attribute == null ? null : attribute.getType().getType());+ Consumer<Object> sensorValueConsumer = value -> updateLinkedAttribute(new AttributeState(attributeRef, toAttributeValue(value, clazz)));+ sensorValueConsumerMap.put(attributeRef, sensorValueConsumer);++ meshNetwork.addMeshModel(address, modelId, appKeyIndex);+ meshNetwork.addSensorValueConsumer(address, modelId, sensorValueConsumer);++ if (meshNetwork.isConnected()) {+ meshNetwork.sendMeshGetCommand(address, modelId);+ }+ }++ @Override+ protected synchronized void doUnlinkAttribute(String assetId, Attribute<?> attribute, BluetoothMeshAgentLink agentLink) {+ if (meshNetwork == null) {+ return;+ }+ final AttributeRef attributeRef = new AttributeRef(assetId, attribute.getName());+ Integer appKeyIndex = getOrThrowAgentLinkProperty(agentLink.getAppKeyIndex(), "Bluetooth Mesh Application Key Index");+ String modelName = getOrThrowAgentLinkProperty(agentLink.getModelName(), "Bluetooth Mesh Model Name");+ Integer modelId = toModelId(modelName, attributeRef);+ if (modelId == null) {+ return;+ }+ String addressAsString = getOrThrowAgentLinkProperty(agentLink.getAddress(), "Bluetooth Mesh Address");+ Integer address = toIntegerAddress(addressAsString, attributeRef);+ if (address == null) {+ return;+ }+ LOG.info(+ "Unlinking Bluetooth Mesh attribute: [address: '" + String.format("0x%04X", address) + "', model: '" ++ modelName + "', appKeyIndex: '" + appKeyIndex + "'] - " + attributeRef+ );+ Consumer<Object> sensorValueConsumer = sensorValueConsumerMap.remove(attributeRef);+ meshNetwork.removeSensorValueConsumer(address, modelId, sensorValueConsumer);+ }++ @Override+ protected synchronized void doLinkedAttributeWrite(Attribute<?> attribute, BluetoothMeshAgentLink agentLink, AttributeEvent event, Object processedValue) {+ if (meshNetwork == null) {+ return;+ }+ Integer appKeyIndex = getOrThrowAgentLinkProperty(agentLink.getAppKeyIndex(), "Bluetooth Mesh Application Key Index");+ String modelName = getOrThrowAgentLinkProperty(agentLink.getModelName(), "Bluetooth Mesh Model Name");+ Integer modelId = toModelId(modelName, null);+ if (modelId == null) {+ return;+ }+ String addressAsString = getOrThrowAgentLinkProperty(agentLink.getAddress(), "Bluetooth Mesh Address");+ Integer address = toIntegerAddress(addressAsString, null);+ if (address == null) {+ return;+ }+ LOG.info(+ "Writing Bluetooth Mesh attribute: [address: '" + String.format("0x%04X", address) + "', model: '" ++ modelName + "', appKeyIndex: '" + appKeyIndex + "', value: '" + processedValue + "']"+ );++ meshNetwork.sendMeshSetCommand(address, modelId, processedValue);+ meshNetwork.sendMeshGetCommand(address, modelId);+ }+++ // Implements ProtocolAssetDiscovery -----------------------------------------------------------++ @Override+ public Future<Void> startAssetDiscovery(final Consumer<AssetTreeNode[]> assetConsumer) {+ return executorService.submit(() -> {+ Asset<?> device = new ThingAsset("ESP32");++ Attribute<?> attribute = new Attribute<>("genericOnOff_0002", ValueType.BOOLEAN);+ attribute.addMeta(new MetaItem<>(MetaItemType.FORMAT, ValueFormat.BOOLEAN_ON_OFF()));++ int appKeyIndex = 0;+ String address = "0002";+ String modelName = "GenericOnOff";+ BluetoothMeshAgentLink agentLink = new BluetoothMeshAgentLink(agent.getId(), appKeyIndex, address, modelName);++ attribute.addOrReplaceMeta(+ new MetaItem<>(AGENT_LINK, agentLink),+ new MetaItem<>(MetaItemType.LABEL, "Generic On Off")+ );++ device.getAttributes().addOrReplace(attribute);++ AssetTreeNode treeNode = new AssetTreeNode(device);+ AssetTreeNode[] assetTreeNodes = new AssetTreeNode[1];+ assetTreeNodes[0] = treeNode;++ assetConsumer.accept(assetTreeNodes);+ }, null );+ }+++ // Private Instance Methods -------------------------------------------------------------------++ private synchronized void updateAllAttributes() {+ if (meshNetwork != null) {+ meshNetwork.sendMeshGetCommands();+ }+ }++ private Integer toIntegerAddress(String addressAsString, AttributeRef attributeRef) {+ if (addressAsString == null) {+ return null;+ }+ Integer address = Integer.decode("0x" + addressAsString);+ if (address == null) {+ if (attributeRef != null) {+ LOG.warning("Format of Bluetooth Mesh unicast address value '" + addressAsString + "' is invalid for protocol attribute: " + attributeRef);+ } else {+ LOG.warning("Format of Bluetooth Mesh unicast address value '" + addressAsString + "' is invalid.");+ }+ }+ return address;+ }++ private Integer toModelId(String modelName, AttributeRef attributeRef) {+ if (modelName == null) {+ return null;+ }+ Integer modelId = null;+ if (modelName.toUpperCase().contains("ONOFF")) {+ modelId = SigModelParser.GENERIC_ON_OFF_SERVER & 0xFFFF;+ }+ if (modelId == null) {+ if (attributeRef != null) {+ LOG.warning("Unknown or unsupported Bluetooth Mesh model name '" + modelName + "' for protocol attribute: " + attributeRef);+ } else {+ LOG.warning("Unknown or unsupported Bluetooth Mesh model name '" + modelName);+ }+ }+ return modelId;+ }++ private Object toAttributeValue(Object value, Class<?> clazz) {+ if (value == null || clazz == null) {+ return null;+ }+ Object retValue = null;+ if (clazz == String.class) {+ if (value instanceof Boolean) {+ retValue = ((Boolean)value) ? "On" : "Off";+ } else if (value instanceof Integer || value instanceof Double || value instanceof String) {+ retValue = value.toString();+ }+ } else if (clazz == Boolean.class) {+ if (value instanceof Boolean) {+ retValue = value;+ } else if (value instanceof String) {+ String strValue = ((String)value).trim().toUpperCase();+ if (strValue.equals("ON") || strValue.equals("TRUE") || strValue.equals("1")) {+ retValue = Boolean.valueOf(true);+ } else if (strValue.equals("OFF") || strValue.equals("FALSE") || strValue.equals("0")) {+ retValue = Boolean.valueOf(false);+ }+ } else if (value instanceof Integer) {+ retValue = ((Integer)value) == 0 ? Boolean.valueOf(false) : Boolean.valueOf(true);+ } else if (value instanceof Double) {+ retValue = ((Double)value) == 0 ? Boolean.valueOf(false) : Boolean.valueOf(true);+ }+ } else if (clazz == Integer.class) {+ if (value instanceof Boolean) {+ retValue = ((Boolean) value) ? Integer.valueOf(1) : Integer.valueOf(0);+ } else if (value instanceof String) {+ try {+ retValue = Double.valueOf((String)value).intValue();+ } catch (NumberFormatException exception) {}+ } else if (value instanceof Integer) {+ retValue = value;+ } else if (value instanceof Double) {+ retValue = ((Double) value).intValue();+ }+ }+ return retValue;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProxy.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProxy.javanew file mode 100644index 000000000..fe56aa5a2--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProxy.java@@ -0,0 +1,192 @@+/*+ * Copyright 2021, 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.bluetooth.mesh;++import com.welie.blessed.BluetoothCentralManager;+import com.welie.blessed.BluetoothCentralManagerCallback;+import com.welie.blessed.BluetoothCommandStatus;+import com.welie.blessed.BluetoothGattCharacteristic;+import com.welie.blessed.BluetoothGattDescriptor;+import com.welie.blessed.BluetoothGattService;+import com.welie.blessed.BluetoothPeripheral;+import com.welie.blessed.BluetoothPeripheralCallback;+import com.welie.blessed.ScanResult;+import org.openremote.model.asset.agent.ConnectionStatus;+import org.openremote.model.syslog.SyslogCategory;++import java.util.List;+import java.util.UUID;+import java.util.concurrent.ScheduledExecutorService;+import java.util.function.Consumer;+import java.util.logging.Logger;++public class BluetoothMeshProxy extends BluetoothCentralManagerCallback {++ public static final Logger LOG = SyslogCategory.getLogger(SyslogCategory.PROTOCOL, BluetoothMeshProxy.class.getName());++ /**+ * Mesh provisioning service UUID+ */+ public final static UUID MESH_PROXY_UUID = UUID.fromString("00001828-0000-1000-8000-00805F9B34FB");++ /**+ * Mesh provisioning data in characteristic UUID+ */+ public final static UUID MESH_PROXY_DATA_IN = UUID.fromString("00002ADD-0000-1000-8000-00805F9B34FB");++ /**+ * Mesh provisioning data out characteristic UUID+ */+ public final static UUID MESH_PROXY_DATA_OUT = UUID.fromString("00002ADE-0000-1000-8000-00805F9B34FB");+++ // Private Instance Fields --------------------------------------------------------------------++ private final BluetoothPeripheralCallbackImpl peripheralCallback;+ private final ScanResult scanResult;+ private int rssi;+ private final BluetoothMeshProxyStateMachine stateMachine;+++ // Constructors -------------------------------------------------------------------------------++ public BluetoothMeshProxy(MainThreadManager bluetoothCommandSerializer, ScheduledExecutorService executorService, BluetoothCentralManager central, BluetoothPeripheral peripheral, ScanResult scanResult) {+ this.scanResult = scanResult;+ this.rssi = scanResult.getRssi();+ this.peripheralCallback = new BluetoothPeripheralCallbackImpl();+ this.stateMachine = new BluetoothMeshProxyStateMachine(this, central, executorService, bluetoothCommandSerializer, peripheral, peripheralCallback);+ }+++ // Implements BluetoothCentralManagerCallback -------------------------------------------------++ @Override+ public synchronized void onConnectedPeripheral(BluetoothPeripheral peripheral) {+ stateMachine.onConnectedPeripheral(peripheral);+ }++ @Override+ public synchronized void onConnectionFailed(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {+ stateMachine.onConnectionFailed(peripheral, status);+ }++ @Override+ public synchronized void onDisconnectedPeripheral(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {+ stateMachine.onDisconnectedPeripheral(peripheral, status);+ }++ @Override+ public synchronized void onDiscoveredPeripheral(BluetoothPeripheral peripheral, ScanResult scanResult) {+ stateMachine.onDiscoveredPeripheral(peripheral, scanResult);+ }++ @Override+ public synchronized void onScanFailed(int errorCode) {+ }+++ // Public instance methods --------------------------------------------------------------------++ public synchronized void connect(Consumer<ConnectionStatus> statusConsumer, BluetoothMeshProxyConnectCallback callback) {+ stateMachine.connect(statusConsumer, callback);+ }++ public synchronized void disconnect() {+ stateMachine.disconnect();+ }++ public synchronized void sendData(int mtuSize, byte[] data, BluetoothMeshProxySendDataCallback callback) {+ stateMachine.sendData(mtuSize, data, callback);+ }++ public synchronized void setRxDataCallback(BluetoothMeshProxyRxCallback callback) {+ stateMachine.setRxDataCallback(callback);+ }++ public synchronized BluetoothPeripheral getPeripheral() {+ return stateMachine.getPeripheral();+ }++ public synchronized ScanResult getScanResult() {+ return scanResult;+ }++ public synchronized int getRssi() {+ return rssi;+ }++ public synchronized boolean isConnected() {+ return stateMachine.isConnected();+ }+++ // Nested Classes -----------------------------------------------------------------------------++ private class BluetoothPeripheralCallbackImpl extends BluetoothPeripheralCallback {++ public void onServicesDiscovered(final BluetoothPeripheral peripheral, List<BluetoothGattService> services) {+ LOG.info("BluetoothPeripheralCallback::onServicesDiscovered: [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + "]");+ stateMachine.onServicesDiscovered(peripheral, services);+ }++ public void onNotificationStateUpdate(BluetoothPeripheral peripheral, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {+ LOG.info("BluetoothPeripheralCallback::onNotificationStateUpdate: [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + ", Status=" + status + "]");+ stateMachine.onNotificationStateUpdate(peripheral, characteristic, status);+ }++ public void onCharacteristicUpdate(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {+ LOG.info("BluetoothPeripheralCallback::onCharacteristicUpdate: [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + ", Status=" + status + "]");+ stateMachine.onCharacteristicUpdate(peripheral, value, characteristic, status);+ }++ public void onCharacteristicWrite(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {+ LOG.info("BluetoothPeripheralCallback::onCharacteristicWrite: [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + ", Status=" + status + "]");+ stateMachine.onCharacteristicWrite(peripheral, value, characteristic, status);+ }++ public void onDescriptorRead(BluetoothPeripheral peripheral, byte[] value, BluetoothGattDescriptor descriptor, BluetoothCommandStatus status) {+ LOG.info("BluetoothPeripheralCallback::onDescriptorRead: [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + ", Status=" + status + "]");+ }++ public void onDescriptorWrite(BluetoothPeripheral peripheral, byte[] value, BluetoothGattDescriptor descriptor, BluetoothCommandStatus status) {+ LOG.info("BluetoothPeripheralCallback::onDescriptorWrite: [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + ", Status=" + status + "]");+ }++ public void onBondingStarted(BluetoothPeripheral peripheral) {+ LOG.info("BluetoothPeripheralCallback::onBondingStarted: [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + "]");+ }++ public void onBondingSucceeded(BluetoothPeripheral peripheral) {+ LOG.info("BluetoothPeripheralCallback::OnBondingSucceeded: [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + "]");+ }++ public void onBondingFailed(BluetoothPeripheral peripheral) {+ LOG.info("BluetoothPeripheralCallback::onBondingFailed: [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + "]");+ }++ public void onBondLost(BluetoothPeripheral peripheral) {+ LOG.info("BluetoothPeripheralCallback::onBondLost: [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + "]");+ }++ public void onReadRemoteRssi(BluetoothPeripheral peripheral, int rssi, BluetoothCommandStatus status) {+ LOG.info("BluetoothPeripheralCallback::onReadRemoteRssi: [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + ", RSSI=" + rssi + ", Status=" + status + "]");+ }+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProxyConnectCallback.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProxyConnectCallback.javanew file mode 100644index 000000000..c127db4ee--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProxyConnectCallback.java@@ -0,0 +1,26 @@+/*+ * Copyright 2021, 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.bluetooth.mesh;++import com.welie.blessed.BluetoothPeripheral;++public interface BluetoothMeshProxyConnectCallback {+ void onMeshProxyConnected(BluetoothPeripheral peripheral, boolean isSuccess);+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProxyRxCallback.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProxyRxCallback.javanew file mode 100644index 000000000..4f08cffc0--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProxyRxCallback.java@@ -0,0 +1,24 @@+/*+ * Copyright 2021, 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.bluetooth.mesh;++public interface BluetoothMeshProxyRxCallback {+ void onRxData(byte[] data);+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProxyScanner.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProxyScanner.javanew file mode 100644index 000000000..530a8f67f--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProxyScanner.java@@ -0,0 +1,268 @@+/*+ * Copyright 2021, 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.bluetooth.mesh;++import com.welie.blessed.BluetoothCentralManager;+import com.welie.blessed.BluetoothCentralManagerCallback;+import com.welie.blessed.BluetoothCommandStatus;+import com.welie.blessed.BluetoothPeripheral;+import com.welie.blessed.ScanResult;+import org.openremote.model.syslog.SyslogCategory;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.UUID;+import java.util.concurrent.ScheduledExecutorService;+import java.util.concurrent.ScheduledFuture;+import java.util.concurrent.TimeUnit;+import java.util.logging.Logger;++public class BluetoothMeshProxyScanner extends BluetoothCentralManagerCallback {++ public static final Logger LOG = SyslogCategory.getLogger(SyslogCategory.PROTOCOL, BluetoothMeshProxyScanner.class.getName());++ /**+ * Mesh provisioning service UUID+ */+ public final static UUID MESH_PROXY_UUID = UUID.fromString("00001828-0000-1000-8000-00805F9B34FB");++ private final static int ADVERTISED_NETWORK_ID_OFFSET = 1; //Offset of the network id contained in the advertisement service data+ private static final int ADVERTISEMENT_TYPE_NETWORK_ID = 0x00;+ private static final int ADVERTISEMENT_TYPE_NODE_IDENTITY = 0x01;+ private final static int ADVERTISED_NETWORK_ID_LENGTH = 8; //Length of the network id contained in the advertisement service data+ private final static int ADVERTISED_HASH_LENGTH = 8; // Length of the hash contained in the advertisement service data+ private final static int ADVERTISED_HASH_OFFSET = 1; // Offset of the hash contained in the advertisement service data++ private final MainThreadManager bluetoothCommandSerializer;+ private final BluetoothCentralManager bluetoothCentral;+ private final ScheduledExecutorService executorService;+ private volatile BluetoothMeshProxyScannerCallback callback;+ private volatile NetworkKey networkKey;+ private volatile boolean isStarted = false;++ private ScheduledFuture<?> timeoutFuture;++ private final Map<String, BluetoothMeshProxy> meshProxyMap = new HashMap<>();+++ // Constructors -------------------------------------------------------------------------------++ public BluetoothMeshProxyScanner(MainThreadManager bluetoothCommandSerializer, BluetoothCentralManager central, ScheduledExecutorService executorService) {+ this.bluetoothCommandSerializer = bluetoothCommandSerializer;+ this.bluetoothCentral = central;+ this.executorService = executorService;+ }++ public synchronized void start(final NetworkKey networkKey, int duration, final BluetoothMeshProxyScannerCallback callback) {+ LOG.info("Starting mesh proxy scanner");+ if (isStarted) {+ stop();+ }+ this.callback = callback;+ this.networkKey = networkKey;+ meshProxyMap.clear();+ isStarted = true;+ Runnable runnable = () -> {+ LOG.info("Scan ON");+ bluetoothCentral.scanForPeripheralsWithServices(new UUID[] {MESH_PROXY_UUID});+ };+ bluetoothCommandSerializer.enqueue(runnable);+ timeoutFuture = executorService.schedule(new Runnable() {+ @Override+ public void run() {+ synchronized (BluetoothMeshProxyScanner.this) {+ if (isStarted && callback != null) {+ final List<BluetoothMeshProxy> proxies = new ArrayList<>(meshProxyMap.values());+ executorService.schedule(new Runnable() {+ @Override+ public void run() {+ callback.onMeshProxiesScanned(proxies, null);+ }+ }, 0, TimeUnit.MILLISECONDS);+ }+ timeoutFuture = null;+ stop();+ }+ }+ }, duration, TimeUnit.MILLISECONDS);+ }+++ // Public Instance Methods -----------------------------------------------------------------------------++ public synchronized void stop() {+ LOG.info("Stopping mesh proxy scanner");+ if (isStarted) {+ // bluetoothCentral.stopScan();+ Runnable runnable = () -> {+ LOG.info("Scan OFF");+ bluetoothCentral.stopScan();+ };+ bluetoothCommandSerializer.enqueue(runnable);+ meshProxyMap.clear();+ isStarted = false;+ if (timeoutFuture != null) {+ timeoutFuture.cancel(false);+ timeoutFuture = null;+ }+ }+ }++ // Implements BluetoothCentralManagerCallback -------------------------------------------------++ @Override+ public synchronized void onConnectedPeripheral(final BluetoothPeripheral peripheral) {++ }++ @Override+ public synchronized void onConnectionFailed(final BluetoothPeripheral peripheral, final BluetoothCommandStatus status) {++ }++ @Override+ public synchronized void onDisconnectedPeripheral(final BluetoothPeripheral peripheral, final BluetoothCommandStatus status) {++ }++ @Override+ public synchronized void onDiscoveredPeripheral(final BluetoothPeripheral peripheral, final ScanResult scanResult) {+ if (!isStarted) {+ return;+ }+ LOG.info("Scanned Bluetooth mesh proxy: [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + ", connectionState=" + peripheral.getState() + "]");+ if (!meshProxyMap.containsKey(peripheral.getAddress())) {+ byte[] serviceData = scanResult.getServiceData().get(MESH_PROXY_UUID.toString());+ if (serviceData != null) {+ if (isAdvertisingWithNetworkIdentity(serviceData)) {+ LOG.info("Checking network identity of scanned Bluetooth mesh proxy: [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + "]");+ if (networkIdMatches(serviceData, networkKey)) {+ LOG.info("Network identity of scanned Bluetooth mesh proxy matches: [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + "]");+ meshProxyMap.put(peripheral.getAddress(), new BluetoothMeshProxy(bluetoothCommandSerializer, executorService, bluetoothCentral, peripheral, scanResult));+ } else {+ LOG.info("Network identity of scanned Bluetooth mesh proxy does NOT match: [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + "]");+ }+ } else if (isAdvertisedWithNodeIdentity(serviceData)) {+ LOG.info("Checking node identity of scanned Bluetooth mesh proxy: [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + "]");+ if (checkIfNodeIdentityMatches(serviceData)) {+ LOG.info("Node identity of scanned Bluetooth mesh proxy matches: [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + "]");+ meshProxyMap.put((peripheral.getAddress()), new BluetoothMeshProxy(bluetoothCommandSerializer, executorService, bluetoothCentral, peripheral, scanResult));+ } else {+ LOG.info("Node identity of scanned Bluetooth mesh proxy does NOT match: [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + "]");+ }+ } else {+ LOG.info("Could NOT find network or node identity in advertisement of Bluetooth mesh proxy: [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + "]");+ }+ } else {+ LOG.warning("Could NOT find service data in advertisement of Bluetooth mesh proxy [Name=" + peripheral.getName() + ", Address=" + peripheral.getAddress() + "] for mesh proxy service UUID:" + MESH_PROXY_UUID.toString());+ }+ }+ }++ @Override+ public synchronized void onScanFailed(final int errorCode) {+ if (isStarted) {+ stop();+ executorService.execute(() -> {+ if (callback != null) {+ callback.onMeshProxiesScanned(new ArrayList<>(), errorCode);+ }+ });+ }+ }++ // Private Instance Methods -------------------------------------------------------------------++ private boolean isAdvertisingWithNetworkIdentity(final byte[] serviceData) {+ return serviceData != null &&+ serviceData.length == 9 &&+ serviceData[ADVERTISED_NETWORK_ID_OFFSET - 1] == ADVERTISEMENT_TYPE_NETWORK_ID;+ }++ private boolean networkIdMatches(final byte[] serviceData, NetworkKey networkKey) {+ final byte[] advertisedNetworkId = getAdvertisedNetworkId(serviceData);+ if (advertisedNetworkId != null) {+ if (Arrays.equals(networkKey.getNetworkId(), advertisedNetworkId)) {+ return true;+ }+ }+ return false;+ }++ private byte[] getAdvertisedNetworkId(final byte[] serviceData) {+ if (serviceData == null)+ return null;+ final ByteBuffer advertisedNetworkID = ByteBuffer.allocate(ADVERTISED_NETWORK_ID_LENGTH).order(ByteOrder.BIG_ENDIAN);+ advertisedNetworkID.put(serviceData, ADVERTISED_NETWORK_ID_OFFSET, ADVERTISED_HASH_LENGTH);+ return advertisedNetworkID.array();+ }++ private boolean isAdvertisedWithNodeIdentity(final byte[] serviceData) {+ return serviceData != null &&+ serviceData.length == 17 &&+ serviceData[ADVERTISED_HASH_OFFSET - 1] == ADVERTISEMENT_TYPE_NODE_IDENTITY;+ }++ private boolean checkIfNodeIdentityMatches(final byte[] serviceData) {+ // TODO+ /*+ final MeshNetwork network = mMeshManagerApi.getMeshNetwork();+ if (network != null) {+ for (ProvisionedMeshNode node : network.getNodes()) {+ if (mMeshManagerApi.nodeIdentityMatches(node, serviceData)) {+ return true;+ }+ }+ }+ return false;+ */+ return false;+ }++ /*+ public boolean nodeIdentityMatches(@NonNull final ProvisionedMeshNode meshNode, @NonNull final byte[] serviceData) {+ final byte[] advertisedHash = getAdvertisedHash(serviceData);+ //If there is no advertised hash return false as this is used to match against the generated hash+ if (advertisedHash == null) {+ return false;+ }++ //If there is no advertised random return false as this is used to generate the hash to match against the advertised+ final byte[] random = getAdvertisedRandom(serviceData);+ if (random == null) {+ return false;+ }++ for (NetworkKey key : mMeshNetwork.netKeys) {+ if (Arrays.equals(advertisedHash, SecureUtils.+ calculateHash(key.getIdentityKey(), random, MeshAddress.addressIntToBytes(meshNode.getUnicastAddress()))) ||+ Arrays.equals(advertisedHash, SecureUtils.+ calculateHash(key.getOldIdentityKey(), random, MeshAddress.addressIntToBytes(meshNode.getUnicastAddress()))))+ return true;+ }+ return false;+ }+ */+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProxyScannerCallback.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProxyScannerCallback.javanew file mode 100644index 000000000..a76e72400--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProxyScannerCallback.java@@ -0,0 +1,28 @@+/*+ * Copyright 2021, 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.bluetooth.mesh;++import com.welie.blessed.BluetoothPeripheral;++import java.util.List;++public interface BluetoothMeshProxyScannerCallback {+ void onMeshProxiesScanned(List<BluetoothMeshProxy> meshProxies, Integer errorCode);+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProxySendDataCallback.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProxySendDataCallback.javanew file mode 100644index 000000000..f9c7bf940--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProxySendDataCallback.java@@ -0,0 +1,24 @@+/*+ * Copyright 2021, 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.bluetooth.mesh;++public interface BluetoothMeshProxySendDataCallback {+ void onDataSent(BluetoothMeshProxy proxy, byte[] data, boolean isSuccess);+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProxyStateMachine.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProxyStateMachine.javanew file mode 100644index 000000000..188973fcd--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProxyStateMachine.java@@ -0,0 +1,1308 @@+/*+ * Copyright 2021, 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.bluetooth.mesh;++import com.welie.blessed.BluetoothCentralManager;+import com.welie.blessed.BluetoothCommandStatus;+import com.welie.blessed.BluetoothGattCharacteristic;+import com.welie.blessed.BluetoothGattService;+import com.welie.blessed.BluetoothPeripheral;+import com.welie.blessed.BluetoothPeripheralCallback;+import com.welie.blessed.ScanResult;+import org.openremote.model.asset.agent.ConnectionStatus;+import org.openremote.model.syslog.SyslogCategory;++import java.util.List;+import java.util.UUID;+import java.util.concurrent.BlockingQueue;+import java.util.concurrent.LinkedBlockingQueue;+import java.util.concurrent.ScheduledExecutorService;+import java.util.concurrent.ScheduledFuture;+import java.util.concurrent.TimeUnit;+import java.util.function.Consumer;+import java.util.logging.Logger;++import static org.openremote.agent.protocol.bluetooth.mesh.BluetoothMeshProxy.*;++public class BluetoothMeshProxyStateMachine {++ public static final Logger LOG = SyslogCategory.getLogger(SyslogCategory.PROTOCOL, BluetoothMeshProxyStateMachine.class.getName());++ public static final int MAX_RETRY_COUNT = 7;+ public static final int CONNECT_TIMEOUT = 60000;+ public static final int SCAN_TIMEOUT = 60000;++ private final BluetoothMeshProxy meshProxy;+ private final BluetoothCentralManager bluetoothCentral;+ private volatile BluetoothPeripheral peripheral;+ private final BluetoothPeripheralCallback peripheralCallback;+ private final ScheduledExecutorService executorService;+ private volatile BluetoothMeshProxyRxCallback rxDataCallback;+ private volatile Consumer<ConnectionStatus> statusConsumer;+ private volatile BluetoothMeshProxyConnectCallback connectCallback;+ private volatile BluetoothGattCharacteristic dataInCharacteristic;+ private volatile BluetoothGattCharacteristic dataOutCharacteristic;+ private volatile int retryCount = 0;++ private final BlockingQueue<SendDataCommand> sendDataQueue = new LinkedBlockingQueue<>();+ private final QueueWorker queueWorker = new QueueWorker(sendDataQueue);+ private volatile ScheduledFuture<?> workerFuture;+ private volatile ScheduledFuture<?> timeoutFuture;+ private final MainThreadManager commandSerializer;++ private final StartState startState = new StartState(this);+ private final RetryToConnectState retryToConnectState = new RetryToConnectState(this);+ private final ConnectingState connectingState = new ConnectingState(this);+ private final ConnectedState connectedState = new ConnectedState(this);+ private final ServicesDiscoveredState servicesDiscoveredState = new ServicesDiscoveredState(this);+ private final ConfigureCharacteristicState configureCharacteristicState = new ConfigureCharacteristicState(this);+ private final EndState endState = new EndState(this);+ private final ScanState scanState = new ScanState(this);+ private final DisconnectedState disconnectedState = new DisconnectedState(this);+ private final FailedState failedState = new FailedState(this);+ private volatile State state = startState;++ public BluetoothMeshProxyStateMachine(BluetoothMeshProxy proxy, BluetoothCentralManager bluetoothCentral, ScheduledExecutorService executorService, MainThreadManager commandSerializer, BluetoothPeripheral peripheral, BluetoothPeripheralCallback callback) {+ this.meshProxy = proxy;+ this.bluetoothCentral = bluetoothCentral;+ this.commandSerializer = commandSerializer;+ this.executorService = executorService;+ this.peripheral = peripheral;+ this.peripheralCallback = callback;+ }++ void setState(State state) {+ this.state = state;+ }++ StartState getStartState() {+ return startState;+ }++ RetryToConnectState getRetryToConnectState() {+ return retryToConnectState;+ }++ ConnectingState getConnectingState() {+ return connectingState;+ }++ ConnectedState getConnectedState() {+ return connectedState;+ }++ ServicesDiscoveredState getServicesDiscoveredState() {+ return servicesDiscoveredState;+ }++ ConfigureCharacteristicState getConfigureCharacteristicState() {+ return configureCharacteristicState;+ }++ EndState getEndState() {+ return endState;+ }++ ScanState getScanState() {+ return scanState;+ }++ DisconnectedState getDisconnectedState() {+ return disconnectedState;+ }++ FailedState getFailedState() {+ return failedState;+ }++ public synchronized void setRxDataCallback(BluetoothMeshProxyRxCallback callback) {+ this.rxDataCallback = callback;+ }++ public synchronized void connect(Consumer<ConnectionStatus> statusConsumer, BluetoothMeshProxyConnectCallback callback) {+ state.connect(statusConsumer, callback);+ }++ public synchronized void disconnect() {+ state.disconnect();+ }++ public synchronized void sendData(int mtuSize, byte[] data, BluetoothMeshProxySendDataCallback callback) {+ state.sendData(mtuSize, data, callback);+ }++ public synchronized void onConnectedPeripheral(BluetoothPeripheral peripheral) {+ state.onConnectedPeripheral(peripheral);+ }++ public synchronized void onConnectionFailed(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {+ state.onConnectionFailed(peripheral, status);+ state.connect(statusConsumer, connectCallback);+ }++ public synchronized void onDisconnectedPeripheral(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {+ state.onDisconnectedPeripheral(peripheral, status);+ state.connect(statusConsumer, connectCallback);+ }++ public synchronized void onServicesDiscovered(BluetoothPeripheral peripheral, List<BluetoothGattService> services) {+ state.onServicesDiscovered(peripheral, services);+ state.configureOutCharacteristic();+ }++ public synchronized void onNotificationStateUpdate(BluetoothPeripheral peripheral, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {+ state.onNotificationStateUpdate(peripheral, characteristic, status);+ }++ public synchronized void onCharacteristicUpdate(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {+ if (!dataOutCharacteristic.getUuid().equals(characteristic.getUuid())) {+ return;+ }+ if (status == BluetoothCommandStatus.COMMAND_SUCCESS ) {+ LOG.info("Received '" + value.length + "' data bytes from mesh proxy: [data=" + dataAsHexString(value) + "]");+ final BluetoothMeshProxyRxCallback callback = rxDataCallback;+ if (callback != null) {+ executorService.execute(() -> callback.onRxData(value));+ }+ }+ }++ public synchronized void onCharacteristicWrite(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {+ if (queueWorker != null) {+ queueWorker.onCharacteristicWrite(peripheral, value, characteristic, status);+ }+ }++ public synchronized void onDiscoveredPeripheral(BluetoothPeripheral peripheral, ScanResult scanResult) {+ state.onDiscoveredPeripheral(peripheral, scanResult);+ state.connect(statusConsumer, connectCallback);+ }++ public synchronized boolean isConnected() {+ return state == getEndState();+ }++ synchronized void onTimeout() {+ LOG.info("Timeout fired !");+ state.onTimeout();+ }++ void setStatusConsumer(Consumer<ConnectionStatus> statusConsumer) {+ this.statusConsumer = statusConsumer;+ }++ Consumer<ConnectionStatus> getStatusConsumer() {+ return statusConsumer;+ }++ void setConnectCallback(BluetoothMeshProxyConnectCallback callback) {+ this.connectCallback = callback;+ }++ BluetoothMeshProxyConnectCallback getConnectCallback() {+ return connectCallback;+ }++ void setDataInCharacteristic(BluetoothGattCharacteristic characteristic) {+ this.dataInCharacteristic = characteristic;+ }++ BluetoothGattCharacteristic getDataInCharacteristic() {+ return dataInCharacteristic;+ }++ void setDataOutCharacteristic(BluetoothGattCharacteristic characteristic) {+ this.dataOutCharacteristic = characteristic;+ }++ BluetoothGattCharacteristic getDataOutCharacteristic() {+ return dataOutCharacteristic;+ }++ void startQueueWorker() {+ workerFuture = executorService.schedule(queueWorker, 0, TimeUnit.MILLISECONDS);+ }++ void stopQueueWorker() {+ if (workerFuture != null) {+ workerFuture.cancel(true);+ workerFuture = null;+ }+ sendDataQueue.clear();+ }++ int getRetryCount() {+ return retryCount;+ }++ void setRetryCount(int count) {+ this.retryCount = count;+ }++ int incrementRetryCount() {+ return ++retryCount;+ }++ BluetoothCentralManager getBluetoothCentral() {+ return bluetoothCentral;+ }++ public synchronized BluetoothPeripheral getPeripheral() {+ return peripheral;+ }++ void setPeripheral(BluetoothPeripheral peripheral) {+ this.peripheral = peripheral;+ }++ BluetoothPeripheralCallback getPeripheralCallback() {+ return peripheralCallback;+ }++ void notifyStatusConsumer(ConnectionStatus status) {+ executorService.execute(() -> statusConsumer.accept(status));+ }++ void executeOnMainThread(Runnable runnable) {+ commandSerializer.enqueue(runnable);+ }++ boolean isExpectedPeripheral(BluetoothPeripheral peripheral) {+ if (peripheral != null && this.peripheral != null) {+ return peripheral.getAddress().equalsIgnoreCase(this.peripheral.getAddress());+ } else {+ return false;+ }+ }++ void notifyListeners(boolean isSuccess, ConnectionStatus status) {+ executorService.execute(() -> connectCallback.onMeshProxyConnected(peripheral, isSuccess));+ executorService.execute(() -> statusConsumer.accept(status));+ }++ void disableOutCharacteristicNotifications() {+ final BluetoothGattCharacteristic out = getDataOutCharacteristic();+ if (out != null) {+ executeOnMainThread(() -> {+ LOG.info("Disabling out characteristic notifications: [Name=" + getPeripheral().getName() + ", Address=" + getPeripheral().getAddress() + "]");+ getPeripheral().setNotify(out, false);+ });+ }+ }++ void cancelConnection() {+ executeOnMainThread(() -> {+ LOG.info("Cancelling peripheral connection: [Name=" + getPeripheral().getName() + ", Address=" + getPeripheral().getAddress() + "]");+ getBluetoothCentral().cancelConnection(getPeripheral());+ });+ }++ void scanOn() {+ try {+ Thread.sleep(4000);+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ return;+ }+ executeOnMainThread(() -> {+ LOG.info("Scan ON");+ getBluetoothCentral().scanForPeripheralsWithServices(new UUID[] {MESH_PROXY_UUID});+ });+ }++ void scanOff() {+ executeOnMainThread(() -> {+ LOG.info("Scan OFF");+ getBluetoothCentral().stopScan();+ });+ }++ void startTimeout(int timeout) {+ timeoutFuture = executorService.schedule(() -> {+ onTimeout();+ },+ timeout, TimeUnit.MILLISECONDS+ );+ }++ void stopTimeout() {+ if (timeoutFuture != null) {+ if ((!timeoutFuture.isCancelled()) && (!timeoutFuture.isDone())) {+ timeoutFuture.cancel(true);+ }+ timeoutFuture = null;+ }+ }++ String dataAsHexString(byte[] data) {+ StringBuilder builder = new StringBuilder();+ for (int i = 0; i < data.length; i++) {+ builder.append(String.format("0x%02X%s", data[i] & 0xFF, i == (data.length - 1) ? "" : ", "));+ }+ return builder.toString();+ }+++ // Nested Classes -----------------------------------------------------------------------------++ private interface State {+ void connect(Consumer<ConnectionStatus> statusConsumer, BluetoothMeshProxyConnectCallback callback);+ void disconnect();+ void sendData(int mtuSize, byte[] data, BluetoothMeshProxySendDataCallback callback);+ void onConnectedPeripheral(BluetoothPeripheral peripheral);+ void onConnectionFailed(BluetoothPeripheral peripheral, BluetoothCommandStatus status);+ void onDisconnectedPeripheral(BluetoothPeripheral peripheral, BluetoothCommandStatus status);+ void onServicesDiscovered(BluetoothPeripheral peripheral, List<BluetoothGattService> services);+ void configureOutCharacteristic();+ void onNotificationStateUpdate(BluetoothPeripheral peripheral, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status);+ void onCharacteristicUpdate(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status);+ void onCharacteristicWrite(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status);+ void onDiscoveredPeripheral(BluetoothPeripheral peripheral, ScanResult scanResult);+ void onTimeout();+ }++ private class StartState implements State {++ private final BluetoothMeshProxyStateMachine stateMachine;++ public StartState(BluetoothMeshProxyStateMachine machine) {+ this.stateMachine = machine;+ }++ @Override+ public void connect(Consumer<ConnectionStatus> statusConsumer, BluetoothMeshProxyConnectCallback callback) {+ setStatusConsumer(statusConsumer);+ setConnectCallback(callback);++ startQueueWorker();+ setRetryCount(1);+ setDataInCharacteristic(null);+ setDataOutCharacteristic(null);++ startTimeout(CONNECT_TIMEOUT);+ setState(getConnectingState());++ notifyStatusConsumer(ConnectionStatus.CONNECTING);++ executeOnMainThread(() -> {+ try {+ Thread.sleep(4000);+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ return;+ }+ LOG.info("Initially connecting to mesh proxy: [Name=" + getPeripheral().getName() + ", Address=" + getPeripheral().getAddress() + "]");+ getBluetoothCentral().connectPeripheral(getPeripheral(), getPeripheralCallback());+ });+ }++ @Override+ public void disconnect() {++ }++ @Override+ public void sendData(int mtuSize, byte[] data, BluetoothMeshProxySendDataCallback callback) {++ }++ @Override+ public void onConnectedPeripheral(BluetoothPeripheral peripheral) {++ }++ @Override+ public void onConnectionFailed(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {++ }++ @Override+ public void onDisconnectedPeripheral(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {++ }++ @Override+ public void onServicesDiscovered(BluetoothPeripheral peripheral, List<BluetoothGattService> services) {++ }++ @Override+ public void configureOutCharacteristic() {++ }++ @Override+ public void onNotificationStateUpdate(BluetoothPeripheral peripheral, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onCharacteristicUpdate(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onCharacteristicWrite(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onDiscoveredPeripheral(BluetoothPeripheral peripheral, ScanResult scanResult) {++ }++ @Override+ public void onTimeout() {++ }+ }++ private class RetryToConnectState implements State {++ private final BluetoothMeshProxyStateMachine stateMachine;++ public RetryToConnectState(BluetoothMeshProxyStateMachine machine) {+ this.stateMachine = machine;+ }++ @Override+ public void connect(Consumer<ConnectionStatus> statusConsumer, BluetoothMeshProxyConnectCallback callback) {+ // initQueueWorker();+ incrementRetryCount();+ setDataInCharacteristic(null);+ setDataOutCharacteristic(null);++ stopTimeout();+ startTimeout(CONNECT_TIMEOUT);+ setState(getConnectingState());++ notifyStatusConsumer(ConnectionStatus.CONNECTING);++ executeOnMainThread(() -> {+ try {+ Thread.sleep(4000);+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ return;+ }+ LOG.info("Reconnecting to mesh proxy: [RetryCount=" + getRetryCount() + ", Name=" + getPeripheral().getName() + ", Address=" + getPeripheral().getAddress() + "]");+ getBluetoothCentral().connectPeripheral(getPeripheral(), getPeripheralCallback());+ });+ }++ @Override+ public void disconnect() {+ setState(getDisconnectedState());+ stopQueueWorker();+ }++ @Override+ public void sendData(int mtuSize, byte[] data, BluetoothMeshProxySendDataCallback callback) {++ }++ @Override+ public void onConnectedPeripheral(BluetoothPeripheral peripheral) {++ }++ @Override+ public void onConnectionFailed(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {++ }++ @Override+ public void onDisconnectedPeripheral(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {++ }++ @Override+ public void onServicesDiscovered(BluetoothPeripheral peripheral, List<BluetoothGattService> services) {++ }++ @Override+ public void configureOutCharacteristic() {++ }++ @Override+ public void onNotificationStateUpdate(BluetoothPeripheral peripheral, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onCharacteristicUpdate(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onCharacteristicWrite(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onDiscoveredPeripheral(BluetoothPeripheral peripheral, ScanResult scanResult) {++ }++ @Override+ public void onTimeout() {++ }+ }+++ private class ConnectingState implements State {++ private final BluetoothMeshProxyStateMachine stateMachine;++ public ConnectingState(BluetoothMeshProxyStateMachine machine) {+ this.stateMachine = machine;+ }++ @Override+ public void connect(Consumer<ConnectionStatus> statusConsumer, BluetoothMeshProxyConnectCallback callback) {++ }++ @Override+ public void disconnect() {+ stopTimeout();+ setState(getDisconnectedState());+ cancelConnection();+ notifyStatusConsumer(ConnectionStatus.DISCONNECTED);+ stopQueueWorker();+ }++ @Override+ public void sendData(int mtuSize, byte[] data, BluetoothMeshProxySendDataCallback callback) {++ }++ @Override+ public void onConnectedPeripheral(BluetoothPeripheral peripheral) {+ if (isExpectedPeripheral(peripheral)) {+ stopTimeout();+ setState(getConnectedState());+ }+ }++ @Override+ public void onConnectionFailed(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {+ if (isExpectedPeripheral(peripheral)) {+ if (getRetryCount() < MAX_RETRY_COUNT) {+ stopTimeout();+ startTimeout(SCAN_TIMEOUT);+ setState(getScanState());+ scanOn();+ } else {+ notifyListeners(false, ConnectionStatus.ERROR);+ stopTimeout();+ setState(getFailedState());+ stopQueueWorker();+ }+ }+ }++ @Override+ public void onDisconnectedPeripheral(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {++ }++ @Override+ public void onServicesDiscovered(BluetoothPeripheral peripheral, List<BluetoothGattService> services) {++ }++ @Override+ public void configureOutCharacteristic() {++ }++ @Override+ public void onNotificationStateUpdate(BluetoothPeripheral peripheral, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onCharacteristicUpdate(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onCharacteristicWrite(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onDiscoveredPeripheral(BluetoothPeripheral peripheral, ScanResult scanResult) {++ }++ @Override+ public void onTimeout() {+ LOG.warning("ConnectingState::onTimeout");+ notifyListeners(false, ConnectionStatus.ERROR);+ setState(getFailedState());+ stopQueueWorker();+ // cancelConnection();+ // startTimeout(SCAN_TIMEOUT);+ // setState(getScanState());+ // scanOn();+ }+ }++ private class ConnectedState implements State {++ private final BluetoothMeshProxyStateMachine stateMachine;++ public ConnectedState(BluetoothMeshProxyStateMachine machine) {+ this.stateMachine = machine;+ }++ @Override+ public void connect(Consumer<ConnectionStatus> statusConsumer, BluetoothMeshProxyConnectCallback callback) {++ }++ @Override+ public void disconnect() {+ setState(getDisconnectedState());+ cancelConnection();+ notifyStatusConsumer(ConnectionStatus.DISCONNECTED);+ stopQueueWorker();+ }++ @Override+ public void sendData(int mtuSize, byte[] data, BluetoothMeshProxySendDataCallback callback) {++ }++ @Override+ public void onConnectedPeripheral(BluetoothPeripheral peripheral) {++ }++ @Override+ public void onConnectionFailed(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {++ }++ @Override+ public void onDisconnectedPeripheral(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {+ if (isExpectedPeripheral(peripheral)) {+ stopTimeout();+ startTimeout(SCAN_TIMEOUT);+ setState(getScanState());+ scanOn();+ }+ }++ @Override+ public void onServicesDiscovered(BluetoothPeripheral peripheral, List<BluetoothGattService> services) {+ if (isExpectedPeripheral(peripheral)) {+ final BluetoothGattCharacteristic in = peripheral.getCharacteristic(MESH_PROXY_UUID, MESH_PROXY_DATA_IN);+ final BluetoothGattCharacteristic out = peripheral.getCharacteristic(MESH_PROXY_UUID, MESH_PROXY_DATA_OUT);+ if (in != null && out != null) {+ setDataInCharacteristic(in);+ setDataOutCharacteristic(out);+ setState(getServicesDiscoveredState());+ } else {+ notifyListeners(false, ConnectionStatus.ERROR);+ setState(getFailedState());+ stopQueueWorker();+ }+ }+ }++ @Override+ public void configureOutCharacteristic() {++ }++ @Override+ public void onNotificationStateUpdate(BluetoothPeripheral peripheral, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onCharacteristicUpdate(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onCharacteristicWrite(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onDiscoveredPeripheral(BluetoothPeripheral peripheral, ScanResult scanResult) {++ }++ @Override+ public void onTimeout() {++ }+ }++ private class ServicesDiscoveredState implements State {++ private final BluetoothMeshProxyStateMachine stateMachine;++ public ServicesDiscoveredState(BluetoothMeshProxyStateMachine machine) {+ this.stateMachine = machine;+ }++ @Override+ public void connect(Consumer<ConnectionStatus> statusConsumer, BluetoothMeshProxyConnectCallback callback) {++ }++ @Override+ public void disconnect() {+ setState(getDisconnectedState());+ cancelConnection();+ notifyStatusConsumer(ConnectionStatus.DISCONNECTED);+ stopQueueWorker();+ }++ @Override+ public void sendData(int mtuSize, byte[] data, BluetoothMeshProxySendDataCallback callback) {++ }++ @Override+ public void onConnectedPeripheral(BluetoothPeripheral peripheral) {++ }++ @Override+ public void onConnectionFailed(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {++ }++ @Override+ public void onDisconnectedPeripheral(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {+ if (isExpectedPeripheral(peripheral)) {+ stopTimeout();+ startTimeout(SCAN_TIMEOUT);+ setState(getScanState());+ scanOn();+ }+ }++ @Override+ public void onServicesDiscovered(BluetoothPeripheral peripheral, List<BluetoothGattService> services) {++ }++ @Override+ public void configureOutCharacteristic() {+ final BluetoothGattCharacteristic out = getDataOutCharacteristic();+ executeOnMainThread(() -> {+ LOG.info("Enabling out characteristic notifications: [Name=" + getPeripheral().getName() + ", Address=" + getPeripheral().getAddress() + "]");+ getPeripheral().setNotify(out, true);+ });+ setState(getConfigureCharacteristicState());+ }++ @Override+ public void onNotificationStateUpdate(BluetoothPeripheral peripheral, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {+ LOG.info("ConfigureCharacteristicState::onNotificationStateUpdate: status=" + status);+ }++ @Override+ public void onCharacteristicUpdate(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onCharacteristicWrite(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onDiscoveredPeripheral(BluetoothPeripheral peripheral, ScanResult scanResult) {++ }++ @Override+ public void onTimeout() {++ }+ }++ private class ConfigureCharacteristicState implements State {++ private final BluetoothMeshProxyStateMachine stateMachine;++ public ConfigureCharacteristicState(BluetoothMeshProxyStateMachine machine) {+ this.stateMachine = machine;+ }++ @Override+ public void connect(Consumer<ConnectionStatus> statusConsumer, BluetoothMeshProxyConnectCallback callback) {++ }++ @Override+ public void disconnect() {+ setState(getDisconnectedState());+ disableOutCharacteristicNotifications();+ cancelConnection();+ notifyStatusConsumer(ConnectionStatus.DISCONNECTED);+ stopQueueWorker();+ }++ @Override+ public void sendData(int mtuSize, byte[] data, BluetoothMeshProxySendDataCallback callback) {++ }++ @Override+ public void onConnectedPeripheral(BluetoothPeripheral peripheral) {++ }++ @Override+ public void onConnectionFailed(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {++ }++ @Override+ public void onDisconnectedPeripheral(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {+ if (isExpectedPeripheral(peripheral)) {+ stopTimeout();+ startTimeout(SCAN_TIMEOUT);+ setState(getScanState());+ scanOn();+ }+ }++ @Override+ public void onServicesDiscovered(BluetoothPeripheral peripheral, List<BluetoothGattService> services) {++ }++ @Override+ public void configureOutCharacteristic() {++ }++ @Override+ public void onNotificationStateUpdate(BluetoothPeripheral peripheral, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {+ if (isExpectedPeripheral(peripheral) && getDataOutCharacteristic().getUuid().equals(characteristic.getUuid())) {+ if (status == BluetoothCommandStatus.COMMAND_SUCCESS) {+ setRetryCount(0);+ notifyListeners(true, ConnectionStatus.CONNECTED);+ setState(getEndState());+ } else {+ notifyListeners(false, ConnectionStatus.ERROR);+ setState(getFailedState());+ stopQueueWorker();+ }+ }+ }++ @Override+ public void onCharacteristicUpdate(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onCharacteristicWrite(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onDiscoveredPeripheral(BluetoothPeripheral peripheral, ScanResult scanResult) {++ }++ @Override+ public void onTimeout() {++ }+ }++ private class EndState implements State {++ private final BluetoothMeshProxyStateMachine stateMachine;++ public EndState(BluetoothMeshProxyStateMachine machine) {+ this.stateMachine = machine;+ }++ @Override+ public void connect(Consumer<ConnectionStatus> statusConsumer, BluetoothMeshProxyConnectCallback callback) {++ }++ @Override+ public void disconnect() {+ setState(getDisconnectedState());+ disableOutCharacteristicNotifications();+ cancelConnection();+ notifyStatusConsumer(ConnectionStatus.DISCONNECTED);+ stopQueueWorker();+ }++ @Override+ public void sendData(int mtuSize, byte[] data, BluetoothMeshProxySendDataCallback callback) {+ SendDataCommand cmd = null;+ if (data.length > mtuSize) {+ cmd = new SendMultiDataSegmentCommand(meshProxy, commandSerializer, mtuSize, executorService, dataInCharacteristic, data, callback);+ } else {+ cmd = new SendSingleDataSegmentCommand(meshProxy, commandSerializer, executorService, dataInCharacteristic, data, callback);+ }+ try {+ sendDataQueue.put(cmd);+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ }+ }++ @Override+ public void onConnectedPeripheral(BluetoothPeripheral peripheral) {++ }++ @Override+ public void onConnectionFailed(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {++ }++ @Override+ public void onDisconnectedPeripheral(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {+ if (isExpectedPeripheral(peripheral)) {+ stopTimeout();+ startTimeout(SCAN_TIMEOUT);+ setState(getScanState());+ scanOn();+ }+ }++ @Override+ public void onServicesDiscovered(BluetoothPeripheral peripheral, List<BluetoothGattService> services) {++ }++ @Override+ public void configureOutCharacteristic() {++ }++ @Override+ public void onNotificationStateUpdate(BluetoothPeripheral peripheral, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onCharacteristicUpdate(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onCharacteristicWrite(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onDiscoveredPeripheral(BluetoothPeripheral peripheral, ScanResult scanResult) {++ }++ @Override+ public void onTimeout() {++ }+ }++ private class ScanState implements State {++ private final BluetoothMeshProxyStateMachine stateMachine;++ public ScanState(BluetoothMeshProxyStateMachine machine) {+ this.stateMachine = machine;+ }++ @Override+ public void connect(Consumer<ConnectionStatus> statusConsumer, BluetoothMeshProxyConnectCallback callback) {++ }++ @Override+ public void disconnect() {+ stopTimeout();+ setState(getDisconnectedState());+ notifyStatusConsumer(ConnectionStatus.DISCONNECTED);+ stopQueueWorker();+ }++ @Override+ public void sendData(int mtuSize, byte[] data, BluetoothMeshProxySendDataCallback callback) {+ }++ @Override+ public void onConnectedPeripheral(BluetoothPeripheral peripheral) {++ }++ @Override+ public void onConnectionFailed(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {++ }++ @Override+ public void onDisconnectedPeripheral(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {+ }++ @Override+ public void onServicesDiscovered(BluetoothPeripheral peripheral, List<BluetoothGattService> services) {++ }++ @Override+ public void configureOutCharacteristic() {++ }++ @Override+ public void onNotificationStateUpdate(BluetoothPeripheral peripheral, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onCharacteristicUpdate(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {+ }++ @Override+ public void onCharacteristicWrite(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onDiscoveredPeripheral(BluetoothPeripheral peripheral, ScanResult scanResult) {+ BluetoothPeripheral oldPeripheral = getPeripheral();+ BluetoothPeripheral newPeripheral = peripheral;+ if (oldPeripheral.getAddress().equals(newPeripheral.getAddress())) {+ LOG.info("Scanned Bluetooth Mesh proxy after connection loss: [Name='" + peripheral.getName() + "', address='" + peripheral.getAddress() + "']");+ setPeripheral(newPeripheral);+ stopTimeout();+ scanOff();+ setState(getRetryToConnectState());+ }+ }++ @Override+ public void onTimeout() {+ LOG.warning("ScanState::onTimeout");+ scanOff();+ notifyListeners(false, ConnectionStatus.ERROR);+ setState(getFailedState());+ stopQueueWorker();+ }+ }++ private class FailedState implements State {++ private final BluetoothMeshProxyStateMachine stateMachine;++ public FailedState(BluetoothMeshProxyStateMachine machine) {+ this.stateMachine = machine;+ }++ @Override+ public void connect(Consumer<ConnectionStatus> statusConsumer, BluetoothMeshProxyConnectCallback callback) {++ }++ @Override+ public void disconnect() {++ }++ @Override+ public void sendData(int mtuSize, byte[] data, BluetoothMeshProxySendDataCallback callback) {++ }++ @Override+ public void onConnectedPeripheral(BluetoothPeripheral peripheral) {++ }++ @Override+ public void onConnectionFailed(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {++ }++ @Override+ public void onDisconnectedPeripheral(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {++ }++ @Override+ public void onServicesDiscovered(BluetoothPeripheral peripheral, List<BluetoothGattService> services) {++ }++ @Override+ public void configureOutCharacteristic() {++ }++ @Override+ public void onNotificationStateUpdate(BluetoothPeripheral peripheral, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onCharacteristicUpdate(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onCharacteristicWrite(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onDiscoveredPeripheral(BluetoothPeripheral peripheral, ScanResult scanResult) {++ }++ @Override+ public void onTimeout() {++ }+ }++ private class DisconnectedState implements State {++ private final BluetoothMeshProxyStateMachine stateMachine;++ public DisconnectedState(BluetoothMeshProxyStateMachine machine) {+ this.stateMachine = machine;+ }++ @Override+ public void connect(Consumer<ConnectionStatus> statusConsumer, BluetoothMeshProxyConnectCallback callback) {++ }++ @Override+ public void disconnect() {++ }++ @Override+ public void sendData(int mtuSize, byte[] data, BluetoothMeshProxySendDataCallback callback) {++ }++ @Override+ public void onConnectedPeripheral(BluetoothPeripheral peripheral) {++ }++ @Override+ public void onConnectionFailed(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {++ }++ @Override+ public void onDisconnectedPeripheral(BluetoothPeripheral peripheral, BluetoothCommandStatus status) {++ }++ @Override+ public void onServicesDiscovered(BluetoothPeripheral peripheral, List<BluetoothGattService> services) {++ }++ @Override+ public void configureOutCharacteristic() {++ }++ @Override+ public void onNotificationStateUpdate(BluetoothPeripheral peripheral, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onCharacteristicUpdate(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onCharacteristicWrite(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {++ }++ @Override+ public void onDiscoveredPeripheral(BluetoothPeripheral peripheral, ScanResult scanResult) {++ }++ @Override+ public void onTimeout() {++ }+ }++ private class QueueWorker extends BluetoothPeripheralCallback implements Runnable {++ private final BlockingQueue<SendDataCommand> queue;+ private SendDataCommand pendingCommand = null;++ public QueueWorker(BlockingQueue<SendDataCommand> queue) {+ this.queue = queue;+ }++ @Override+ public void run() {+ while (!Thread.currentThread().isInterrupted()) {+ try {+ SendDataCommand command = queue.take();+ synchronized (QueueWorker.this) {+ pendingCommand = command;+ }+ // Note: send data is blocking+ command.sendData();+ } catch (InterruptedException e) {+ return;+ }+ }+ }++ // Implements BluetoothPeripheralCallback -------------------------------------------------++ @Override+ public synchronized void onCharacteristicWrite(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {+ if (pendingCommand != null) {+ pendingCommand.onCharacteristicWrite(peripheral, value, characteristic, status);+ }+ }+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/ExportConfig.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/ExportConfig.javanew file mode 100644index 000000000..ba1421bf4--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/ExportConfig.java@@ -0,0 +1,38 @@+package org.openremote.agent.protocol.bluetooth.mesh;++/**+ * Base class for network export configuration+ */+class ExportConfig {++ protected final Builder config;++ /**+ * Export configuration builder+ */+ protected interface Builder {++ /**+ * Builds the export configuration.+ *+ * @return {@link ExportConfig}+ */+ ExportConfig build();+ }++ /**+ * Constructs the builder configuration+ *+ * @param config configuration {@link Builder}+ */+ ExportConfig(final Builder config) {+ this.config = config;+ }++ /**+ * Returns the configuration+ */+ protected final Builder getConfig() {+ return config;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/Features.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/Features.javanew file mode 100644index 000000000..6b7c41d0b--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/Features.java@@ -0,0 +1,194 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import org.openremote.agent.protocol.bluetooth.mesh.transport.ProvisionedMeshNode;++import java.lang.annotation.Retention;+import java.lang.annotation.RetentionPolicy;++/**+ * Defines the features supported by a {@link ProvisionedMeshNode}+ */+public class Features {++ // @IntDef({DISABLED, ENABLED, UNSUPPORTED})+ // @interface FeatureState {+ // }++ // Key refresh phases+ public static final int DISABLED = 0; //Feature is disabled+ public static final int ENABLED = 1; //Feature is enabled+ public static final int UNSUPPORTED = 2; //Feature is not supported++ private int friend; //friend feature+ private int lowPower; //low power feature+ private int proxy; //proxy feature+ private int relay; //relay feature++ //+ // Constructs the features of a provisioned node+ //+ // @param friend Specifies if the friend feature is supported based on {@link FeatureState}+ // @param lowPower Specifies if the low power feature is supported based on {@link FeatureState}+ // @param proxy Specifies if the proxy feature is supported based on {@link FeatureState}+ // @param relay Specifies if the relay feature is supported based on {@link FeatureState}+ //+ public Features(/*@FeatureState*/ final int friend, /*@FeatureState*/ final int lowPower, /*@FeatureState*/ final int proxy, /*@FeatureState*/ final int relay) {+ this.friend = friend;+ this.lowPower = lowPower;+ this.proxy = proxy;+ this.relay = relay;+ }++ @Override+ public String toString() {+ return "Features{" ++ "friend=" + friend ++ ", lowPower=" + lowPower ++ ", proxy=" + proxy ++ ", relay=" + relay ++ '}';+ }++ /**+ * Returns the friend feature state+ */+ // @FeatureState+ public int getFriend() {+ return friend;+ }++ //+ // Sets the friend feature of the node+ //+ // @param friend {@link FeatureState}+ //+ public void setFriend(/*@FeatureState*/ final int friend) {+ this.friend = friend;+ }++ /**+ * Returns the low power feature state+ */+ // @FeatureState+ public int getLowPower() {+ return lowPower;+ }++ //+ // Sets the low power feature of the node+ //+ // @param lowPower {@link FeatureState}+ //+ public void setLowPower(/*@FeatureState*/ final int lowPower) {+ this.lowPower = lowPower;+ }++ /**+ * Returns the proxy feature state+ */+ // @FeatureState+ public int getProxy() {+ return proxy;+ }++ //+ // Sets the proxy feature of the node+ //+ // @param proxy {@link FeatureState}+ //+ public void setProxy(/* @FeatureState */ final int proxy) {+ this.proxy = proxy;+ }++ /**+ * Returns the relay feature state+ */+ // @FeatureState+ public int getRelay() {+ return relay;+ }++ //+ // Sets the relay feature of the node+ //+ // @param relay {@link FeatureState}+ //+ public void setRelay(/*@FeatureState*/ final int relay) {+ this.relay = relay;+ }++ /**+ * Returns true if friend feature is supported and false otherwise+ */+ public boolean isFriendFeatureSupported() {+ switch (friend) {+ case UNSUPPORTED:+ return false;+ case ENABLED:+ case DISABLED:+ default:+ return true;+ }+ }++ /**+ * Returns true if relay feature is supported and false otherwise+ */+ public boolean isRelayFeatureSupported() {+ switch (relay) {+ case UNSUPPORTED:+ return false;+ case ENABLED:+ case DISABLED:+ default:+ return true;+ }+ }++ /**+ * Returns true if proxy feature is supported and false otherwise+ */+ public boolean isProxyFeatureSupported() {+ switch (proxy) {+ case UNSUPPORTED:+ return false;+ case ENABLED:+ case DISABLED:+ default:+ return true;+ }+ }++ /**+ * Returns true if low power feature is supported and false otherwise+ */+ public boolean isLowPowerFeatureSupported() {+ switch (lowPower) {+ case UNSUPPORTED:+ return false;+ case ENABLED:+ case DISABLED:+ default:+ return true;+ }+ }++ public int assembleFeatures() {+ int features = bitValue(lowPower) << 3;+ features = features | bitValue(friend) << 2;+ features = features | bitValue(proxy) << 1;+ features = features | bitValue(relay);+ return features;+ }++ private short bitValue(final int feature) {+ switch (feature) {+ default:+ case UNSUPPORTED:+ case DISABLED:+ return 0;+ case ENABLED:+ return 1;+ }+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/Group.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/Group.javanew file mode 100644index 000000000..52b7b9840--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/Group.java@@ -0,0 +1,249 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;++import java.util.UUID;++public class Group {++ public int id = 0;++ private String name = "Mesh Group";++ private int address;++ private UUID addressLabel;++ private int parentAddress;++ private UUID parentAddressLabel;++ private String meshUuid;++ /**+ * Constructs a mesh group to be used for room db implementation+ *+ * @param id Autogenerated primary key id+ * @param address Address of the group+ * @param addressLabel Label UUID of the group address in the case of a virtual address+ * @param parentAddress Parent address of the group+ * @param parentAddressLabel Label UUID of the parent address in the case of a virtual address+ * @param meshUuid UUID of the mesh network+ */+ public Group(final int id, final int address,+ final UUID addressLabel,+ final int parentAddress,+ final UUID parentAddressLabel,+ final String meshUuid) throws IllegalArgumentException {+ this(address, addressLabel, parentAddress, parentAddressLabel, meshUuid);+ this.id = id;+ }++ /**+ * Constructs a mesh group+ *+ * @param address Address of the group+ * @param meshUuid UUID of the mesh network+ */+ public Group(final int address, final String meshUuid) throws IllegalArgumentException {+ this(address, null, MeshAddress.UNASSIGNED_ADDRESS, null, meshUuid);+ }++ /**+ * Constructs a mesh group+ *+ * @param address Address of the group+ * @param parentAddress Parent address of the group. If there is no parent group use {@link MeshAddress#UNASSIGNED_ADDRESS}+ * @param meshUuid UUID of the mesh network+ */+ public Group(final int address, final int parentAddress, final String meshUuid) throws IllegalArgumentException {+ this(address, null, parentAddress, null, meshUuid);+ }++ /**+ * Constructs a mesh group+ *+ * @param address Address of the group+ * @param parentAddressLabel Label UUID of the parent address in the case of a virtual address+ * @param meshUuid UUID of the mesh network+ */+ public Group(final int address, final UUID parentAddressLabel, final String meshUuid) throws IllegalArgumentException {+ this(address, null, MeshAddress.UNASSIGNED_ADDRESS, parentAddressLabel, meshUuid);+ }++ /**+ * Constructs a mesh group+ *+ * @param addressLabel Label UUID of the address in the case of a virtual address+ * @param parentAddress Parent address of the group. If there is no parent group use {@link MeshAddress#UNASSIGNED_ADDRESS}+ * @param meshUuid UUID of the mesh network+ */+ public Group(final UUID addressLabel, final int parentAddress, final String meshUuid) throws IllegalArgumentException {+ this(MeshAddress.UNASSIGNED_ADDRESS, addressLabel, parentAddress, null, meshUuid);+ }++ /**+ * Constructs a mesh group+ *+ * @param addressLabel Label UUID of the group address in the case of a virtual address+ * @param parentAddressLabel Label UUID of the parent address in the case of a virtual address+ * @param meshUuid UUID of the mesh network+ */+ public Group(final UUID addressLabel, final UUID parentAddressLabel, final String meshUuid) throws IllegalArgumentException {+ this(MeshAddress.UNASSIGNED_ADDRESS, addressLabel, MeshAddress.UNASSIGNED_ADDRESS, parentAddressLabel, meshUuid);+ }++ /**+ * Constructs a mesh group+ *+ * @param address Address of the group+ * @param addressLabel Label UUID of the group address in the case of a virtual address+ * @param parentAddress Parent address of the group. If there is no parent group use {@link MeshAddress#UNASSIGNED_ADDRESS}+ * @param parentAddressLabel Label UUID of the parent address in the case of a virtual address+ * @param meshUuid UUID of the mesh network+ * @throws IllegalArgumentException for invalid arguments+ */+ private Group(final int address,+ final UUID addressLabel,+ final int parentAddress,+ final UUID parentAddressLabel,+ final String meshUuid) throws IllegalArgumentException {+ if (!MeshAddress.isValidUnassignedAddress(address) && MeshAddress.isValidUnassignedAddress(parentAddress)) {+ if (address == parentAddress) {+ throw new IllegalArgumentException("The value of the parentAddress property shall not be equal to the value of the address property");+ }+ }++ if (addressLabel == null) {+ if (MeshAddress.isValidVirtualAddress(address)) {+ throw new IllegalArgumentException("Please provide a Label UUID when creating groups using virtual addresses");+ } else if (!MeshAddress.isValidGroupAddress(address)) {+ throw new IllegalArgumentException("Address of the group must be a valid group address or a virtual address");+ }+ this.address = address;+ generateParentAddressLabel(parentAddressLabel, parentAddress);+ } else {+ this.addressLabel = addressLabel;+ this.address = MeshAddress.generateVirtualAddress(addressLabel);+ generateParentAddressLabel(parentAddressLabel, parentAddress);+ }+ this.meshUuid = meshUuid;+ }++ private void generateParentAddressLabel(final UUID parentAddressLabel, final int parentAddress) throws IllegalArgumentException {+ this.parentAddressLabel = parentAddressLabel;+ if (parentAddressLabel == null) {+ if (MeshAddress.isValidVirtualAddress(parentAddress)) {+ throw new IllegalArgumentException("Please provide a Label UUID for the parent address of this group");+ } else if (!MeshAddress.isValidGroupAddress(parentAddress) && !MeshAddress.isValidUnassignedAddress(parentAddress)) {+ throw new IllegalArgumentException("parentAddress value must be a group address, " ++ "virtual address or an unassigned address");+ }+ this.parentAddress = parentAddress;+ } else {+ this.parentAddress = MeshAddress.generateVirtualAddress(parentAddressLabel);+ }+ }++ /**+ * Returns the provisionerUuid of the network+ *+ * @return provisionerUuid+ */+ public String getMeshUuid() {+ return meshUuid;+ }++ /**+ * Sets the provisionerUuid of the network+ *+ * @param meshUuid network provisionerUuid+ */+ public void setMeshUuid(final String meshUuid) {+ this.meshUuid = meshUuid;+ }++ /**+ * Returns the address of the group+ *+ * @return 2 byte group address+ */+ public int getAddress() {+ return address;+ }++ /**+ * Returns the label UUID of the address of the group+ *+ * @return Label UUID of the group address if the group address is a virtual address or null otherwise+ */+ public UUID getAddressLabel() {+ return addressLabel;+ }++ /**+ * Sets the group address label+ *+ * @param uuidLabel UUID label of the address+ */+ public void setAddressLabel(final UUID uuidLabel) {+ addressLabel = uuidLabel;+ if (uuidLabel != null) {+ address = MeshAddress.generateVirtualAddress(uuidLabel);+ }+ }++ public UUID getParentAddressLabel() {+ return parentAddressLabel;+ }++ /**+ * Sets the label UUID of the parent address+ *+ * @param parentAddressLabel Label UUID of the parent address+ */+ public void setParentAddressLabel(final UUID parentAddressLabel) {+ this.parentAddressLabel = parentAddressLabel;+ if (parentAddressLabel != null) {+ parentAddress = MeshAddress.generateVirtualAddress(parentAddressLabel);+ }+ }++ /**+ * Returns address of the parent group if the group has one+ *+ * @return parent address+ */+ public int getParentAddress() {+ return parentAddress;+ }++ /**+ * Sets the parent address, if this group belongs to a parent group+ *+ * @param parentAddress address of the parent group+ */+ public void setParentAddress(final int parentAddress) {+ if (MeshAddress.isValidVirtualAddress(parentAddress)) {+ throw new IllegalArgumentException("Assigning a virtual address to parentAddress can be done only by setting a parent address label");+ } else if (!MeshAddress.isValidGroupAddress(parentAddress)) {+ throw new IllegalArgumentException("parentAddress must be a group address value");+ }+ this.parentAddress = parentAddress;+ this.parentAddressLabel = null;+ }++ /**+ * Returns the group name of a mesh network+ */+ public String getName() {+ return name;+ }++ /**+ * Sets a name to a mesh group+ */+ public void setName(final String name) {+ this.name = name;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/GroupsConfig.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/GroupsConfig.javanew file mode 100644index 000000000..95251e638--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/GroupsConfig.java@@ -0,0 +1,62 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import java.util.List;++/**+ * Contains the configuration required when exporting a selected number of Groups in a mesh network.+ */+public class GroupsConfig extends ExportConfig {++ /**+ * Use this class to configure when exporting all the Groups.+ */+ public static class ExportAll implements Builder {+ @Override+ public GroupsConfig build() {+ return new GroupsConfig(this);+ }+ }++ /**+ * Use this class to configure when exporting the related Groups, which means that the exported+ * configuration will only contain those groups that any exported model is subscribed or publishing to+ */+ public static class ExportRelated implements Builder {+ @Override+ public GroupsConfig build() {+ return new GroupsConfig(this);+ }+ }++ /**+ * Use this class to configure when exporting some of the groups.+ */+ public static class ExportSome implements Builder {++ private final List<Group> groups;++ /**+ * Constructs ExportSome to export only a selected number of Groups when exporting a mesh network.+ * Excluded groups will also be excluded from subscription lists and publish information in exported Models.+ *+ * @param groups List of Groups to export.+ */+ public ExportSome(final List<Group> groups) {+ this.groups = groups;+ }++ protected List<Group> getGroups() {+ return groups;+ }++ @Override+ public ExportConfig build() {+ return new GroupsConfig(this);+ }+ }++ GroupsConfig(final Builder config) {+ super(config);+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/InternalMeshManagerCallbacks.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/InternalMeshManagerCallbacks.javanew file mode 100644index 000000000..b6e58bb48--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/InternalMeshManagerCallbacks.java@@ -0,0 +1,14 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import org.openremote.agent.protocol.bluetooth.mesh.transport.ProvisionedMeshNode;++interface InternalMeshManagerCallbacks {++ /**+ * Internal callback to notify the {@link MeshManagerApi} of provisioned nodes+ *+ * @param meshNode node that was provisioned+ */+ void onNodeProvisioned(final ProvisionedMeshNode meshNode);+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/InternalProvisioningCallbacks.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/InternalProvisioningCallbacks.javanew file mode 100644index 000000000..b9078ba44--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/InternalProvisioningCallbacks.java@@ -0,0 +1,16 @@+package org.openremote.agent.protocol.bluetooth.mesh;++/**+ * Internal provisioning callbacks+ */+public interface InternalProvisioningCallbacks {++ /**+ * Generates confirmation inputs based on the public key xy components of provisioner and provisionee+ *+ * @param provisionerPublicKeyXY provisioner public key xy+ * @param provisioneePublicKeyXY provisionee publick key xy+ */+ byte[] generateConfirmationInputs(final byte[] provisionerPublicKeyXY, final byte[] provisioneePublicKeyXY);++}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/InternalTransportCallbacks.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/InternalTransportCallbacks.javanew file mode 100644index 000000000..534ac5302--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/InternalTransportCallbacks.java@@ -0,0 +1,79 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import org.openremote.agent.protocol.bluetooth.mesh.provisionerstates.UnprovisionedMeshNode;+import org.openremote.agent.protocol.bluetooth.mesh.transport.MeshMessage;+import org.openremote.agent.protocol.bluetooth.mesh.transport.ProvisionedMeshNode;+import org.openremote.agent.protocol.bluetooth.mesh.utils.ProxyFilter;++import java.util.List;++public interface InternalTransportCallbacks {+++ /**+ * Returns an application key with a given key index+ *+ * @param boundNetKeyIndex NetKey index+ */+ List<ApplicationKey> getApplicationKeys(final int boundNetKeyIndex);++ /**+ * Returns the node with the corresponding unicast address+ *+ * @param unicast unicast address+ */+ ProvisionedMeshNode getNode(final int unicast);++ /**+ * Returns the Provisioner with the corresponding unicast address+ *+ * @param unicast unicast address+ */+ Provisioner getProvisioner(final int unicast);++ /**+ * Send mesh pdu+ *+ * @param meshNode mesh node to send to+ * @param pdu mesh pdu to be sent+ */+ void sendProvisioningPdu(final UnprovisionedMeshNode meshNode, final byte[] pdu);++ /**+ * Callback that is invoked when a mesh pdu is created+ *+ * @param dst Destination address to be sent+ * @param pdu mesh pdu to be sent+ */+ void onMeshPduCreated(final int dst, final byte[] pdu);+++ ProxyFilter getProxyFilter();++ void setProxyFilter(final ProxyFilter filter);++ /**+ * Update mesh network+ *+ * @param message mesh message+ */+ void updateMeshNetwork(final MeshMessage message);++ /**+ * This callback is invoked when the mesh node is successfully reset+ *+ * @param meshNode mesh to be updated+ */+ void onMeshNodeReset(final ProvisionedMeshNode meshNode);+++ /**+ * Returns the mesh network+ */+ MeshNetwork getMeshNetwork();++ void storeScene(final int address, final int currentScene, final List<Integer> scenes);++ void deleteScene(final int address, final int currentScene, final List<Integer> scenes);+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/IvIndex.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/IvIndex.javanew file mode 100644index 000000000..50889ef37--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/IvIndex.java@@ -0,0 +1,76 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import java.util.Calendar;++/**+ * Class containing the current IV Index State of the network.+ */+public class IvIndex {++ private final int ivIndex;+ private final boolean isIvUpdateActive; // False: Normal Operation, True: IV Update in progress+ private boolean ivRecoveryFlag = false;+ private Calendar transitionDate;++ /**+ * Construct the IV Index state of the mesh network+ *+ * @param ivIndex IV Index of the network.+ * @param isIvUpdateActive If true IV Update is in progress and false the network is in Normal operation.+ * @param transitionDate Time when the last IV Update happened+ */+ public IvIndex(final int ivIndex, final boolean isIvUpdateActive, final Calendar transitionDate) {+ this.ivIndex = ivIndex;+ this.isIvUpdateActive = isIvUpdateActive;+ this.transitionDate = transitionDate;+ }++ @Override+ public String toString() {+ return "IV Index: " + ivIndex + ", IV Update Active: " + isIvUpdateActive;+ }++ /**+ * Returns current iv index+ */+ public int getIvIndex() {+ return ivIndex;+ }++ /**+ * Returns the current iv update flag.+ */+ public boolean isIvUpdateActive() {+ return isIvUpdateActive;+ }++ /**+ * Returns iv index used when transmitting messages.+ */+ public int getTransmitIvIndex() {+ return (isIvUpdateActive && ivIndex != 0) ? ivIndex - 1 : ivIndex;+ }++ public boolean getIvRecoveryFlag() {+ return ivRecoveryFlag;+ }++ public void setIvRecoveryFlag(boolean ivRecoveryFlag) {+ this.ivRecoveryFlag = ivRecoveryFlag;+ }++ public Calendar getTransitionDate() {+ return transitionDate;+ }++ @Override+ public boolean equals(Object o) {+ if (this == o) return true;+ if (o == null || getClass() != o.getClass()) return false;+ IvIndex ivIndex1 = (IvIndex) o;+ return ivIndex == ivIndex1.ivIndex &&+ isIvUpdateActive == ivIndex1.isIvUpdateActive &&+ ivRecoveryFlag == ivIndex1.ivRecoveryFlag &&+ (transitionDate.getTimeInMillis() == ivIndex1.transitionDate.getTimeInMillis());+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MainThreadManager.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MainThreadManager.javanew file mode 100644index 000000000..682f61e00--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MainThreadManager.java@@ -0,0 +1,51 @@+/*+ * Copyright 2021, 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.bluetooth.mesh;++import java.util.concurrent.BlockingQueue;+import java.util.concurrent.LinkedBlockingQueue;++public class MainThreadManager implements Runnable {++ private final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();++ public MainThreadManager() {+ }++ @Override+ public void run() {+ while (!Thread.currentThread().isInterrupted()) {+ try {+ Runnable command = queue.take();+ command.run();+ } catch (InterruptedException e) {+ return;+ }+ }+ }++ public void enqueue(Runnable runnable) {+ try {+ queue.put(runnable);+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ }+ }+}\ No newline at end of filediff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshBeacon.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshBeacon.javanew file mode 100644index 000000000..55ef153af--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshBeacon.java@@ -0,0 +1,32 @@+package org.openremote.agent.protocol.bluetooth.mesh;++/**+ * Abstract class containing mesh beacon information+ */+public abstract class MeshBeacon {++ private static final String TAG = MeshBeacon.class.getSimpleName();+ static final int MESH_BEACON = 0x2B;+ final byte[] beaconData;+ final int beaconType;+++ /**+ * Constructs a {@link MeshBeacon} object+ *+ * @param beaconData beacon data advertised by the mesh beacon+ * @throws IllegalArgumentException if beacon data provided is empty or null+ */+ MeshBeacon(final byte[] beaconData) {+ if (beaconData == null)+ throw new IllegalArgumentException("Invalid beacon data");+ this.beaconData = beaconData;+ beaconType = beaconData[0];+ }++ /**+ * Returns the beacon type value+ */+ public abstract int getBeaconType();++}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshKey.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshKey.javanew file mode 100644index 000000000..1230b9b92--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshKey.java@@ -0,0 +1,173 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import org.openremote.model.util.TextUtil;++import javax.validation.constraints.NotNull;+import java.util.Arrays;+import java.util.Objects;++abstract class MeshKey implements Cloneable {++ protected int id;+ protected String meshUuid;+ protected int keyIndex;+ protected String name;+ protected byte[] key;+ protected byte[] oldKey;++ MeshKey() {+ }++ MeshKey(final int keyIndex, @NotNull final byte[] key) {+ Objects.requireNonNull(key);++ this.keyIndex = keyIndex;+ if (key.length != 16) {+ throw new IllegalArgumentException("Application key must be 16-bytes");+ }+ this.key = key;+ }++ public int getId() {+ return id;+ }++ public void setId(final int id) {+ this.id = id;+ }++ /**+ * Returns the meshUuid of the Mesh network+ *+ * @return String meshUuid+ */+ public String getMeshUuid() {+ return meshUuid;+ }++ /**+ * Sets the meshUuid of the mesh network to this application key+ *+ * @param meshUuid mesh network meshUuid+ */+ public void setMeshUuid(final String meshUuid) {+ this.meshUuid = meshUuid;+ }++ /**+ * Returns a friendly name of the application key+ *+ * @return string containing the name+ */+ public String getName() {+ return name;+ }++ /**+ * Sets a friendly name of the application key+ *+ * @param name friendly name for the application key+ */+ public void setName(@NotNull final String name) throws IllegalArgumentException {+ if (TextUtil.isNullOrEmpty(name))+ throw new IllegalArgumentException("Name cannot be empty!");+ this.name = name;+ }++ /**+ * Returns the application key+ *+ * @return 16 byte application key+ */+ public byte[] getKey() {+ return key;+ }++ /**+ * Sets a network key.+ *+ * <p>+ * In order to change the key call {@link BaseMeshNetwork#updateNetKey(NetworkKey, String)} or {@link BaseMeshNetwork#updateAppKey(ApplicationKey, String)})}}+ * </p>+ *+ * @param key 16-byte network key+ */+ public void setKey(@NotNull final byte[] key) {+ Objects.requireNonNull(key);+ if (valid(key)) {+ this.key = key;+ }+ }++ /**+ * Returns the application key index+ *+ * @return key index+ */+ public int getKeyIndex() {+ return keyIndex;+ }++ /**+ * Sets the key index of network key+ *+ * @param keyIndex index+ */+ public void setKeyIndex(final int keyIndex) {+ this.keyIndex = keyIndex;+ }++ /**+ * Returns the old app key+ *+ * @return old key+ */+ public byte[] getOldKey() {+ return oldKey;+ }++ /**+ * Set the old key+ *+ * @param oldKey old app key+ */+ public void setOldKey(final byte[] oldKey) {+ this.oldKey = oldKey;+ }++ @Override+ public boolean equals(final Object obj) {+ if (obj == this) {+ return true;+ }+ if (obj instanceof ApplicationKey) {+ final ApplicationKey appKey = (ApplicationKey) obj;++ return Arrays.equals(key, appKey.key) && keyIndex == appKey.keyIndex;+ } else if (obj instanceof NetworkKey) {+ final NetworkKey netKey = (NetworkKey) obj;++ return Arrays.equals(key, netKey.key) && keyIndex == netKey.keyIndex;+ }+ return false;+ }++ public MeshKey clone() throws CloneNotSupportedException {+ return (MeshKey) super.clone();+ }++ protected boolean valid(@NotNull final byte[] key) {+ Objects.requireNonNull(key);+ if (key.length != 16)+ throw new IllegalArgumentException("Key must be of length 16!");+ return true;+ }++ protected boolean distributeKey(@NotNull final byte[] key) {+ Objects.requireNonNull(key);+ if (!Arrays.equals(this.key, oldKey))+ setOldKey(this.key);+ setKey(key);+ return true;+ }+}\ No newline at end of filediff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshManagerApi.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshManagerApi.javanew file mode 100644index 000000000..989a98b50--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshManagerApi.java@@ -0,0 +1,997 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import org.openremote.agent.protocol.bluetooth.mesh.provisionerstates.UnprovisionedMeshNode;+import org.openremote.agent.protocol.bluetooth.mesh.transport.MeshMessage;+import org.openremote.agent.protocol.bluetooth.mesh.transport.NetworkLayerCallbacks;+import org.openremote.agent.protocol.bluetooth.mesh.transport.ProvisionedMeshNode;+import org.openremote.agent.protocol.bluetooth.mesh.transport.UpperTransportLayerCallbacks;+import org.openremote.agent.protocol.bluetooth.mesh.utils.ExtendedInvalidCipherTextException;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;+import org.openremote.agent.protocol.bluetooth.mesh.utils.ProxyFilter;+import org.openremote.agent.protocol.bluetooth.mesh.utils.SecureUtils;++import java.nio.ByteBuffer;+import java.security.Security;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.Calendar;+import java.util.Iterator;+import java.util.List;+import java.util.Locale;+import java.util.Map;+import java.util.UUID;+import java.util.concurrent.ScheduledExecutorService;+import java.util.concurrent.ScheduledFuture;+import java.util.concurrent.TimeUnit;+import java.util.logging.Logger;++public class MeshManagerApi implements MeshMngrApi{++ public static final Logger LOG = Logger.getLogger(MeshManagerApi.class.getName());+ public final static UUID MESH_PROVISIONING_UUID = UUID.fromString("00001827-0000-1000-8000-00805F9B34FB");+ public final static UUID MESH_PROXY_UUID = UUID.fromString("00001828-0000-1000-8000-00805F9B34FB");+ public static final byte PDU_TYPE_PROVISIONING = 0x03;++ private static final long PROXY_SAR_TRANSFER_TIME_OUT = 20 * 1000; // According to the spec the proxy protocol must contain an SAR timeout of 20 seconds.++ //PDU types+ public static final byte PDU_TYPE_NETWORK = 0x00;+ public static final byte PDU_TYPE_MESH_BEACON = 0x01;+ public static final byte PDU_TYPE_PROXY_CONFIGURATION = 0x02;+ //GATT level segmentation+ private static final byte GATT_SAR_COMPLETE = 0b00;+ private static final byte GATT_SAR_START = 0b01;+ private static final byte GATT_SAR_CONTINUATION = 0b10;+ private static final byte GATT_SAR_END = 0b11;+ //GATT level segmentation mask+ private static final int GATT_SAR_MASK = 0xC0;+ private static final int GATT_SAR_UNMASK = 0x3F;+ private static final int SAR_BIT_OFFSET = 6;++ private boolean ivUpdateTestModeActive = false;+ private boolean allowIvIndexRecoveryOver42 = false;++ private MeshNetwork mMeshNetwork;++ private MeshManagerCallbacks mMeshManagerCallbacks;+ private final MeshMessageHandler mMeshMessageHandler;+ private final MeshProvisioningHandler mMeshProvisioningHandler;+ // private final ImportExportUtils mImportExportUtils;++ private byte[] mOutgoingBuffer;+ private int mOutgoingBufferOffset;+ private byte[] mIncomingBuffer;+ private int mIncomingBufferOffset;++ private final ScheduledExecutorService executorService;++ private final Runnable mProxyProtocolTimeoutRunnable = new Runnable() {+ @Override+ public void run() {+ mMeshMessageHandler.onIncompleteTimerExpired(MeshAddress.UNASSIGNED_ADDRESS);+ }+ };++ /**+ * The mesh manager api constructor.+ */+ public MeshManagerApi(ScheduledExecutorService executorService) {+ this.executorService = executorService;+ // mHandler = new Handler(Looper.getMainLooper());+ mMeshProvisioningHandler = new MeshProvisioningHandler(internalTransportCallbacks, internalMeshMgrCallbacks);+ mMeshMessageHandler = new MeshMessageHandler(internalTransportCallbacks, networkLayerCallbacks, upperTransportLayerCallbacks);+ // mImportExportUtils = new ImportExportUtils();+ initBouncyCastle();+ //Init database+ // initDb(context);+ }+++ @Override+ public synchronized void setMeshManagerCallbacks(final MeshManagerCallbacks callbacks) {+ mMeshManagerCallbacks = callbacks;+ }++ @Override+ public void setMeshStatusCallbacks(final MeshStatusCallbacks callbacks) {+ mMeshMessageHandler.setMeshStatusCallbacks(callbacks);+ }++ @Override+ public synchronized final void handleWriteCallbacks(final int mtuSize, final byte[] data) {+ byte[] unsegmentedPdu;+ if (!shouldWaitForMoreData(data)) {+ unsegmentedPdu = data;+ } else {+ final byte[] combinedPdu = appendWritePdu(mtuSize, data);+ if (combinedPdu == null)+ return;+ else {+ unsegmentedPdu = removeSegmentation(mtuSize, combinedPdu);+ }+ }+ handleWriteCallbacks(unsegmentedPdu);+ }++ @Override+ public synchronized final void handleNotifications(final int mtuSize, final byte[] data) {+ byte[] unsegmentedPdu;+ if (!shouldWaitForMoreData(data)) {+ unsegmentedPdu = data;+ } else {+ final byte[] combinedPdu = appendPdu(mtuSize, data);+ if (combinedPdu == null) {+ //Start the timer+ toggleProxyProtocolSarTimeOut(data);+ return;+ } else {+ toggleProxyProtocolSarTimeOut(data);+ unsegmentedPdu = removeSegmentation(mtuSize, combinedPdu);+ }+ }+ parseNotifications(unsegmentedPdu);+ }++ public String dataAsHexString(byte[] data) {+ StringBuilder builder = new StringBuilder();+ for (int i = 0; i < data.length; i++) {+ builder.append(String.format("0x%02X%s", data[i] & 0xFF, i == (data.length - 1) ? "" : ", "));+ }+ return builder.toString();+ }+++ public synchronized MeshNetwork getMeshNetwork() {+ return mMeshNetwork;+ }++ /**+ * Toggles the Segmentation and Reassembly timeout for proxy configuration messages received via proxy protocol+ *+ * @param data pdu+ */+ private void toggleProxyProtocolSarTimeOut(final byte[] data) {+ final int pduType = MeshParserUtils.unsignedByteToInt(data[0]);+ if (pduType == ((GATT_SAR_START << SAR_BIT_OFFSET) | MeshManagerApi.PDU_TYPE_PROXY_CONFIGURATION)) {+ // mHandler.postDelayed(mProxyProtocolTimeoutRunnable, PROXY_SAR_TRANSFER_TIME_OUT);+ scheduleTimeoutHandler();+ } else if (pduType == ((GATT_SAR_END << SAR_BIT_OFFSET) | MeshManagerApi.PDU_TYPE_PROXY_CONFIGURATION)) {+ // mHandler.removeCallbacks(mProxyProtocolTimeoutRunnable);+ cancelTimeoutHandler();+ }+ }++ private ScheduledFuture<?> scheduledFuture;++ private void scheduleTimeoutHandler() {+ cancelTimeoutHandler();+ scheduledFuture = executorService.schedule(mProxyProtocolTimeoutRunnable, PROXY_SAR_TRANSFER_TIME_OUT, TimeUnit.MILLISECONDS);+ }++ private void cancelTimeoutHandler() {+ if (scheduledFuture != null) {+ scheduledFuture.cancel(false);+ }+ scheduledFuture = null;+ }++ /**+ * Parses notifications received by the client.+ *+ * @param unsegmentedPdu pdu received by the client.+ */+ private void parseNotifications(final byte[] unsegmentedPdu) {+ try {+ switch (unsegmentedPdu[0]) {+ case PDU_TYPE_NETWORK:+ //MeshNetwork PDU+ LOG.info("Received network pdu: " + MeshParserUtils.bytesToHex(unsegmentedPdu, true));+ mMeshMessageHandler.parseMeshPduNotifications(unsegmentedPdu, mMeshNetwork);+ break;+ case PDU_TYPE_MESH_BEACON:+ //Validate SNBs against all network keys+ NetworkKey networkKey;+ for (int i = 0; i < mMeshNetwork.getNetKeys().size(); i++) {+ networkKey = mMeshNetwork.getNetKeys().get(i);+ final byte[] receivedBeaconData = new byte[unsegmentedPdu.length - 1];+ System.arraycopy(unsegmentedPdu, 1, receivedBeaconData, 0, receivedBeaconData.length);+ final SecureNetworkBeacon receivedBeacon = new SecureNetworkBeacon(receivedBeaconData);++ final byte[] n = networkKey.getTxNetworkKey();+ final int flags = receivedBeacon.getFlags();+ final byte[] networkId = SecureUtils.calculateK3(n);+ final int ivIndex = receivedBeacon.getIvIndex().getIvIndex();+ LOG.info("Received mesh beacon: " + receivedBeacon.toString());++ final SecureNetworkBeacon localSecureNetworkBeacon = SecureUtils.createSecureNetworkBeacon(n, flags, networkId, ivIndex);+ //Check the the beacon received is a valid by matching the authentication values+ if (Arrays.equals(receivedBeacon.getAuthenticationValue(), localSecureNetworkBeacon.getAuthenticationValue())) {+ LOG.info("Secure Network Beacon beacon authenticated.");++ // The library does not retransmit Secure Network Beacon.+ // If this node is a member of a primary subnet and receives a Secure Network+ // beacon on a secondary subnet, it will disregard it.+ if (mMeshNetwork.getPrimaryNetworkKey() != null && networkKey.keyIndex != 0) {+ LOG.info("Discarding beacon for secondary subnet with network key index: " + networkKey.keyIndex);+ return;+ }++ // Get the last IV Index.+ /// The last used IV Index for this mesh network.+ final IvIndex lastIvIndex = mMeshNetwork.getIvIndex();+ LOG.info("Last IV Index: " + lastIvIndex.getIvIndex());+ /// The date of the last change of IV Index or IV Update Flag.+ final Calendar lastTransitionDate = lastIvIndex.getTransitionDate();+ /// A flag whether the IV has recently been updated using IV Recovery procedure.+ /// The at-least-96h requirement for the duration of the current state will not apply.+ /// The node shall not execute more than one IV Index Recovery within a period of 192 hours.+ final boolean isIvRecoveryActive = lastIvIndex.getIvRecoveryFlag();+ /// The test mode disables the 96h rule, leaving all other behavior unchanged.+ final boolean isIvTestModeActive = ivUpdateTestModeActive;++ final boolean flag = allowIvIndexRecoveryOver42;+ if (!receivedBeacon.canOverwrite(lastIvIndex, lastTransitionDate, isIvRecoveryActive, isIvTestModeActive, flag)) {+ String numberOfHoursSinceDate = ((Calendar.getInstance().getTimeInMillis() -+ lastTransitionDate.getTimeInMillis()) / (3600 * 1000)) + "h";+ LOG.info("Discarding beacon " + receivedBeacon.getIvIndex() ++ ", last " + lastIvIndex.getIvIndex() + ", changed: "+ + numberOfHoursSinceDate + "ago, test mode: " + ivUpdateTestModeActive);+ return;+ }++ final IvIndex receivedIvIndex = receivedBeacon.getIvIndex();+ mMeshNetwork.ivIndex = new IvIndex(receivedIvIndex.getIvIndex(), receivedIvIndex.isIvUpdateActive(), lastTransitionDate);++ if (mMeshNetwork.ivIndex.getIvIndex() > lastIvIndex.getIvIndex()) {+ LOG.info("Applying: " + mMeshNetwork.ivIndex.getIvIndex());+ }++ // If the IV Index used for transmitting messages effectively increased,+ // the Node shall reset the sequence number to 0x000000.+ if (mMeshNetwork.ivIndex.getTransmitIvIndex() > lastIvIndex.getTransmitIvIndex()) {+ LOG.info("Resetting local sequence numbers to 0");+ final Provisioner provisioner = mMeshNetwork.getSelectedProvisioner();+ final ProvisionedMeshNode node = mMeshNetwork.getNode(provisioner.getProvisionerUuid());+ node.setSequenceNumber(0);+ }++ //Updating the iv recovery flag+ if (lastIvIndex != mMeshNetwork.ivIndex) {+ final boolean ivRecovery = mMeshNetwork.getIvIndex().getIvIndex() > lastIvIndex.getIvIndex() + 1+ && !receivedBeacon.getIvIndex().isIvUpdateActive();+ mMeshNetwork.getIvIndex().setIvRecoveryFlag(ivRecovery);+ }++ if (!mMeshNetwork.ivIndex.getIvRecoveryFlag()) {+ final Iterator<Map.Entry<Integer, ArrayList<Integer>>> iterator = mMeshNetwork.networkExclusions.entrySet().iterator();+ while (iterator.hasNext()) {+ final Map.Entry<Integer, ArrayList<Integer>> exclusions = iterator.next();+ final int expectedIncrement = exclusions.getKey() + 2;+ if (mMeshNetwork.ivIndex.getIvIndex() >= expectedIncrement) {+ // Clear the last known sequence number of addresses that are to be removed from the exclusion list.+ // Decided to retain the last known sequence number as the IV Indexes increment the sequence number+ // will be greater than the last known anyways+ //for (Integer address : mMeshNetwork.networkExclusions.get(expectedIncrement)) {+ // mMeshNetwork.sequenceNumbers.removeAt(address);+ //}+ iterator.remove();+ }+ }+ }+ }+ }+ break;+ case PDU_TYPE_PROXY_CONFIGURATION:+ //Proxy configuration+ LOG.info("Received proxy configuration message: " + MeshParserUtils.bytesToHex(unsegmentedPdu, true));+ mMeshMessageHandler.parseMeshPduNotifications(unsegmentedPdu, mMeshNetwork);+ break;+ case PDU_TYPE_PROVISIONING:+ //Provisioning PDU+ LOG.info("Received provisioning message: " + MeshParserUtils.bytesToHex(unsegmentedPdu, true));+ mMeshProvisioningHandler.parseProvisioningNotifications(unsegmentedPdu);+ break;+ }+ } catch (ExtendedInvalidCipherTextException ex) {+ //TODO handle decryption failure+ } catch (IllegalArgumentException ex) {+ LOG.severe("Parsing notification failed: " + MeshParserUtils.bytesToHex(unsegmentedPdu, true) + " - " + ex.getMessage());+ }+ }++++ /**+ * Handles callbacks after writing to characteristics to maintain/update the state machine+ *+ * @param data written to the peripheral+ */+ private void handleWriteCallbacks(final byte[] data) {+ switch (data[0]) {+ case PDU_TYPE_NETWORK: // MeshNetwork PDU+ LOG.info("MeshNetwork pdu sent: " + MeshParserUtils.bytesToHex(data, true));+ break;+ case PDU_TYPE_MESH_BEACON: // MESH BEACON+ LOG.info("Mesh beacon pdu sent: " + MeshParserUtils.bytesToHex(data, true));+ break;+ case PDU_TYPE_PROXY_CONFIGURATION: // Proxy configuration+ LOG.info("Proxy configuration pdu sent: " + MeshParserUtils.bytesToHex(data, true));+ break;+ case PDU_TYPE_PROVISIONING: // Provisioning PDU+ LOG.info("Provisioning pdu sent: " + MeshParserUtils.bytesToHex(data, true));+ mMeshProvisioningHandler.handleProvisioningWriteCallbacks();+ break;+ }+ }++ private boolean shouldWaitForMoreData(final byte[] pdu) {+ final int gattSar = (pdu[0] & GATT_SAR_MASK) >> SAR_BIT_OFFSET;+ switch (gattSar) {+ case GATT_SAR_START:+ case GATT_SAR_CONTINUATION:+ case GATT_SAR_END:+ return true;+ default:+ return false;+ }+ }++ /**+ * Appends the PDUs that are segmented at gatt layer.+ *+ * @param mtuSize mtu size supported by the device/node+ * @param pdu pdu received by the provisioner+ * @return the combine pdu or returns null if not complete.+ */+ private byte[] appendPdu(final int mtuSize, final byte[] pdu) {+ if (mIncomingBuffer == null) {+ final int length = Math.min(pdu.length, mtuSize);+ mIncomingBufferOffset = 0;+ mIncomingBufferOffset += length;+ mIncomingBuffer = pdu;+ } else {+ final int length = Math.min(pdu.length, mtuSize);+ final byte[] buffer = new byte[mIncomingBuffer.length + length];+ System.arraycopy(mIncomingBuffer, 0, buffer, 0, mIncomingBufferOffset);+ System.arraycopy(pdu, 0, buffer, mIncomingBufferOffset, length);+ mIncomingBufferOffset += length;+ mIncomingBuffer = buffer;+ if (length < mtuSize) {+ final byte[] packet = mIncomingBuffer;+ mIncomingBuffer = null;+ return packet;+ }+ }+ return null;+ }++ /**+ * Appends the PDUs that are segmented at gatt layer.+ *+ * @param mtuSize mtu size supported by the device/node+ * @param pdu pdu received by the provisioner+ * @return the combine pdu or returns null if not complete.+ */+ private byte[] appendWritePdu(final int mtuSize, final byte[] pdu) {+ if (mOutgoingBuffer == null) {+ final int length = Math.min(pdu.length, mtuSize);+ mOutgoingBufferOffset = 0;+ mOutgoingBufferOffset += length;+ mOutgoingBuffer = pdu;+ } else {+ final int length = Math.min(pdu.length, mtuSize);+ final byte[] buffer = new byte[mOutgoingBuffer.length + length];+ System.arraycopy(mOutgoingBuffer, 0, buffer, 0, mOutgoingBufferOffset);+ System.arraycopy(pdu, 0, buffer, mOutgoingBufferOffset, length);+ mOutgoingBufferOffset += length;+ mOutgoingBuffer = buffer;+ if (length < mtuSize) {+ final byte[] packet = mOutgoingBuffer;+ mOutgoingBuffer = null;+ return packet;+ }+ }+ return null;+ }+++ @Override+ public synchronized void createMeshPdu(final int dst, final MeshMessage meshMessage) {+ if (!MeshAddress.isAddressInRange(dst)) {+ throw new IllegalArgumentException("Invalid address, destination address must be a valid 16-bit value.");+ }+ final Provisioner provisioner = mMeshNetwork.getSelectedProvisioner();+ if (provisioner != null && provisioner.getProvisionerAddress() != null) {+ UUID label = null;+ if (MeshAddress.isValidVirtualAddress(dst)) {+ label = mMeshNetwork.getLabelUuid(dst);+ if (label == null) {+ throw new IllegalArgumentException("Label UUID unavailable for the virtual address provided");+ }+ }+ mMeshMessageHandler.createMeshMessage(provisioner.getProvisionerAddress(), dst, label, meshMessage);+ } else {+ throw new IllegalArgumentException("Provisioner address not set, please assign an address to the provisioner.");+ }+ }++ // public synchronized final void resetMeshNetwork() {+ public synchronized final void resetMeshNetwork(int provisionerAddress) {+ //We delete the existing network as the user has already given the+ ivUpdateTestModeActive = false;+ allowIvIndexRecoveryOver42 = false;+ final MeshNetwork meshNet = mMeshNetwork;+ // deleteMeshNetworkFromDb(meshNet);+ final MeshNetwork newMeshNetwork = generateMeshNetwork(provisionerAddress);+ newMeshNetwork.setCallbacks(callbacks);+ insertNetwork(newMeshNetwork);+ mMeshNetwork = newMeshNetwork;+ mMeshManagerCallbacks.onNetworkLoaded(newMeshNetwork);+ }+++ private MeshNetwork generateMeshNetwork(int provisionerAddress) {+ final String meshUuid = UUID.randomUUID().toString().toUpperCase(Locale.US);++ final MeshNetwork network = new MeshNetwork(meshUuid);+ // network.netKeys = generateNetKeys(meshUuid);+ // network.appKeys = generateAppKeys(meshUuid);+ //final AllocatedUnicastRange unicastRange = new AllocatedUnicastRange(0x0001, 0x199A);+ final AllocatedUnicastRange unicastRange = new AllocatedUnicastRange(provisionerAddress, provisionerAddress);+ final AllocatedGroupRange groupRange = new AllocatedGroupRange(0xC000, 0xCC9A);+ final AllocatedSceneRange sceneRange = new AllocatedSceneRange(0x0001, 0x3333);+ final Provisioner provisioner = network.createProvisioner("nRF Mesh Provisioner", unicastRange, groupRange, sceneRange);+ final int unicast = provisioner.getAllocatedUnicastRanges().get(0).getLowAddress();+ provisioner.assignProvisionerAddress(unicast);+ network.selectProvisioner(provisioner);+ network.addProvisioner(provisioner);+ final ProvisionedMeshNode node = network.getNode(unicast);+ if (node != null) {+ network.unicastAddress = node.getUnicastAddress() + (node.getNumberOfElements() - 1);+ } else {+ network.unicastAddress = 1;+ }+ network.lastSelected = true;+ network.sequenceNumbers.clear(); //Clear the sequence numbers first+ network.loadSequenceNumbers();+ ivUpdateTestModeActive = false;+ allowIvIndexRecoveryOver42 = false;+ return network;+ }++ private List<NetworkKey> generateNetKeys(final String meshUuid) {+ final List<NetworkKey> networkKeys = new ArrayList<>();+ final NetworkKey networkKey = new NetworkKey(0, SecureUtils.generateRandomNumber());+ networkKey.setMeshUuid(meshUuid);+ networkKeys.add(networkKey);+ return networkKeys;+ }++ private List<ApplicationKey> generateAppKeys(final String meshUuid) {+ final List<ApplicationKey> appKeys = new ArrayList<>();+ for (int i = 0; i < 3; i++) {+ final ApplicationKey appKey = new ApplicationKey(i, SecureUtils.generateRandomNumber());+ appKey.setMeshUuid(meshUuid);+ appKeys.add(appKey);+ }+ return appKeys;+ }++ private void deleteNode(final ProvisionedMeshNode meshNode) {+ deleteSceneAddress(meshNode.getUnicastAddress());+ // We should not remove the last known sequence number when resetting a node.+ // This should be kept until the current iv index has incremented by 2 and delete it when+ // clearing the exclusion lists+ // mMeshNetwork.sequenceNumbers.delete(meshNode.getUnicastAddress());+ mMeshMessageHandler.resetState(meshNode.getUnicastAddress());+ // mMeshNetworkDb.deleteNode(mProvisionedNodeDao, meshNode);+ mMeshManagerCallbacks.onNetworkUpdated(mMeshNetwork);+ }++ /**+ * Deletes an address from the scenes in the network. This is to be called when resetting or deleting a node from the network.+ *+ * @param address Address to be removed.+ */+ private void deleteSceneAddress(final int address) {+ for (Scene scene : mMeshNetwork.getScenes()) {+ if (scene.addresses.remove((Integer) address)) {+ LOG.info("Node removed from " + scene.getName());+ }+ }+ }+++ /**+ * Callbacks observing user updates on the mesh network object+ */+ private final MeshNetworkCallbacks callbacks = new MeshNetworkCallbacks() {+ @Override+ public void onMeshNetworkUpdated() {+ synchronized (MeshManagerApi.this) {+ mMeshNetwork.setTimestamp(System.currentTimeMillis());+ // mMeshNetworkDb.update(mMeshNetworkDao, mMeshNetwork);+ mMeshManagerCallbacks.onNetworkUpdated(mMeshNetwork);+ }+ }++ @Override+ public void onNetworkKeyAdded(final NetworkKey networkKey) {+ synchronized (MeshManagerApi.this) {+ // mMeshNetworkDb.insert(mNetworkKeyDao, networkKey);+ mMeshManagerCallbacks.onNetworkUpdated(mMeshNetwork);+ }+ }++ @Override+ public void onNetworkKeyUpdated(final NetworkKey networkKey) {+ synchronized (MeshManagerApi.this) {+ // mMeshNetworkDb.update(mNetworkKeyDao, networkKey);+ mMeshManagerCallbacks.onNetworkUpdated(mMeshNetwork);+ }+ }++ @Override+ public void onNetworkKeyDeleted(final NetworkKey networkKey) {+ synchronized (MeshManagerApi.this) {+ // mMeshNetworkDb.delete(mNetworkKeyDao, networkKey);+ mMeshManagerCallbacks.onNetworkUpdated(mMeshNetwork);+ }+ }++ @Override+ public void onApplicationKeyAdded(final ApplicationKey applicationKey) {+ synchronized (MeshManagerApi.this) {+ // mMeshNetworkDb.insert(mApplicationKeyDao, applicationKey);+ mMeshManagerCallbacks.onNetworkUpdated(mMeshNetwork);+ }+ }++ @Override+ public void onApplicationKeyUpdated(final ApplicationKey applicationKey) {+ synchronized (MeshManagerApi.this) {+ // mMeshNetworkDb.update(mApplicationKeyDao, applicationKey);+ mMeshManagerCallbacks.onNetworkUpdated(mMeshNetwork);+ }+ }++ @Override+ public void onApplicationKeyDeleted(final ApplicationKey applicationKey) {+ synchronized (MeshManagerApi.this) {+ // mMeshNetworkDb.delete(mApplicationKeyDao, applicationKey);+ mMeshManagerCallbacks.onNetworkUpdated(mMeshNetwork);+ }+ }++ @Override+ public void onProvisionerAdded(final Provisioner provisioner) {+ synchronized (MeshManagerApi.this) {+ // mMeshNetworkDb.insert(mProvisionerDao, provisioner);+ mMeshManagerCallbacks.onNetworkUpdated(mMeshNetwork);+ }+ }++ @Override+ public void onProvisionerUpdated(final Provisioner provisioner) {+ synchronized (MeshManagerApi.this) {+ // mMeshNetworkDb.update(mProvisionerDao, provisioner);+ mMeshManagerCallbacks.onNetworkUpdated(mMeshNetwork);+ }+ }++ @Override+ public void onProvisionersUpdated(final List<Provisioner> provisioners) {+ synchronized (MeshManagerApi.this) {+ // mMeshNetworkDb.update(mProvisionerDao, provisioners);+ mMeshManagerCallbacks.onNetworkUpdated(mMeshNetwork);+ }+ }++ @Override+ public void onProvisionerDeleted(Provisioner provisioner) {+ synchronized (MeshManagerApi.this) {+ // mMeshNetworkDb.delete(mProvisionerDao, provisioner);+ mMeshManagerCallbacks.onNetworkUpdated(mMeshNetwork);+ }+ }++ @Override+ public void onNodeDeleted(final ProvisionedMeshNode meshNode) {+ deleteNode(meshNode);+ }++ @Override+ public void onNodeAdded(final ProvisionedMeshNode meshNode) {+ synchronized (MeshManagerApi.this) {+ // mMeshNetworkDb.insert(mProvisionedNodeDao, meshNode);+ mMeshManagerCallbacks.onNetworkUpdated(mMeshNetwork);+ }+ }++ @Override+ public void onNodeUpdated(final ProvisionedMeshNode meshNode) {+ synchronized (MeshManagerApi.this) {+ // mMeshNetworkDb.update(mProvisionedNodeDao, meshNode);+ mMeshManagerCallbacks.onNetworkUpdated(mMeshNetwork);+ }+ }++ @Override+ public void onNodesUpdated() {+ synchronized (MeshManagerApi.this) {+ // mMeshNetworkDb.update(mProvisionedNodesDao, mMeshNetwork.nodes);+ mMeshManagerCallbacks.onNetworkUpdated(mMeshNetwork);+ }+ }++ @Override+ public void onGroupAdded(final Group group) {+ synchronized (MeshManagerApi.this) {+ // mMeshNetworkDb.insert(mGroupDao, group);+ mMeshManagerCallbacks.onNetworkUpdated(mMeshNetwork);+ }+ }++ @Override+ public void onGroupUpdated(final Group group) {+ synchronized (MeshManagerApi.this) {+ // mMeshNetworkDb.update(mGroupDao, group);+ mMeshManagerCallbacks.onNetworkUpdated(mMeshNetwork);+ }+ }++ @Override+ public void onGroupDeleted(final Group group) {+ synchronized (MeshManagerApi.this) {+ // mMeshNetworkDb.delete(mGroupDao, group);+ mMeshManagerCallbacks.onNetworkUpdated(mMeshNetwork);+ }+ }++ @Override+ public void onSceneAdded(final Scene scene) {+ synchronized (MeshManagerApi.this) {+ // mMeshNetworkDb.insert(mSceneDao, scene);+ mMeshManagerCallbacks.onNetworkUpdated(mMeshNetwork);+ }+ }++ @Override+ public void onSceneUpdated(final Scene scene) {+ synchronized (MeshManagerApi.this) {+ // mMeshNetworkDb.update(mSceneDao, scene);+ mMeshManagerCallbacks.onNetworkUpdated(mMeshNetwork);+ }+ }++ @Override+ public void onSceneDeleted(final Scene scene) {+ synchronized (MeshManagerApi.this) {+ // mMeshNetworkDb.delete(mSceneDao, scene);+ mMeshManagerCallbacks.onNetworkUpdated(mMeshNetwork);+ }+ }+ };++ private final InternalMeshManagerCallbacks internalMeshMgrCallbacks = new InternalMeshManagerCallbacks() {+ @Override+ public void onNodeProvisioned(final ProvisionedMeshNode meshNode) {+ synchronized (MeshManagerApi.this) {+ updateProvisionedNodeList(meshNode);+ mMeshNetwork.sequenceNumbers.put(meshNode.getUnicastAddress(), meshNode.getSequenceNumber());+ mMeshNetwork.unicastAddress = mMeshNetwork.nextAvailableUnicastAddress(meshNode.getNumberOfElements(), mMeshNetwork.getSelectedProvisioner());+ //Set the mesh network uuid to the node so we can identify nodes belonging to a network+ meshNode.setMeshUuid(mMeshNetwork.getMeshUUID());+ // mMeshNetworkDb.insert(mProvisionedNodeDao, meshNode);+ // mMeshNetworkDb.update(mProvisionerDao,+ // mMeshNetwork.getSelectedProvisioner());+ mMeshManagerCallbacks.onNetworkUpdated(mMeshNetwork);+ }+ }++ private void updateProvisionedNodeList(final ProvisionedMeshNode meshNode) {+ for (int i = 0; i < mMeshNetwork.nodes.size(); i++) {+ final ProvisionedMeshNode node = mMeshNetwork.nodes.get(i);+ if (meshNode.getUuid().equals(node.getUuid())) {+ mMeshNetwork.nodes.remove(i);+ break;+ }+ }+ mMeshNetwork.nodes.add(meshNode);+ }+ };++ private final NetworkLayerCallbacks networkLayerCallbacks = new NetworkLayerCallbacks() {++ @Override+ public Provisioner getProvisioner() {+ synchronized (MeshManagerApi.this) {+ return mMeshNetwork.getSelectedProvisioner();+ }+ }++ @Override+ public Provisioner getProvisioner(final int unicastAddress) {+ synchronized (MeshManagerApi.this) {+ for (Provisioner provisioner : mMeshNetwork.getProvisioners()) {+ if (provisioner.isLastSelected())+ return provisioner;+ }+ return null;+ }+ }++ @Override+ public NetworkKey getPrimaryNetworkKey() {+ synchronized (MeshManagerApi.this) {+ return mMeshNetwork.getPrimaryNetworkKey();+ }+ }++ @Override+ public NetworkKey getNetworkKey(final int keyIndex) {+ synchronized (MeshManagerApi.this) {+ return mMeshNetwork.getNetKey(keyIndex);+ }+ }++ @Override+ public List<NetworkKey> getNetworkKeys() {+ synchronized (MeshManagerApi.this) {+ return mMeshNetwork.getNetKeys();+ }+ }+ };++ private final UpperTransportLayerCallbacks upperTransportLayerCallbacks = new UpperTransportLayerCallbacks() {++ @Override+ public ProvisionedMeshNode getNode(final int unicastAddress) {+ synchronized (MeshManagerApi.this) {+ return mMeshNetwork.getNode(unicastAddress);+ }+ }++ @Override+ public byte[] getIvIndex() {+ synchronized (MeshManagerApi.this) {+ int ivIndex = mMeshNetwork.getIvIndex().getTransmitIvIndex();+ return ByteBuffer.allocate(4).putInt(ivIndex).array();+ }+ }++ @Override+ public byte[] getApplicationKey(final int aid) {+ synchronized (MeshManagerApi.this) {+ for (ApplicationKey key : mMeshNetwork.getAppKeys()) {+ final byte[] k = key.getKey();+ if (aid == SecureUtils.calculateK4(k)) {+ return key.getKey();+ }+ }+ return null;+ }+ }++ @Override+ public List<ApplicationKey> getApplicationKeys(final int boundNetKeyIndex) {+ synchronized (MeshManagerApi.this) {+ final List<ApplicationKey> keys = new ArrayList<>();+ for (ApplicationKey key : mMeshNetwork.getAppKeys()) {+ if (key.getBoundNetKeyIndex() == boundNetKeyIndex) {+ keys.add(key);+ }+ }+ return keys;+ }+ }++ /* @Nullable */+ @Override+ public List<Group> gerVirtualGroups() {+ synchronized (MeshManagerApi.this) {+ return mMeshNetwork.getGroups();+ }+ }+ };++ private final InternalTransportCallbacks internalTransportCallbacks = new InternalTransportCallbacks() {++ @Override+ public List<ApplicationKey> getApplicationKeys(final int boundNetKeyIndex) {+ synchronized (MeshManagerApi.this) {+ return mMeshNetwork.getAppKeys(boundNetKeyIndex);+ }+ }++ @Override+ public ProvisionedMeshNode getNode(final int unicast) {+ synchronized (MeshManagerApi.this) {+ return mMeshNetwork.getNode(unicast);+ }+ }++ @Override+ public Provisioner getProvisioner(final int unicast) {+ return null;+ }++ @Override+ public void sendProvisioningPdu(final UnprovisionedMeshNode meshNode, final byte[] pdu) {+ synchronized (MeshManagerApi.this) {+ final int mtu = mMeshManagerCallbacks.getMtu();+ mMeshManagerCallbacks.sendProvisioningPdu(meshNode, applySegmentation(mtu, pdu));+ }+ }++ @Override+ public void onMeshPduCreated(final int dst, final byte[] pdu) {+ synchronized (MeshManagerApi.this) {+ //We must save the mesh network state for every message that is being sent out.+ //This will specifically save the sequence number for every message sent.+ final ProvisionedMeshNode meshNode = mMeshNetwork.getNode(dst);+ updateNetwork(meshNode);+ final int mtu = mMeshManagerCallbacks.getMtu();+ mMeshManagerCallbacks.onMeshPduCreated(applySegmentation(mtu, pdu));+ }+ }++ @Override+ public ProxyFilter getProxyFilter() {+ synchronized (MeshManagerApi.this) {+ return mMeshNetwork.getProxyFilter();+ }+ }++ @Override+ public void setProxyFilter(final ProxyFilter filter) {+ synchronized (MeshManagerApi.this) {+ mMeshNetwork.setProxyFilter(filter);+ }+ }++ @Override+ public void updateMeshNetwork(final MeshMessage message) {+ synchronized (MeshManagerApi.this) {+ final ProvisionedMeshNode meshNode = mMeshNetwork.getNode(message.getSrc());+ updateNetwork(meshNode);+ }+ }++ @Override+ public void onMeshNodeReset(final ProvisionedMeshNode meshNode) {+ synchronized (MeshManagerApi.this) {+ if (meshNode != null) {+ if (mMeshNetwork.deleteNode(meshNode)) {+ deleteNode(meshNode);+ }+ }+ }+ }++ @Override+ public MeshNetwork getMeshNetwork() {+ synchronized (MeshManagerApi.this) {+ return mMeshNetwork;+ }+ }++ @Override+ public void storeScene(final int address, final int currentScene, final List<Integer> scenes) {+ synchronized (MeshManagerApi.this) {+ final Scene scene = mMeshNetwork.getScene(currentScene);+ if (scene != null && !scene.getAddresses().contains(address)) {+ scene.addresses.add(address);+ }+ }+ }++ @Override+ public void deleteScene(final int address, final int currentScene, final List<Integer> scenes) {+ synchronized (MeshManagerApi.this) {+ final Scene scene = mMeshNetwork.getScene(currentScene);+ if (scene != null && scene.getAddresses().contains(address)) {+ scene.addresses.remove((Integer) address);+ }+ }+ }++ private void updateNetwork(final ProvisionedMeshNode meshNode) {+ synchronized (MeshManagerApi.this) {+ if (meshNode != null) {+ for (int i = 0; i < mMeshNetwork.nodes.size(); i++) {+ if (meshNode.getUnicastAddress() == mMeshNetwork.nodes.get(i).getUnicastAddress()) {+ mMeshNetwork.nodes.set(i, meshNode);+ break;+ }+ }+ }+ mMeshNetwork.setTimestamp(System.currentTimeMillis());+ // mMeshNetworkDb.update(mMeshNetwork, mMeshNetworkDao, mNetworkKeysDao, mApplicationKeysDao, mProvisionersDao, mProvisionedNodesDao,+ // mGroupsDao, mScenesDao);+ mMeshManagerCallbacks.onNetworkUpdated(mMeshNetwork);+ }+ }+ };++ private byte[] applySegmentation(final int mtuSize, final byte[] pdu) {+ int srcOffset = 0;+ int dstOffset = 0;+ final int chunks = (pdu.length + (mtuSize - 1)) / mtuSize;++ final int pduType = pdu[0];+ if (chunks > 1) {+ final byte[] segmentedBuffer = new byte[pdu.length + chunks - 1];+ int length;+ for (int i = 0; i < chunks; i++) {+ if (i == 0) {+ length = Math.min(pdu.length - srcOffset, mtuSize);+ System.arraycopy(pdu, srcOffset, segmentedBuffer, dstOffset, length);+ segmentedBuffer[0] = (byte) ((GATT_SAR_START << 6) | pduType);+ } else if (i == chunks - 1) {+ length = Math.min(pdu.length - srcOffset, mtuSize);+ segmentedBuffer[dstOffset] = (byte) ((GATT_SAR_END << 6) | pduType);+ System.arraycopy(pdu, srcOffset, segmentedBuffer, dstOffset + 1, length);+ } else {+ length = Math.min(pdu.length - srcOffset, mtuSize - 1);+ segmentedBuffer[dstOffset] = (byte) ((GATT_SAR_CONTINUATION << 6) | pduType);+ System.arraycopy(pdu, srcOffset, segmentedBuffer, dstOffset + 1, length);+ }+ srcOffset += length;+ dstOffset += mtuSize;+ }+ return segmentedBuffer;+ }+ return pdu;+ }++ private byte[] removeSegmentation(final int mtuSize, final byte[] data) {+ int srcOffset = 0;+ int dstOffset = 0;+ final int chunks = (data.length + (mtuSize - 1)) / mtuSize;+ if (chunks > 1) {+ final byte[] buffer = new byte[data.length - (chunks - 1)];+ int length;+ for (int i = 0; i < chunks; i++) {+ // when removing segmentation bits we only remove the start because the pdu type would be the same for each segment.+ // Therefore we can ignore this pdu type byte as they are already put together in the ble+ length = Math.min(buffer.length - dstOffset, mtuSize);+ if (i == 0) {+ System.arraycopy(data, srcOffset, buffer, dstOffset, length);+ buffer[0] = (byte) (buffer[0] & GATT_SAR_UNMASK);+ } else if (i == chunks - 1) {+ System.arraycopy(data, srcOffset + 1, buffer, dstOffset, length);+ } else {+ length = length - 1;+ System.arraycopy(data, srcOffset + 1, buffer, dstOffset, length);+ }+ srcOffset += mtuSize;+ dstOffset += length;+ }+ return buffer;+ }+ return data;+ }++ private void insertNetwork(final MeshNetwork meshNetwork) {+ meshNetwork.setLastSelected(true);+ //If there is only one provisioner we default to the zeroth+ if (meshNetwork.provisioners.size() == 1) {+ meshNetwork.provisioners.get(0).setLastSelected(true);+ }+ /*+ mMeshNetworkDb.insertNetwork(mMeshNetworkDao,+ mNetworkKeysDao,+ mApplicationKeysDao,+ mProvisionersDao,+ mProvisionedNodesDao,+ mGroupsDao, mScenesDao,+ meshNetwork);+ */+ }++ private void initBouncyCastle() {+ Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 1);+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshManagerCallbacks.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshManagerCallbacks.javanew file mode 100644index 000000000..192908824--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshManagerCallbacks.java@@ -0,0 +1,74 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import org.openremote.agent.protocol.bluetooth.mesh.provisionerstates.UnprovisionedMeshNode;++/**+ * Implement this class in order to get the transport callbacks from the {@link MeshManagerApi}+ */+public interface MeshManagerCallbacks {++ /**+ * Returns the network that was loaded+ *+ * @param meshNetwork{@link MeshNetwork that was loaded}+ */+ void onNetworkLoaded(final MeshNetwork meshNetwork);++ /**+ * Returns the network that was updated+ * <p>+ * This callback is invoked for every message that was sent or received as it changes the contents of the network+ * </p>+ *+ * @param meshNetwork{@link MeshNetwork that was loaded}+ */+ void onNetworkUpdated(final MeshNetwork meshNetwork);++ /**+ * Callback that notifies in case the mesh network was unable to load+ *+ * @param error error+ */+ void onNetworkLoadFailed(final String error);++ /**+ * Callbacks notifying the network was imported+ *+ * @param meshNetwork{@link MeshNetwork that was loaded}+ */+ void onNetworkImported(final MeshNetwork meshNetwork);++ /**+ * Callback that notifies in case the mesh network was unable to imported+ *+ * @param error error+ */+ void onNetworkImportFailed(final String error);++ /**+ * Send mesh pdu+ *+ * @param meshNode {@link UnprovisionedMeshNode}+ * @param pdu mesh pdu to be sent+ */+ void sendProvisioningPdu(final UnprovisionedMeshNode meshNode, final byte[] pdu);++ /**+ * Send mesh pdu+ *+ * @param pdu mesh pdu to be sent+ */+ void onMeshPduCreated(final byte[] pdu);++ /**+ * Get mtu size supported by the peripheral node+ * <p>+ * This is used to get the supported mtu size from the ble module, so that the messages+ * that are larger than the supported mtu size could be segmented+ * </p>+ *+ * @return mtu size+ */+ int getMtu();+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshMessageHandler.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshMessageHandler.javanew file mode 100644index 000000000..a4ce388b4--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshMessageHandler.java@@ -0,0 +1,37 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import org.openremote.agent.protocol.bluetooth.mesh.transport.BaseMeshMessageHandler;+import org.openremote.agent.protocol.bluetooth.mesh.transport.NetworkLayerCallbacks;+import org.openremote.agent.protocol.bluetooth.mesh.transport.UpperTransportLayerCallbacks;+import org.openremote.agent.protocol.bluetooth.mesh.utils.ExtendedInvalidCipherTextException;++/**+ * MeshMessageHandler class for handling mesh+ */+final class MeshMessageHandler extends BaseMeshMessageHandler {++ /**+ * Constructs MeshMessageHandler+ *+ * @param internalTransportCallbacks {@link InternalTransportCallbacks} Callbacks+ * @param networkLayerCallbacks {@link NetworkLayerCallbacks} network layer callbacks+ * @param upperTransportLayerCallbacks {@link UpperTransportLayerCallbacks} upper transport layer callbacks+ */+ MeshMessageHandler(final InternalTransportCallbacks internalTransportCallbacks,+ final NetworkLayerCallbacks networkLayerCallbacks,+ final UpperTransportLayerCallbacks upperTransportLayerCallbacks) {+ super(internalTransportCallbacks, networkLayerCallbacks, upperTransportLayerCallbacks);+ }++ @Override+ protected synchronized final void setMeshStatusCallbacks(final MeshStatusCallbacks statusCallbacks) {+ mStatusCallbacks = statusCallbacks;+ }+++ @Override+ protected synchronized final void parseMeshPduNotifications(final byte[] pdu, final MeshNetwork network) throws ExtendedInvalidCipherTextException {+ super.parseMeshPduNotifications(pdu, network);+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshMngrApi.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshMngrApi.javanew file mode 100644index 000000000..a3ff470fc--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshMngrApi.java@@ -0,0 +1,47 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import org.openremote.agent.protocol.bluetooth.mesh.transport.MeshMessage;++public interface MeshMngrApi {+ /**+ * Sets the {@link MeshManagerCallbacks} listener+ *+ * @param callbacks callbacks+ */+ void setMeshManagerCallbacks(final MeshManagerCallbacks callbacks);++ /**+ * Sets the {@link MeshManagerCallbacks} listener to return mesh status callbacks.+ *+ * @param callbacks callbacks+ */+ void setMeshStatusCallbacks(final MeshStatusCallbacks callbacks);++ /**+ * Handles notifications received by the client.+ * <p>+ * This method will check if the library should wait for more data in case of a gatt layer segmentation.+ * If its required the method will remove the segmentation bytes and reassemble the pdu together.+ * </p>+ *+ * @param mtuSize GATT MTU size+ * @param data PDU received by the client+ */+ void handleNotifications(final int mtuSize, final byte[] data);++ /**+ * Must be called to handle provisioning states+ *+ * @param mtuSize GATT MTU size+ * @param data PDU received by the client+ */+ void handleWriteCallbacks(final int mtuSize, final byte[] data);++ /**+ * Sends the specified mesh message specified within the {@link MeshMessage} object+ *+ * @param dst destination address+ * @param meshMessage {@link MeshMessage} Mesh message containing the message opcode and message parameters+ */+ void createMeshPdu(final int dst, final MeshMessage meshMessage) throws IllegalArgumentException;+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshNetwork.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshNetwork.javanew file mode 100644index 000000000..e0183ce69--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshNetwork.java@@ -0,0 +1,242 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import org.openremote.agent.protocol.bluetooth.mesh.transport.Element;+import org.openremote.agent.protocol.bluetooth.mesh.transport.MeshModel;+import org.openremote.agent.protocol.bluetooth.mesh.transport.ProvisionedMeshNode;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;++import java.util.ArrayList;+import java.util.Collections;+import java.util.List;+import java.util.Map;+import java.util.UUID;++public class MeshNetwork extends BaseMeshNetwork{++ public MeshNetwork(final String meshUUID) {+ super(meshUUID);+ }++ synchronized void setCallbacks(final MeshNetworkCallbacks mCallbacks) {+ this.mCallbacks = mCallbacks;+ }++ /**+ * Sets the time stamp+ *+ * @param timestamp timestamp+ */+ public synchronized void setTimestamp(long timestamp) {+ this.timestamp = timestamp;+ }++ /**+ * Returns a list of scenes.+ */+ public synchronized List<Scene> getScenes() {+ return Collections.unmodifiableList(scenes);+ }++ /**+ * Returns a group based on the group number+ */+ /* @Nullable */+ public synchronized Group getGroup(final int address) {+ for (final Group group : groups) {+ if (address == group.getAddress()) {+ return group;+ }+ }+ return null;+ }++ public synchronized List<Group> getGroups() {+ return groups;+ }++ public synchronized String getMeshUUID() {+ return meshUUID;+ }++ synchronized void setNetKeys(final List<NetworkKey> netKeys) {+ this.netKeys = netKeys;+ }++ public synchronized List<NetworkKey> getNetKeys() {+ return Collections.unmodifiableList(netKeys);+ }++ public synchronized NetworkKey getPrimaryNetworkKey() {+ for (NetworkKey networkKey : netKeys) {+ if (networkKey.getKeyIndex() == 0) {+ return networkKey;+ }+ }+ return null;+ }++ /**+ * Returns a list of {@link ApplicationKey} belonging to the mesh network+ */+ public synchronized List<ApplicationKey> getAppKeys() {+ return Collections.unmodifiableList(appKeys);+ }++ public synchronized IvIndex getIvIndex() {+ return ivIndex;+ }++ public synchronized String getSchema() {+ return schema;+ }++ public synchronized String getId() {+ return id;+ }++ public synchronized String getVersion() {+ return version;+ }++ /**+ * Returns the name of the mesh network+ */+ public synchronized String getMeshName() {+ return meshName;+ }++ /**+ * Returns the time stamp of th e mesh network+ */+ public synchronized long getTimestamp() {+ return timestamp;+ }++ /**+ * Set the partial configuration flag to true. To be used internally+ *+ * @param partial true if the network is set to be exported partially.+ */+ public synchronized void setPartial(final boolean partial) {+ this.partial = partial;+ }++ public synchronized void setLastSelected(final boolean lastSelected) {+ this.lastSelected = lastSelected;+ }++ /**+ * Returns a scene based on the scene number.+ */+ /* @Nullable */+ public synchronized Scene getScene(final int number) {+ for (final Scene scene : scenes) {+ if (number == scene.getNumber()) {+ return scene;+ }+ }+ return null;+ }++ /**+ * Returns the uuid for a given virtual address+ *+ * @param address virtual address+ * @return The label uuid if it's known to the provisioner or null otherwise+ */+ public synchronized UUID getLabelUuid(final int address) throws IllegalArgumentException {+ if (!MeshAddress.isValidVirtualAddress(address)) {+ throw new IllegalArgumentException("Address type must be a virtual address ");+ }++ for (ProvisionedMeshNode node : nodes) {+ for (Map.Entry<Integer, Element> elementEntry : node.getElements().entrySet()) {+ final Element element = elementEntry.getValue();+ for (Map.Entry<Integer, MeshModel> modelEntry : element.getMeshModels().entrySet()) {+ final MeshModel model = modelEntry.getValue();+ if (model != null) {+ if (model.getPublicationSettings() != null) {+ if (model.getPublicationSettings().getLabelUUID() != null) {+ if (address == MeshAddress.generateVirtualAddress(model.getPublicationSettings().getLabelUUID())) {+ return model.getPublicationSettings().getLabelUUID();+ }+ }+ }+ final UUID label = model.getLabelUUID(address);+ if (label != null) {+ return label;+ }+ }+ }+ }+ }+ return null;+ }++ /**+ * Returns the next unicast address for a node based on the number of elements+ * and the range allocated to the provisioner.+ * P.S. When setting up a new network don't forget to assign an address to the provisioner.+ * When importing a network make sure to create a new provisioner with a different address+ * which is the recommended approach. However you can also use the same provisioner+ * with a different address.+ *+ * @param elementCount Element count+ * @param provisioner provisioner+ * @return Allocated unicast address or -1 if none+ * @throws IllegalArgumentException if there is no allocated unicast range to the provisioner+ */+ public synchronized int nextAvailableUnicastAddress(final int elementCount, final Provisioner provisioner) throws IllegalArgumentException {+ if (provisioner.getAllocatedUnicastRanges().isEmpty()) {+ throw new IllegalArgumentException("Please allocate a unicast address range to the provisioner");+ }++ // Populate all addresses that are currently in use+ final ArrayList<Integer> usedAddresses = new ArrayList<>();+ for (ProvisionedMeshNode node : nodes) {+ usedAddresses.addAll(node.getElements().keySet());+ }+ // Excluded addresses with the current IvIndex and current IvIndex - 1 must be considered as addresses in use.+ if (networkExclusions.get(ivIndex.getIvIndex()) != null)+ usedAddresses.addAll(networkExclusions.get(ivIndex.getIvIndex()));+ if (networkExclusions.get(ivIndex.getIvIndex() - 1) != null)+ usedAddresses.addAll(networkExclusions.get(ivIndex.getIvIndex() - 1));++ Collections.sort(usedAddresses);+ // Iterate through all nodes just once, while iterating over ranges.+ int index = 0;+ for (AllocatedUnicastRange range : provisioner.getAllocatedUnicastRanges()) {+ // Start from the beginning of the current range.+ int address = range.getLowAddress();++ // Iterate through nodes that weren't checked yet in essence the used addresses which include the excluded adresses+ for (int usedAddress : usedAddresses) {++ // Skip nodes with addresses below the range.+ if (address > usedAddress) {+ continue;+ }++ // If we found a space before the current node, return the address.+ if (usedAddress > (address + (elementCount - 1))) {+ return address;+ }++ // Else, move the address to the next available address.+ address = usedAddress + 1;++ // If the new address is outside of the range, go to the next one.+ if (range.highAddress < address + (elementCount - 1)) {+ break;+ }+ }++ if (range.getHighAddress() >= address + (elementCount - 1)) {+ return address;+ }+ }++ // No address was found :(+ return -1;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshNetworkCallbacks.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshNetworkCallbacks.javanew file mode 100644index 000000000..ce5761910--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshNetworkCallbacks.java@@ -0,0 +1,50 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import org.openremote.agent.protocol.bluetooth.mesh.transport.ProvisionedMeshNode;++import java.util.List;++public interface MeshNetworkCallbacks {++ void onMeshNetworkUpdated();++ void onNetworkKeyAdded(final NetworkKey networkKey);++ void onNetworkKeyUpdated(final NetworkKey networkKey);++ void onNetworkKeyDeleted(final NetworkKey networkKey);++ void onApplicationKeyAdded(final ApplicationKey applicationKey);++ void onApplicationKeyUpdated(final ApplicationKey applicationKey);++ void onApplicationKeyDeleted(final ApplicationKey applicationKey);++ void onProvisionerAdded(final Provisioner provisioner);++ void onProvisionerUpdated(final Provisioner provisioner);++ void onProvisionersUpdated(final List<Provisioner> provisioner);++ void onProvisionerDeleted(final Provisioner provisioner);++ void onNodeDeleted(final ProvisionedMeshNode meshNode);++ void onNodeAdded(final ProvisionedMeshNode meshNode);++ void onNodeUpdated(final ProvisionedMeshNode meshNode);++ void onNodesUpdated();++ void onGroupAdded(final Group group);++ void onGroupUpdated(final Group group);++ void onGroupDeleted(final Group group);++ void onSceneAdded(final Scene scene);++ void onSceneUpdated(final Scene scene);++ void onSceneDeleted(final Scene scene);+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshProvisioningHandler.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshProvisioningHandler.javanew file mode 100644index 000000000..3acecfa93--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshProvisioningHandler.java@@ -0,0 +1,558 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import org.openremote.agent.protocol.bluetooth.mesh.provisionerstates.ProvisioningCapabilities;+import org.openremote.agent.protocol.bluetooth.mesh.provisionerstates.ProvisioningCapabilitiesState;+import org.openremote.agent.protocol.bluetooth.mesh.provisionerstates.ProvisioningCompleteState;+import org.openremote.agent.protocol.bluetooth.mesh.provisionerstates.ProvisioningConfirmationState;+import org.openremote.agent.protocol.bluetooth.mesh.provisionerstates.ProvisioningDataState;+import org.openremote.agent.protocol.bluetooth.mesh.provisionerstates.ProvisioningFailedState;+import org.openremote.agent.protocol.bluetooth.mesh.provisionerstates.ProvisioningInputCompleteState;+import org.openremote.agent.protocol.bluetooth.mesh.provisionerstates.ProvisioningInviteState;+import org.openremote.agent.protocol.bluetooth.mesh.provisionerstates.ProvisioningPublicKeyState;+import org.openremote.agent.protocol.bluetooth.mesh.provisionerstates.ProvisioningRandomConfirmationState;+import org.openremote.agent.protocol.bluetooth.mesh.provisionerstates.ProvisioningStartState;+import org.openremote.agent.protocol.bluetooth.mesh.provisionerstates.ProvisioningState;+import org.openremote.agent.protocol.bluetooth.mesh.provisionerstates.UnprovisionedMeshNode;+import org.openremote.agent.protocol.bluetooth.mesh.transport.ProvisionedMeshNode;+import org.openremote.agent.protocol.bluetooth.mesh.utils.InputOOBAction;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;+import org.openremote.agent.protocol.bluetooth.mesh.utils.OutputOOBAction;+import org.openremote.agent.protocol.bluetooth.mesh.utils.StaticOOBType;++import java.nio.ByteBuffer;+import java.util.UUID;+import java.util.logging.Logger;++class MeshProvisioningHandler implements InternalProvisioningCallbacks {+ public static final Logger LOG = Logger.getLogger(MeshProvisioningHandler.class.getName());+ static final int ATTENTION_TIMER = 5; //seconds+ private final InternalTransportCallbacks mInternalTransportCallbacks;+ private MeshProvisioningStatusCallbacks mStatusCallbacks;+ private UnprovisionedMeshNode mUnprovisionedMeshNode;+ private byte attentionTimer = ATTENTION_TIMER;++ private ProvisioningState provisioningState;+ private boolean isProvisioningPublicKeySent;+ private boolean isProvisioneePublicKeyReceived;+ private InternalMeshManagerCallbacks mInternalMeshManagerCallbacks;+ private byte[] confirmationInputs;++ /**+ * Constructs the mesh provisioning handler+ * <p>+ * This will handle the provisioning process through each step+ * </p>+ *+ * @param mInternalTransportCallbacks {@link InternalTransportCallbacks} callbacks+ * @param internalMeshManagerCallbacks {@link InternalMeshManagerCallbacks} callbacks+ */+ MeshProvisioningHandler(final InternalTransportCallbacks mInternalTransportCallbacks, final InternalMeshManagerCallbacks internalMeshManagerCallbacks) {+ this.mInternalTransportCallbacks = mInternalTransportCallbacks;+ this.mInternalMeshManagerCallbacks = internalMeshManagerCallbacks;+ }++ /**+ * Returns the unprovisioned mesh node+ */+ public UnprovisionedMeshNode getMeshNode() {+ return mUnprovisionedMeshNode;+ }++ /**+ * Sets the provisioning callbacks+ *+ * @param provisioningCallbacks {@link MeshProvisioningStatusCallbacks} callbacks+ */+ void setProvisioningCallbacks(MeshProvisioningStatusCallbacks provisioningCallbacks) {+ this.mStatusCallbacks = provisioningCallbacks;+ }++ void parseProvisioningNotifications(final byte[] data) {+ final UnprovisionedMeshNode unprovisionedMeshNode = mUnprovisionedMeshNode;+ try {+ switch (provisioningState.getState()) {+ case PROVISIONING_INVITE:+ break;+ case PROVISIONING_CAPABILITIES:+ if (validateMessage(data)) {+ if (!parseProvisioningCapabilitiesMessage(unprovisionedMeshNode, data)) {+ parseProvisioningState(unprovisionedMeshNode, data);+ }+ } else {+ parseProvisioningState(unprovisionedMeshNode, data);+ }+ break;+ case PROVISIONING_START:+ break;+ case PROVISIONING_PUBLIC_KEY:+ if (validateMessage(data)) {+ parseProvisioneePublicKeyXY(unprovisionedMeshNode, data);+ } else {+ parseProvisioningState(unprovisionedMeshNode, data);+ }+ break;+ case PROVISIONING_INPUT_COMPLETE:+ if (validateMessage(data)) {+ if (parseProvisioningInputCompleteState(data)) {+ sendProvisioningConfirmation(null);+ }+ } else {+ parseProvisioningState(unprovisionedMeshNode, data);+ }+ break;+ case PROVISIONING_CONFIRMATION:+ if (validateMessage(data)) {+ if (parseProvisioneeConfirmation(data)) {+ sendRandomConfirmationPDU(unprovisionedMeshNode);+ }+ } else {+ parseProvisioningState(unprovisionedMeshNode, data);+ }+ break;+ case PROVISIONING_RANDOM:+ if (validateMessage(data)) {+ if (parseProvisioneeRandom(data)) {+ sendProvisioningData(unprovisionedMeshNode);+ }+ } else {+ parseProvisioningState(unprovisionedMeshNode, data);+ }+ break;+ case PROVISIONING_DATA:+ case PROVISIONING_COMPLETE:+ case PROVISIONING_FAILED:+ parseProvisioningState(unprovisionedMeshNode, data);+ break;++ }+ } catch (Exception ex) {+ LOG.severe("Exception in " + provisioningState.getState().name() + " : " + ex.getMessage());+ parseProvisioningState(unprovisionedMeshNode, data);+ }+ }++ void handleProvisioningWriteCallbacks() {+ final UnprovisionedMeshNode unprovisionedMeshNode = mUnprovisionedMeshNode;+ switch (provisioningState.getState()) {+ case PROVISIONING_INVITE:+ provisioningState = new ProvisioningCapabilitiesState(unprovisionedMeshNode, mStatusCallbacks);+ break;+ case PROVISIONING_CAPABILITIES:+ break;+ case PROVISIONING_START:+ case PROVISIONING_PUBLIC_KEY:+ //Devices with lower mtu have to send the key in multiple segments+ sendProvisionerPublicKey(unprovisionedMeshNode);+ break;+ case PROVISIONING_INPUT_COMPLETE:+ break;+ case PROVISIONING_CONFIRMATION:+ break;+ case PROVISIONING_RANDOM:+ break;+ case PROVISIONING_DATA:+ break;+ }+ }++ private void parseProvisioningState(final UnprovisionedMeshNode unprovisionedMeshNode, final byte[] data) {+ isProvisioningPublicKeySent = false;+ isProvisioneePublicKeyReceived = false;+ if (data[1] == ProvisioningState.State.PROVISIONING_COMPLETE.getState()) {+ provisioningState = new ProvisioningCompleteState(unprovisionedMeshNode);+ //Generate the network id and store it in the mesh node, this is needed to reconnect to the device at a later stage.+ final ProvisionedMeshNode provisionedMeshNode = new ProvisionedMeshNode(unprovisionedMeshNode);+ mInternalMeshManagerCallbacks.onNodeProvisioned(provisionedMeshNode);+ mStatusCallbacks.onProvisioningCompleted(provisionedMeshNode, ProvisioningState.States.PROVISIONING_COMPLETE, data);+ } else {+ final ProvisioningFailedState provisioningFailedState = new ProvisioningFailedState();+ provisioningState = provisioningFailedState;+ if (provisioningFailedState.parseData(data)) {+ mStatusCallbacks.onProvisioningFailed(unprovisionedMeshNode, ProvisioningState.States.PROVISIONING_FAILED, data);+ }+ }+ }++ /**+ * Initializes a mesh node object to be provisioned+ *+ * @param uuid Device UUID of unprovisioned node+ * @param networkKey Network key+ * @param flags Flag containing the key refresh or the iv update operations+ * @param ivIndex 32-bit value shared across the network+ * @param globalTtl Global ttl which is also the number of hops to be used for a message+ * @return MeshModel to be provisioned+ */+ private UnprovisionedMeshNode initializeMeshNode(final UUID uuid,+ final NetworkKey networkKey,+ final int flags,+ final int ivIndex,+ final int globalTtl) throws IllegalArgumentException {+ UnprovisionedMeshNode unprovisionedMeshNode = null;++ if (validateProvisioningDataInput(networkKey, flags, ivIndex)) {+ final byte[] flagBytes = ByteBuffer.allocate(1).put((byte) flags).array();++ byte[] ivIndexBytes = null;+ if (MeshParserUtils.validateIvIndexInput(ivIndex)) {+ ivIndexBytes = ByteBuffer.allocate(4).putInt(ivIndex).array();+ }++ unprovisionedMeshNode = new UnprovisionedMeshNode(uuid);+ unprovisionedMeshNode.setNetworkKey(networkKey.getTxNetworkKey());+ unprovisionedMeshNode.setKeyIndex(networkKey.getKeyIndex());+ unprovisionedMeshNode.setFlags(flagBytes);+ unprovisionedMeshNode.setIvIndex(ivIndexBytes);+ unprovisionedMeshNode.setTtl(globalTtl);+ mUnprovisionedMeshNode = unprovisionedMeshNode;+ }+ return unprovisionedMeshNode;+ }++ private boolean validateProvisioningDataInput(final NetworkKey networkKey,+ final Integer flags, final Integer ivIndex) {+ String error;++ if (networkKey == null) {+ error = "Network key cannot be null or empty!";+ throw new IllegalArgumentException(error);+ }++ if (networkKey.getKey() == null || networkKey.getKey().length != 16) {+ error = "Network key length must be 16 octets!";+ throw new IllegalArgumentException(error);+ }++ if (flags == null) {+ error = "Flags cannot be null!";+ throw new IllegalArgumentException(error);+ }++ if (ivIndex == null) {+ error = "IV Index cannot be null!";+ throw new IllegalArgumentException(error);+ }++ return true;+ }++ /**+ * Identifies the node that is to be provisioned.+ * <p>+ * This method will send a provisioning invite to the connected peripheral. This will help users to identify a particular node before starting the provisioning process.+ * This method must be invoked before calling {@link #startProvisioningNoOOB(UnprovisionedMeshNode)}+ * </p+ *+ * @param uuid Device UUID of unprovisioned node+ * @param networkKey Network key+ * @param flags Flag containing the key refresh or the iv update operations+ * @param ivIndex 32-bit value shared across the network+ * @param globalTtl Global ttl which is also the number of hops to be used for a message+ * @param attentionTimer Attention timer+ */+ void identify(final UUID uuid,+ final NetworkKey networkKey,+ final int flags,+ final int ivIndex,+ final int globalTtl,+ final int attentionTimer) throws IllegalArgumentException {+ confirmationInputs = null;+ this.attentionTimer = (byte) attentionTimer;+ final UnprovisionedMeshNode unprovisionedMeshNode =+ initializeMeshNode(uuid, networkKey, flags, ivIndex, globalTtl);+ sendProvisioningInvite(unprovisionedMeshNode);+ }++ /**+ * Starts provisioning an unprovisioned mesh node using No OOB+ * <p>+ * This method will continue the provisioning process that was started by invoking {@link #identify(UUID, NetworkKey, int, int, int, int)}.+ * </p>+ *+ * @param unprovisionedMeshNode {@link UnprovisionedMeshNode}+ */+ void startProvisioningNoOOB(final UnprovisionedMeshNode unprovisionedMeshNode) throws+ IllegalArgumentException {+ sendProvisioningStart(unprovisionedMeshNode);+ }++ /**+ * Starts provisioning an unprovisioned mesh node using Static OOB+ * <p>+ * This method will continue the provisioning process that was started by invoking {@link #identify(UUID, NetworkKey, int, int, int, int)}.+ * </p>+ *+ * @param unprovisionedMeshNode {@link UnprovisionedMeshNode}+ */+ void startProvisioningWithStaticOOB(+ final UnprovisionedMeshNode unprovisionedMeshNode) throws IllegalArgumentException {+ sendProvisioningStartWithStaticOOB(unprovisionedMeshNode);+ }++ /**+ * Starts provisioning an unprovisioned mesh node using Output OOB+ * <p>+ * This method will continue the provisioning process that was started by invoking {@link #identify(UUID, NetworkKey, int, int, int, int)}.+ * </p>+ *+ * @param unprovisionedMeshNode {@link UnprovisionedMeshNode}+ * @param action Selected {@link OutputOOBAction}+ */+ void startProvisioningWithOutputOOB(+ final UnprovisionedMeshNode unprovisionedMeshNode,+ final OutputOOBAction action) throws IllegalArgumentException {+ sendProvisioningStartWithOutputOOB(unprovisionedMeshNode, action);+ }++ /**+ * Starts provisioning an unprovisioned mesh node using Input OOB+ * <p>+ * This method will continue the provisioning process that was started by invoking {@link #identify(UUID, NetworkKey, int, int, int, int)}.+ * </p>+ *+ * @param unprovisionedMeshNode {@link UnprovisionedMeshNode}+ * @param action Selected {@link InputOOBAction}+ */+ void startProvisioningWithInputOOB(+ final UnprovisionedMeshNode unprovisionedMeshNode,+ final InputOOBAction action) throws IllegalArgumentException {+ sendProvisioningStartWithInputOOB(unprovisionedMeshNode, action);+ }++ private void sendProvisioningInvite(final UnprovisionedMeshNode unprovisionedMeshNode) {+ isProvisioningPublicKeySent = false;+ isProvisioneePublicKeyReceived = false;+ final ProvisioningInviteState invite = new ProvisioningInviteState(unprovisionedMeshNode, attentionTimer, mInternalTransportCallbacks, mStatusCallbacks);+ provisioningState = invite;+ invite.executeSend();+ }++ /**+ * Read provisioning capabilities of node+ *+ * @param capabilities provisioning capabilities of the node+ * @return true if the message is valid+ */+ private boolean parseProvisioningCapabilitiesMessage(+ final UnprovisionedMeshNode unprovisionedMeshNode, final byte[] capabilities) {+ final ProvisioningCapabilitiesState provisioningCapabilitiesState = new ProvisioningCapabilitiesState(unprovisionedMeshNode, mStatusCallbacks);+ provisioningState = provisioningCapabilitiesState;+ return provisioningCapabilitiesState.parseData(capabilities);+ }++ private void sendProvisioningStart(final UnprovisionedMeshNode unprovisionedMeshNode) {+ final ProvisioningCapabilitiesState capabilitiesState = (ProvisioningCapabilitiesState) provisioningState;+ final ProvisioningCapabilities capabilities = capabilitiesState.getCapabilities();+ final ProvisioningStartState startProvisioning = new ProvisioningStartState(unprovisionedMeshNode, mInternalTransportCallbacks, mStatusCallbacks);+ startProvisioning.setProvisioningCapabilities(capabilities.getNumberOfElements(),+ capabilities.getRawAlgorithm(),+ capabilities.getRawPublicKeyType(),+ capabilities.getRawStaticOOBType(),+ capabilities.getOutputOOBSize(),+ capabilities.getRawOutputOOBAction(),+ capabilities.getInputOOBSize(),+ capabilities.getRawInputOOBAction());+ provisioningState = startProvisioning;+ startProvisioning.executeSend();+ }++ private void sendProvisioningStartWithStaticOOB(+ final UnprovisionedMeshNode unprovisionedMeshNode) {+ final ProvisioningCapabilitiesState capabilitiesState = (ProvisioningCapabilitiesState) provisioningState;+ final ProvisioningCapabilities capabilities = capabilitiesState.getCapabilities();++ final ProvisioningStartState startProvisioning = new ProvisioningStartState(unprovisionedMeshNode, mInternalTransportCallbacks, mStatusCallbacks);+ startProvisioning.setProvisioningCapabilities(capabilities.getNumberOfElements(),+ capabilities.getRawAlgorithm(),+ capabilities.getRawPublicKeyType(),+ capabilities.getRawStaticOOBType(),+ capabilities.getOutputOOBSize(),+ capabilities.getRawOutputOOBAction(),+ capabilities.getInputOOBSize(),+ capabilities.getRawInputOOBAction());+ startProvisioning.setUseStaticOOB(StaticOOBType.STATIC_OOB_AVAILABLE);+ provisioningState = startProvisioning;+ startProvisioning.executeSend();+ }++ private void sendProvisioningStartWithOutputOOB(+ final UnprovisionedMeshNode unprovisionedMeshNode, final OutputOOBAction action) {+ final ProvisioningCapabilitiesState capabilitiesState = (ProvisioningCapabilitiesState) provisioningState;+ final ProvisioningCapabilities capabilities = capabilitiesState.getCapabilities();++ final ProvisioningStartState startProvisioning = new ProvisioningStartState(unprovisionedMeshNode, mInternalTransportCallbacks, mStatusCallbacks);+ startProvisioning.setProvisioningCapabilities(capabilities.getNumberOfElements(),+ capabilities.getRawAlgorithm(),+ capabilities.getRawPublicKeyType(),+ capabilities.getRawStaticOOBType(),+ capabilities.getOutputOOBSize(),+ capabilities.getRawOutputOOBAction(),+ capabilities.getInputOOBSize(),+ capabilities.getRawInputOOBAction());+ startProvisioning.setUseOutputOOB(action);+ provisioningState = startProvisioning;+ startProvisioning.executeSend();+ }++ private void sendProvisioningStartWithInputOOB(+ final UnprovisionedMeshNode unprovisionedMeshNode, final InputOOBAction action) {+ final ProvisioningCapabilitiesState capabilitiesState = (ProvisioningCapabilitiesState) provisioningState;+ final ProvisioningCapabilities capabilities = capabilitiesState.getCapabilities();++ final ProvisioningStartState startProvisioning = new ProvisioningStartState(unprovisionedMeshNode, mInternalTransportCallbacks, mStatusCallbacks);+ startProvisioning.setProvisioningCapabilities(capabilities.getNumberOfElements(),+ capabilities.getRawAlgorithm(),+ capabilities.getRawPublicKeyType(),+ capabilities.getRawStaticOOBType(),+ capabilities.getOutputOOBSize(),+ capabilities.getRawOutputOOBAction(),+ capabilities.getInputOOBSize(),+ capabilities.getRawInputOOBAction());+ startProvisioning.setUseInputOOB(action);+ provisioningState = startProvisioning;+ startProvisioning.executeSend();+ }++ private void sendProvisionerPublicKey(final UnprovisionedMeshNode unprovisionedMeshNode) {+ if (!isProvisioningPublicKeySent) {+ if (provisioningState instanceof ProvisioningPublicKeyState) {+ isProvisioningPublicKeySent = true;+ provisioningState.executeSend();+ } else {+ final ProvisioningPublicKeyState provisioningPublicKeyState = new ProvisioningPublicKeyState(unprovisionedMeshNode, mInternalTransportCallbacks, mStatusCallbacks);+ provisioningState = provisioningPublicKeyState;+ isProvisioningPublicKeySent = true;+ provisioningPublicKeyState.executeSend();+ }+ }+ }++ private void parseProvisioneePublicKeyXY(+ final UnprovisionedMeshNode unprovisionedMeshNode, final byte[] data) {+ if (provisioningState instanceof ProvisioningPublicKeyState) {+ final ProvisioningPublicKeyState provisioningPublicKeyState = ((ProvisioningPublicKeyState) provisioningState);+ isProvisioneePublicKeyReceived = provisioningPublicKeyState.parseData(data);+ if (isProvisioningPublicKeySent && isProvisioneePublicKeyReceived) {+ switch (unprovisionedMeshNode.getAuthMethodUsed()) {+ case STATIC_OOB_AUTHENTICATION:+ provisioningState = new ProvisioningConfirmationState(this, unprovisionedMeshNode, mInternalTransportCallbacks, mStatusCallbacks);+ mStatusCallbacks.onProvisioningStateChanged(mUnprovisionedMeshNode, ProvisioningState.States.PROVISIONING_AUTHENTICATION_STATIC_OOB_WAITING, data);+ break;+ case OUTPUT_OOB_AUTHENTICATION:+ provisioningState = new ProvisioningConfirmationState(this, unprovisionedMeshNode, mInternalTransportCallbacks, mStatusCallbacks);+ mStatusCallbacks.onProvisioningStateChanged(mUnprovisionedMeshNode, ProvisioningState.States.PROVISIONING_AUTHENTICATION_OUTPUT_OOB_WAITING, data);+ break;+ case INPUT_OOB_AUTHENTICATION:+ provisioningState = new ProvisioningInputCompleteState(unprovisionedMeshNode, mInternalTransportCallbacks, mStatusCallbacks);+ mStatusCallbacks.onProvisioningStateChanged(mUnprovisionedMeshNode, ProvisioningState.States.PROVISIONING_AUTHENTICATION_INPUT_OOB_WAITING, data);+ break;+ default:+ provisioningState = new ProvisioningConfirmationState(this, unprovisionedMeshNode, mInternalTransportCallbacks, mStatusCallbacks);+ sendProvisioningConfirmation("");+ break;+ }+ }+ }+ }++ /**+ * Sends the provisioning confirmation+ *+ * @param authentication authentication value input by the user this may be nullable depending on the OOB type selected by the user+ */+ void sendProvisioningConfirmation(/* @Nullable */ final String authentication) {+ final ProvisioningConfirmationState provisioningConfirmationState;+ // Check if the current provisioning state, if the user had selected InputOOBAction the state will be ProvisioningInputCompleteState+ if (provisioningState instanceof ProvisioningInputCompleteState) {+ provisioningConfirmationState = new ProvisioningConfirmationState(this, mUnprovisionedMeshNode, mInternalTransportCallbacks, mStatusCallbacks);+ provisioningState = provisioningConfirmationState;+ } else {+ provisioningConfirmationState = (ProvisioningConfirmationState) provisioningState;+ provisioningConfirmationState.setProvisioningAuthentication(authentication);+ }+ provisioningConfirmationState.executeSend();+ }++ private boolean parseProvisioningInputCompleteState(final byte[] data) {+ final ProvisioningInputCompleteState inputCompleteState = (ProvisioningInputCompleteState) provisioningState;+ return inputCompleteState.parseData(data);+ }++ private boolean parseProvisioneeConfirmation(final byte[] data) {+ final ProvisioningConfirmationState provisioningConfirmationState = (ProvisioningConfirmationState) provisioningState;+ return provisioningConfirmationState.parseData(data);+ }++ private void sendRandomConfirmationPDU(final UnprovisionedMeshNode unprovisionedMeshNode) {+ final ProvisioningRandomConfirmationState provisioningRandomConfirmation = new ProvisioningRandomConfirmationState(this, unprovisionedMeshNode, mInternalTransportCallbacks, mStatusCallbacks);+ provisioningState = provisioningRandomConfirmation;+ provisioningRandomConfirmation.executeSend();+ }++ private boolean parseProvisioneeRandom(final byte[] data) {+ final ProvisioningRandomConfirmationState provisioningRandomConfirmation = (ProvisioningRandomConfirmationState) provisioningState;+ return provisioningRandomConfirmation.parseData(data);+ }++ private void sendProvisioningData(final UnprovisionedMeshNode unprovisionedMeshNode) {+ final ProvisioningDataState provisioningDataState = new ProvisioningDataState(this, unprovisionedMeshNode, mInternalTransportCallbacks, mStatusCallbacks);+ provisioningState = provisioningDataState;+ provisioningDataState.executeSend();+ }++ private boolean validateMessage(final byte[] data) {+ final ProvisioningState state = provisioningState;+ return data[1] == state.getState().ordinal();++ }++ /**+ * Generates the confirmation inputs for a provisionee+ *+ * @param provisionerKeyXY xy components of the provisioner public key+ * @param provisioneeKeyXY xy components of the provisionee public key+ */+ public final byte[] generateConfirmationInputs(final byte[] provisionerKeyXY,+ final byte[] provisioneeKeyXY) {+ //invite: 1 bytes, capabilities: 11 bytes, start: 5 bytes, provisionerKey: 64 bytes, deviceKey: 64 bytes+ //Append all the raw data together+ if (confirmationInputs != null) {+ return confirmationInputs;+ }++ //We must remove the first two bytes which is the pdu type and the provisioning pdu type+ final int offset = 2;+ final int inviteLength = mUnprovisionedMeshNode.getProvisioningInvitePdu().length - offset;+ final ByteBuffer inviteBuffer = ByteBuffer.allocate(inviteLength).+ put(mUnprovisionedMeshNode.getProvisioningInvitePdu(), offset, inviteLength);+ final byte[] invite = inviteBuffer.array();++ //We must remove the first two bytes which is the pdu type and the provisioning pdu type+ final int capabilitiesLength = mUnprovisionedMeshNode.getProvisioningCapabilitiesPdu().length - offset;+ final ByteBuffer capabilitiesBuffer = ByteBuffer.allocate(capabilitiesLength)+ .put(mUnprovisionedMeshNode.getProvisioningCapabilitiesPdu(), offset, capabilitiesLength);+ final byte[] capabilities = capabilitiesBuffer.array();++ //We must remove the first two bytes which is the pdu type and the provisioning pdu type+ final int startDataLength = mUnprovisionedMeshNode.getProvisioningStartPdu().length - offset;+ final ByteBuffer startDataBuffer = ByteBuffer.allocate(startDataLength).+ put(mUnprovisionedMeshNode.getProvisioningStartPdu(), offset, startDataLength);+ final byte[] startData = startDataBuffer.array();//get(startData, 2, startDataLength);++ final int length = invite.length ++ capabilities.length ++ startData.length ++ provisionerKeyXY.length ++ provisioneeKeyXY.length;++ final ByteBuffer buffer = ByteBuffer.allocate(length);+ buffer.put(invite);+ buffer.put(capabilities);+ buffer.put(startData);+ buffer.put(provisionerKeyXY);+ buffer.put(provisioneeKeyXY);+ confirmationInputs = buffer.array();+ return confirmationInputs;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshProvisioningStatusCallbacks.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshProvisioningStatusCallbacks.javanew file mode 100644index 000000000..de026291b--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshProvisioningStatusCallbacks.java@@ -0,0 +1,40 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import org.openremote.agent.protocol.bluetooth.mesh.provisionerstates.ProvisioningState;+import org.openremote.agent.protocol.bluetooth.mesh.provisionerstates.UnprovisionedMeshNode;+import org.openremote.agent.protocol.bluetooth.mesh.transport.ProvisionedMeshNode;++/**+ * Callbacks to notify status during the provisioning process+ */+public interface MeshProvisioningStatusCallbacks {++ /**+ * Invoked when the provisioning state changed.+ *+ * @param meshNode {@link UnprovisionedMeshNode} unprovisioned node.+ * @param state {@link ProvisioningState.State} each provisioning state.+ * @param data data that was sent or received during each provisioning state.+ */+ void onProvisioningStateChanged(final UnprovisionedMeshNode meshNode, final ProvisioningState.States state, final byte[] data);++ /**+ * Invoked when the provisioning state changed.+ *+ * @param meshNode {@link UnprovisionedMeshNode} unprovisioned node.+ * @param state {@link ProvisioningState.State} each provisioning state.+ * @param data data that was sent or received during each provisioning state.+ */+ void onProvisioningFailed(final UnprovisionedMeshNode meshNode, final ProvisioningState.States state, final byte[] data);++ /**+ * Invoked when the provisioning state changed.+ *+ * @param meshNode {@link ProvisionedMeshNode} provisioned mesh node.+ * @param state {@link ProvisioningState.State} each provisioning state.+ * @param data data that was sent or received during each provisioning state.+ */+ void onProvisioningCompleted(final ProvisionedMeshNode meshNode, final ProvisioningState.States state, final byte[] data);++}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshStatusCallbacks.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshStatusCallbacks.javanew file mode 100644index 000000000..8641e2372--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/MeshStatusCallbacks.java@@ -0,0 +1,79 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import org.openremote.agent.protocol.bluetooth.mesh.transport.ControlMessage;+import org.openremote.agent.protocol.bluetooth.mesh.transport.MeshMessage;++/**+ * Callbacks to notify the status of the mesh messages+ */+public interface MeshStatusCallbacks {+ /**+ * Notifies if a transaction has failed+ * <p>+ * As of now this is only triggered if the incomplete timer has expired for a given segmented message.+ * The incomplete timer will wait for a minimum of 10 seconds on receiving a segmented message.+ * If all segments are not received during this period, that transaction shall be considered as failed.+ * </p>+ *+ * @param dst Unique dst address of the device+ * @param hasIncompleteTimerExpired Flag that notifies if the incomplete timer had expired+ */+ void onTransactionFailed(final int dst, final boolean hasIncompleteTimerExpired);++ /**+ * Notifies if an unknown pdu was received+ *+ * @param src Address where the message originated from+ * @param accessPayload Access payload of the message+ */+ void onUnknownPduReceived(final int src, final byte[] accessPayload);++ /**+ * Notifies when a block acknowledgement has been processed+ *+ * <p>+ * This callback is invoked after {@link MeshManagerCallbacks#onMeshPduCreated(byte[])} where a mesh pdu is created.+ * </p>+ *+ * @param dst Destination address to which the block ack was sent+ * @param message Control message containing the block acknowledgement+ */+ void onBlockAcknowledgementProcessed(final int dst, final ControlMessage message);++ /**+ * Notifies if a block acknowledgement was received+ *+ * @param src Source address from which the block ack was received+ * @param message Control message containing the block acknowledgement+ */+ void onBlockAcknowledgementReceived(final int src, final ControlMessage message);++ /**+ * Callback to notify the mesh message has been processed to be sent to the bearer+ *+ * <p>+ * This callback is invoked after {@link MeshManagerCallbacks#onMeshPduCreated(byte[])} where+ * a mesh pdu is created and is ready to be sent.+ * </p>+ *+ * @param dst Destination address to be sent+ * @param meshMessage {@link MeshMessage} containing the message that was sent+ */+ void onMeshMessageProcessed(final int dst, final MeshMessage meshMessage);++ /**+ * Callback to notify that a mesh status message was received from the bearer+ *+ * @param src Source address where the message originated from+ * @param meshMessage {@link MeshMessage} containing the message that was received+ */+ void onMeshMessageReceived(final int src, final MeshMessage meshMessage);++ /**+ * Callback to notify if the decryption failed of a received mesh message+ *+ * @param meshLayer Mesh layer name+ * @param errorMessage Error message+ */+ void onMessageDecryptionFailed(final String meshLayer, final String errorMessage);+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/NetworkKey.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/NetworkKey.javanew file mode 100644index 000000000..a118805f1--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/NetworkKey.java@@ -0,0 +1,252 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import org.openremote.agent.protocol.bluetooth.mesh.utils.SecureUtils;++import javax.validation.constraints.NotNull;++/**+ * Wrapper class for network key+ */+public final class NetworkKey extends MeshKey {++ // Key refresh phases+ public static final int NORMAL_OPERATION = 0;+ public static final int KEY_DISTRIBUTION = 1;+ public static final int USING_NEW_KEYS = 2;+ //public static final int REVOKING_OLD_KEYS = 3; This phase is instantaneous.++ // Transitions+ public static final int USE_NEW_KEYS = 2; //Normal operation+ public static final int REVOKE_OLD_KEYS = 3; //Key Distribution++ private int phase = NORMAL_OPERATION;++ private boolean minSecurity;++ private long timestamp;++ private byte[] identityKey;++ private byte[] oldIdentityKey;++ private SecureUtils.K2Output derivatives;++ private SecureUtils.K2Output oldDerivatives;++ /**+ * Constructs a NetworkKey object with a given key index and network key+ *+ * @param keyIndex 12-bit network key index+ * @param key 16-byte network key+ */+ public NetworkKey(final int keyIndex, @NotNull final byte[] key) {+ super(keyIndex, key);+ name = "Network Key " + (keyIndex + 1);+ identityKey = SecureUtils.calculateIdentityKey(key);+ derivatives = SecureUtils.calculateK2(key, SecureUtils.K2_MASTER_INPUT);+ timestamp = System.currentTimeMillis();+ }++ /**+ * Returns the key refresh phase of the network key+ *+ * @return int phase+ */+ public int getPhase() {+ return phase;+ }++ public void setPhase(final int phase) {+ this.phase = phase;+ }++ @Override+ public void setKey(@NotNull final byte[] key) {+ super.setKey(key);+ identityKey = SecureUtils.calculateIdentityKey(key);+ derivatives = SecureUtils.calculateK2(key, SecureUtils.K2_MASTER_INPUT);+ }++ @Override+ public void setOldKey(final byte[] oldKey) {+ super.setOldKey(oldKey);+ oldIdentityKey = SecureUtils.calculateIdentityKey(oldKey);+ oldDerivatives = SecureUtils.calculateK2(oldKey, SecureUtils.K2_MASTER_INPUT);+ }++ /**+ * Returns the NetworkKey based on the key refresh procedure phase.+ *+ * @return key+ */+ public byte[] getTxNetworkKey() {+ switch (phase) {+ case KEY_DISTRIBUTION:+ return oldKey;+ case USING_NEW_KEYS:+ default:+ return key;+ }+ }++ /**+ * Returns the NetworkKey based on the key refresh procedure phase.+ *+ * @return key+ */+ public SecureUtils.K2Output getTxDerivatives() {+ switch (phase) {+ case KEY_DISTRIBUTION:+ return oldDerivatives;+ case USING_NEW_KEYS:+ default:+ return derivatives;+ }+ }++ /**+ * Uses min security+ *+ * @return true if minimum security or false otherwise+ */+ public boolean isMinSecurity() {+ return minSecurity;+ }++ /**+ * Sets the minimum security.+ *+ * @param minSecurity true if minimum security or false if insecure.+ */+ public void setMinSecurity(final boolean minSecurity) {+ this.minSecurity = minSecurity;+ }++ /**+ * Returns the identity key derived from the current key+ */+ public byte[] getIdentityKey() {+ return identityKey;+ }++ /**+ * Returns the identity key derived from the Old Key+ */+ public byte[] getOldIdentityKey() {+ return oldIdentityKey;+ }++ /**+ * Returns the timestamp of the phase change+ *+ * @return timestamp+ */+ public long getTimestamp() {+ return timestamp;+ }++ /**+ * Returns the current phase description+ */+ public String getPhaseDescription() {+ switch (phase) {+ default:+ case NORMAL_OPERATION:+ return "Normal Operation";+ case KEY_DISTRIBUTION:+ return "Key Distribution";+ case USING_NEW_KEYS:+ return "Using New Keys";+ }+ }++ /**+ * Set the timestamp when the the phase change happened+ *+ * @param timestamp timestamp+ */+ public void setTimestamp(final long timestamp) {+ this.timestamp = timestamp;+ }++ public NetworkKey clone() throws CloneNotSupportedException {+ return (NetworkKey) super.clone();+ }++ /**+ * Updates the currently used {@link #key} with the newKey and sets the currently used key as the {@link #oldKey}+ *+ * @param newKey New NetworkKey value+ * @return true if successful or false otherwise+ * @throws IllegalArgumentException if a NetworkKey distribution is attempted twice with different key+ * values during a single Key refresh procedure+ */+ protected boolean distributeKey(@NotNull final byte[] newKey) throws IllegalArgumentException {+ if (valid(newKey)) {+ if (phase == 0 || phase == 1) {+ phase = 1;+ timestamp = System.currentTimeMillis();+ return super.distributeKey(newKey);+ } else {+ throw new IllegalArgumentException("A NetworkKey can only be updated once during a Key Refresh Procedure.");+ }+ }+ return false;+ }++ /**+ * Switch to New Key.+ *+ * @return true if successful or false otherwise.+ */+ protected boolean switchToNewKey() {+ if (phase == 1) {+ setPhase(USING_NEW_KEYS);+ timestamp = System.currentTimeMillis();+ return true;+ }+ return false;+ }++ /**+ * Revokes old key by switching the phase to {KEY_DISTRIBUTION or USING_NEW_KEYS}+ *+ * @return true if successful or false otherwise.+ */+ protected boolean revokeOldKey() {+ if (phase == KEY_DISTRIBUTION || phase == USING_NEW_KEYS) {+ phase = NORMAL_OPERATION;+ timestamp = System.currentTimeMillis();+ return true;+ }+ return false;+ }++ protected byte[] getNetworkId() {+ return SecureUtils.calculateK3(key);+ }++ protected byte[] getOldNetworkId() {+ return SecureUtils.calculateK3(oldKey);+ }+++ /**+ * Returns the derivatives from the network key+ *+ * @return {@link SecureUtils.K2Output}+ */+ public SecureUtils.K2Output getDerivatives() {+ return derivatives;+ }++ /**+ * Returns the derivatives from the old network key+ *+ * @return {@link SecureUtils.K2Output}+ */+ public SecureUtils.K2Output getOldDerivatives() {+ return oldDerivatives;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/NetworkKeysConfig.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/NetworkKeysConfig.javanew file mode 100644index 000000000..cc3c9a9b6--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/NetworkKeysConfig.java@@ -0,0 +1,53 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import java.util.List;++/**+ * Contains the configuration required when exporting a selected number of Network Keys in a mesh network.+ */+public class NetworkKeysConfig extends ExportConfig {++ NetworkKeysConfig(final Builder config) {+ super(config);+ }++ /**+ * Use this class to configure when exporting all the Network Keys.+ */+ public static class ExportAll implements Builder {+ @Override+ public NetworkKeysConfig build() {+ return new NetworkKeysConfig(this);+ }+ }++ /**+ * Use this class to configure when exporting some of the Network Keys in network.+ */+ public static class ExportSome implements Builder {++ private final List<NetworkKey> keys;++ /**+ * Constructs ExportSome to export only a selected number of network keys when exporting a mesh network.+ *+ * @param keys List of Network Keys to export.+ * @throws IllegalArgumentException if the list does not contain at least one network key.+ */+ public ExportSome(final List<NetworkKey> keys) {+ if (keys.isEmpty())+ throw new IllegalArgumentException("Error, at least one Network Key must be selected!");+ this.keys = keys;+ }++ protected List<NetworkKey> getKeys() {+ return keys;+ }++ @Override+ public NetworkKeysConfig build() {+ return new NetworkKeysConfig(this);+ }+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/NodeKey.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/NodeKey.javanew file mode 100644index 000000000..3c8161c78--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/NodeKey.java@@ -0,0 +1,49 @@+package org.openremote.agent.protocol.bluetooth.mesh;++public class NodeKey {+ private final int index;+ private boolean updated;++ /**+ * Constructs a NodeKey+ *+ * @param index Index of the key+ */+ public NodeKey(final int index) {+ this(index, false);+ }++ /**+ * Constructs a NodeKey+ *+ * @param index Index of the key+ * @param updated If the key has been updated+ */+ public NodeKey(final int index, final boolean updated) {+ this.index = index;+ this.updated = updated;+ }++ /**+ * Returns the index of the added key+ */+ public int getIndex() {+ return index;+ }++ /**+ * Returns true if the key has been updated+ */+ public boolean isUpdated() {+ return updated;+ }++ /**+ * Sets the updated state of the network/application key+ *+ * @param updated true if updated and false otherwise+ */+ public void setUpdated(final boolean updated) {+ this.updated = updated;+ }+}\ No newline at end of filediff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/NodesConfig.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/NodesConfig.javanew file mode 100644index 000000000..37c858321--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/NodesConfig.java@@ -0,0 +1,69 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import org.openremote.agent.protocol.bluetooth.mesh.transport.ProvisionedMeshNode;++import java.util.List;++/**+ * Contains the configuration required when exporting a selected number of mesh nodes in a mesh network.+ */+public class NodesConfig extends ExportConfig {++ /**+ * Use this class to configure when exporting some of the Nodes with their device keys.+ */+ public static class ExportWithDeviceKey implements Builder {+ @Override+ public NodesConfig build() {+ return new NodesConfig(this);+ }+ }++ /**+ * Use this class to configure when exporting some of the Nodes without their device keys.+ */+ public static class ExportWithoutDeviceKey implements Builder {+ @Override+ public NodesConfig build() {+ return new NodesConfig(this);+ }+ }++ /**+ * Use this class to configure when exporting some of the Nodes.+ */+ public static class ExportSome implements Builder {++ private final List<ProvisionedMeshNode> withDeviceKey;+ private final List<ProvisionedMeshNode> withoutDeviceKey;++ /**+ * Constructs ExportSome to export only a selected number of Nodes when exporting a mesh network.+ *+ * @param withDeviceKey List of nodes to be exported with their device keys.+ * @param withoutDeviceKey List of nodes to be exported without their device keys.+ */+ public ExportSome(final List<ProvisionedMeshNode> withDeviceKey, final List<ProvisionedMeshNode> withoutDeviceKey) {+ this.withDeviceKey = withDeviceKey;+ this.withoutDeviceKey = withoutDeviceKey;+ }++ protected List<ProvisionedMeshNode> getWithDeviceKey() {+ return withDeviceKey;+ }++ protected List<ProvisionedMeshNode> getWithoutDeviceKey() {+ return withoutDeviceKey;+ }++ @Override+ public NodesConfig build() {+ return new NodesConfig(this);+ }+ }++ NodesConfig(final Builder config) {+ super(config);+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/Provisioner.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/Provisioner.javanew file mode 100644index 000000000..e690b99a1--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/Provisioner.java@@ -0,0 +1,342 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import org.openremote.agent.protocol.bluetooth.mesh.transport.ProvisionedMeshNode;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.util.ArrayList;+import java.util.Collections;+import java.util.Comparator;+import java.util.List;+import java.util.Locale;++/**+ * Class definition of a Provisioner of mesh network+ */+public class Provisioner {++ private String meshUuid;++ private String provisionerUuid;++ private String provisionerName = "nRF Mesh Provisioner";++ List<AllocatedUnicastRange> allocatedUnicastRanges = new ArrayList<>();++ List<AllocatedGroupRange> allocatedGroupRanges = new ArrayList<>();++ List<AllocatedSceneRange> allocatedSceneRanges = new ArrayList<>();++ private Integer provisionerAddress = null;++ private int globalTtl = 5;++ private boolean lastSelected;++ private final Comparator<AddressRange> addressRangeComparator = (addressRange1, addressRange2) ->+ Integer.compare(addressRange1.getLowAddress(), addressRange2.getLowAddress());++ private final Comparator<AllocatedSceneRange> sceneRangeComparator = (sceneRange1, sceneRange2) ->+ Integer.compare(sceneRange1.getFirstScene(), sceneRange2.getFirstScene());++ /**+ * Constructs {@link Provisioner}+ */+ public Provisioner(final String provisionerUuid,+ final List<AllocatedUnicastRange> allocatedUnicastRanges,+ final List<AllocatedGroupRange> allocatedGroupRanges,+ final List<AllocatedSceneRange> allocatedSceneRanges,+ final String meshUuid) {++ this.provisionerUuid = provisionerUuid.toUpperCase(Locale.US);+ this.allocatedUnicastRanges = allocatedUnicastRanges;+ this.allocatedGroupRanges = allocatedGroupRanges;+ this.allocatedSceneRanges = allocatedSceneRanges;+ this.meshUuid = meshUuid;+ }+ /**+ * Returns the provisionerUuid of the Mesh network+ *+ * @return String provisionerUuid+ */+ public String getMeshUuid() {+ return meshUuid;+ }++ /**+ * Sets the provisionerUuid of the mesh network to this application key+ *+ * @param uuid mesh network provisionerUuid+ */+ public void setMeshUuid(final String uuid) {+ meshUuid = uuid;+ }++ /**+ * Returns the provisioner name+ *+ * @return name+ */+ public String getProvisionerName() {+ return provisionerName;+ }++ /**+ * Sets a friendly name to a provisioner+ *+ * @param provisionerName friendly name+ */+ public void setProvisionerName(final String provisionerName) throws IllegalArgumentException {+ if (provisionerName == null || provisionerName.length() == 0)+ throw new IllegalArgumentException("Name cannot be empty");+ this.provisionerName = provisionerName;+ }++ /**+ * Returns the provisionerUuid+ *+ * @return UUID+ */+ public String getProvisionerUuid() {+ return provisionerUuid;+ }++ public void setProvisionerUuid(final String provisionerUuid) {+ this.provisionerUuid = provisionerUuid;+ }++ /**+ * Returns {@link AllocatedGroupRange} for this provisioner+ *+ * @return allocated range of group addresses+ */+ public List<AllocatedGroupRange> getAllocatedGroupRanges() {+ return Collections.unmodifiableList(allocatedGroupRanges);+ }++ /**+ * Sets {@link AllocatedGroupRange} for this provisioner+ *+ * @param allocatedGroupRanges allocated range of group addresses+ */+ public void setAllocatedGroupRanges(final List<AllocatedGroupRange> allocatedGroupRanges) {+ this.allocatedGroupRanges = allocatedGroupRanges;+ }++ /**+ * Returns {@link AllocatedUnicastRange} for this provisioner+ *+ * @return allocated range of unicast addresses+ */+ public List<AllocatedUnicastRange> getAllocatedUnicastRanges() {+ return Collections.unmodifiableList(allocatedUnicastRanges);+ }++ /**+ * Sets {@link AllocatedGroupRange} for this provisioner+ *+ * @param allocatedUnicastRanges allocated range of unicast addresses+ */+ public void setAllocatedUnicastRanges(final List<AllocatedUnicastRange> allocatedUnicastRanges) {+ this.allocatedUnicastRanges = allocatedUnicastRanges;+ }++ /**+ * Returns {@link AllocatedSceneRange} for this provisioner+ *+ * @return allocated range of unicast addresses+ */+ public List<AllocatedSceneRange> getAllocatedSceneRanges() {+ return Collections.unmodifiableList(allocatedSceneRanges);+ }++ /**+ * Sets {@link AllocatedSceneRange} for this provisioner+ *+ * @param allocatedSceneRanges allocated range of unicast addresses+ */+ public void setAllocatedSceneRanges(final List<AllocatedSceneRange> allocatedSceneRanges) {+ this.allocatedSceneRanges = allocatedSceneRanges;+ }++ public Integer getProvisionerAddress() {+ return provisionerAddress;+ }++ /**+ * Set provisioner address+ *+ * @param address address of the provisioner+ */+ public void setProvisionerAddress(final Integer address) throws IllegalArgumentException {+ if (address != null && !MeshAddress.isValidUnicastAddress(address)) {+ throw new IllegalArgumentException("Unicast address must range between 0x0001 to 0x7FFF.");+ }+ this.provisionerAddress = address;+ }++ /**+ * Assigns provisioner address+ *+ * @param address address of the provisioner+ */+ public boolean assignProvisionerAddress(final Integer address) throws IllegalArgumentException {+ if (address != null && !MeshAddress.isValidUnicastAddress(address)) {+ throw new IllegalArgumentException("Unicast address must range between 0x0001 to 0x7FFF.");+ }+ if (isAddressWithinAllocatedRange(address)) {+ this.provisionerAddress = address;+ return true;+ } else {+ throw new IllegalArgumentException("Address must be within the allocated address range.");+ }+ }++ public int getGlobalTtl() {+ return globalTtl;+ }++ /**+ * Returns true if the provisioner is allowed to configure the network+ */+ public boolean supportsConfiguration() {+ return provisionerAddress != null;+ }++ /**+ * Set the ttl of the provisioner+ *+ * @param ttl ttl+ * @throws IllegalArgumentException if invalid ttl value is set+ */+ public void setGlobalTtl(final int ttl) throws IllegalArgumentException {+ if (!MeshParserUtils.isValidTtl(ttl))+ throw new IllegalArgumentException("Invalid ttl, ttl must range from 0 - 127");+ this.globalTtl = ttl;+ }++ public boolean isLastSelected() {+ return lastSelected;+ }++ public void setLastSelected(final boolean lastSelected) {+ this.lastSelected = lastSelected;+ }++ /**+ * Add a range to the provisioner+ *+ * @param allocatedRange {@link Range}+ */+ @SuppressWarnings("UnusedReturnValue")+ public boolean addRange(final Range allocatedRange) {+ if (allocatedRange instanceof AllocatedUnicastRange) {+ allocatedUnicastRanges.add((AllocatedUnicastRange) allocatedRange);+ final ArrayList<AllocatedUnicastRange> ranges = new ArrayList<>(allocatedUnicastRanges);+ Collections.sort(ranges, addressRangeComparator);+ allocatedUnicastRanges.clear();+ allocatedUnicastRanges.addAll(Range.mergeUnicastRanges(ranges));+ return true;+ } else if (allocatedRange instanceof AllocatedGroupRange) {+ allocatedGroupRanges.add((AllocatedGroupRange) allocatedRange);+ final ArrayList<AllocatedGroupRange> ranges = new ArrayList<>(allocatedGroupRanges);+ Collections.sort(ranges, addressRangeComparator);+ allocatedGroupRanges.clear();+ allocatedGroupRanges.addAll(Range.mergeGroupRanges(ranges));+ return true;+ } else if (allocatedRange instanceof AllocatedSceneRange) {+ allocatedSceneRanges.add((AllocatedSceneRange) allocatedRange);+ final ArrayList<AllocatedSceneRange> ranges = new ArrayList<>(allocatedSceneRanges);+ Collections.sort(allocatedSceneRanges, sceneRangeComparator);+ allocatedSceneRanges.clear();+ allocatedSceneRanges.addAll(Range.mergeSceneRanges(ranges));+ return true;+ }+ return false;+ }++ /**+ * Add a range to the provisioner+ *+ * @param range {@link Range}+ */+ public boolean removeRange(final Range range) {+ if (range instanceof AllocatedUnicastRange) {+ return allocatedUnicastRanges.remove(range);+ } else if (range instanceof AllocatedGroupRange) {+ return allocatedGroupRanges.remove(range);+ } else if (range instanceof AllocatedSceneRange) {+ return allocatedSceneRanges.remove(range);+ }+ return false;+ }++ /**+ * Checks if a given Unicast Address is within an allocated unicast address range+ *+ * @param address Unicast Address+ * @return true if it is within a range or false otherwise+ * @throws IllegalArgumentException if address is invalid or out of range+ */+ boolean isAddressWithinAllocatedRange(final Integer address) throws IllegalArgumentException {+ if (address == null)+ return true;++ if (!MeshAddress.isValidUnicastAddress(address)) {+ throw new IllegalArgumentException("Unicast address must range from 0x0001 - 0x7FFF");+ }++ for (AllocatedUnicastRange range : allocatedUnicastRanges) {+ if (address >= range.getLowAddress() && address <= range.getHighAddress())+ return true;+ }+ return false;+ }++ public boolean hasOverlappingUnicastRanges(final List<AllocatedUnicastRange> otherRanges) {+ for (AllocatedUnicastRange range : allocatedUnicastRanges) {+ for (AllocatedUnicastRange other : otherRanges) {+ if (range.overlaps(other)) {+ return true;+ }+ }+ }+ return false;+ }++ public boolean hasOverlappingGroupRanges(final List<AllocatedGroupRange> otherRanges) {+ for (AllocatedGroupRange range : allocatedGroupRanges) {+ for (AllocatedGroupRange other : otherRanges) {+ if (range.overlaps(other)) {+ return true;+ }+ }+ }+ return false;+ }++ public boolean hasOverlappingSceneRanges(final List<AllocatedSceneRange> otherRanges) {+ for (AllocatedSceneRange range : allocatedSceneRanges) {+ for (AllocatedSceneRange other : otherRanges) {+ if (range.overlaps(other)) {+ return true;+ }+ }+ }+ return false;+ }++ boolean isNodeAddressInUse(final List<ProvisionedMeshNode> nodes) {+ if (provisionerAddress == null)+ return false;++ for (ProvisionedMeshNode node : nodes) {+ if (!node.getUuid().equalsIgnoreCase(provisionerUuid)) {+ if (node.getUnicastAddress() == provisionerAddress) {+ return true;+ }+ }+ }+ return false;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/ProvisionersConfig.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/ProvisionersConfig.javanew file mode 100644index 000000000..ade46aa99--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/ProvisionersConfig.java@@ -0,0 +1,52 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import java.util.List;++/**+ * Contains the configuration required when exporting a selected number of Provisioners in a mesh network.+ */+public class ProvisionersConfig extends ExportConfig {++ /**+ * Use this class to configure when exporting all the Provisioners.+ */+ public static class ExportAll implements Builder {+ @Override+ public ProvisionersConfig build() {+ return new ProvisionersConfig(this);+ }+ }++ /**+ * Use this class to configure when exporting some of the Provisioners.+ */+ public static class ExportSome implements Builder {++ private final List<Provisioner> provisioners;++ /**+ * Constructs ExportSome to export only a selected number of Provisioners when exporting a mesh network.+ *+ * @param provisioners List of Provisioners to export.+ * @throws IllegalArgumentException if the list does not contain at least one provisioner.+ */+ public ExportSome(final List<Provisioner> provisioners) {+ if (provisioners.isEmpty())+ throw new IllegalArgumentException("Error, at least one Provisioner must be selected!");+ this.provisioners = provisioners;+ }++ protected List<Provisioner> getProvisioners() {+ return provisioners;+ }++ @Override+ public ProvisionersConfig build() {+ return new ProvisionersConfig(this);+ }+ }++ ProvisionersConfig(final Builder config) {+ super(config);+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/Range.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/Range.javanew file mode 100644index 000000000..92d20f06d--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/Range.java@@ -0,0 +1,175 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import java.util.ArrayList;+import java.util.List;++public abstract class Range {++ protected int lowerBound;++ protected int upperBound;++ /**+ * Returns the lower bound of the Range+ */+ public abstract int getLowerBound();++ /**+ * Returns the upper bound of the range+ */+ public abstract int getUpperBound();++ /**+ * Checks if two ranges overlaps+ *+ * @param otherRange other range+ * @return true if overlaps or false otherwise+ */+ public abstract boolean overlaps(final Range otherRange);++ /**+ * Returns the address range as a int+ */+ public abstract int range();++ protected boolean overlaps(final int rLow, final int rHigh, final int oLow, final int oHigh) {+ // Are the ranges are equal+ if (rLow == oLow && rHigh == oHigh) {+ return true;+ }+ // Is the range greater than the other range?+ else if (rLow < oLow && rHigh > oHigh) {+ return true;+ }+ // Is the range within the other range?+ else if (rLow > oLow && rHigh < oHigh) {+ return true;+ }+ // Is the range's lower address lower than the other range's low address+ else if (rLow <= oLow &&+ rHigh >= oLow && rHigh <= oHigh) {+ return true;+ }+ // Is the range's higher address greater than the other range's high address+ else return rHigh >= oHigh &&+ rLow >= oLow && rLow <= oHigh;+ }+++ /**+ * Returns a list of merged unicast ranges+ *+ * @param ranges list of{@link AllocatedUnicastRange} to merge with+ */+ public static List<AllocatedUnicastRange> mergeUnicastRanges(final List<AllocatedUnicastRange> ranges) {+ AllocatedUnicastRange accumulator = new AllocatedUnicastRange();+ final List<AllocatedUnicastRange> result = new ArrayList<>();+ for (AllocatedUnicastRange range : ranges) {+ if (accumulator.getLowAddress() == 0 && accumulator.getHighAddress() == 0) {+ accumulator = range;+ }++ // Is the range already in accumulator's range?+ //noinspection StatementWithEmptyBody+ if (accumulator.getHighAddress() >= range.getHighAddress()) {+ // Do nothing.+ }++ // Does the range start inside the accumulator, or just after the accumulator?+ else if (accumulator.getHighAddress() + 1 >= range.getLowAddress()) {+ accumulator = new AllocatedUnicastRange(accumulator.getLowAddress(), range.getHighAddress());+ }++ // There must have been a gap, the accumulator can be appended to result array.+ else {+ result.add(accumulator);+ // Initialize the new accumulator as the new range.+ accumulator = range;+ }+ }++ // Add the last accumulator if it was set above.+ if (accumulator.getLowAddress() != 0 && accumulator.getHighAddress() != 0) {+ result.add(accumulator);+ }+ return result;+ }++ /**+ * Returns a list of merged group ranges+ *+ * @param ranges list of{@link AllocatedGroupRange} to merge with+ */+ public static List<AllocatedGroupRange> mergeGroupRanges(final List<AllocatedGroupRange> ranges) {+ AllocatedGroupRange accumulator = new AllocatedGroupRange();+ final List<AllocatedGroupRange> results = new ArrayList<>();+ for (AllocatedGroupRange range : ranges) {+ if (accumulator.getLowAddress() == 0 && accumulator.getHighAddress() == 0) {+ accumulator = range;+ }++ // Is the range already in accumulator's range?+ //noinspection StatementWithEmptyBody+ if (accumulator.getHighAddress() >= range.getHighAddress()) {+ // Do nothing.+ }++ // Does the range start inside the accumulator, or just after the accumulator?+ else if (accumulator.getHighAddress() + 1 >= range.getLowAddress()) {+ accumulator = new AllocatedGroupRange(accumulator.getLowAddress(), range.getHighAddress());+ }++ // There must have been a gap, the accumulator can be appended to result array.+ else {+ results.add(accumulator);+ // Initialize the new accumulator as the new range.+ accumulator = range;+ }+ }++ // Add the last accumulator if it was set above.+ if (accumulator.getLowAddress() != 0 && accumulator.getHighAddress() != 0) {+ results.add(accumulator);+ }+ return results;+ }++ /**+ * Returns a list of merged scene ranges+ *+ * @param ranges list of{@link AllocatedSceneRange} to merge with+ */+ public static List<AllocatedSceneRange> mergeSceneRanges(final List<AllocatedSceneRange> ranges) {+ AllocatedSceneRange accumulator = new AllocatedSceneRange();+ final List<AllocatedSceneRange> result = new ArrayList<>();+ for (AllocatedSceneRange range : ranges) {+ if (accumulator.getFirstScene() == 0 && accumulator.getLastScene() == 0) {+ accumulator = range;+ }++ // Is the range already in accumulator's range?+ //noinspection StatementWithEmptyBody+ if (accumulator.getLastScene() >= range.getLastScene()) {+ // Do nothing.+ }++ // Does the range start inside the accumulator, or just after the accumulator?+ else if (accumulator.getLastScene() + 1 >= range.getFirstScene()) {+ accumulator = new AllocatedSceneRange(accumulator.getFirstScene(), range.getLastScene());+ }++ // There must have been a gap, the accumulator can be appended to result array.+ else {+ result.add(accumulator);+ // Initialize the new accumulator as the new range.+ accumulator = range;+ }+ }++ // Add the last accumulator if it was set above.+ if (accumulator.getFirstScene() != 0 && accumulator.getLastScene() != 0) {+ result.add(accumulator);+ }+ return result;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/Scene.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/Scene.javanew file mode 100644index 000000000..3033499b0--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/Scene.java@@ -0,0 +1,110 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import java.util.ArrayList;+import java.util.Collections;+import java.util.List;+import java.util.Locale;++/**+ * Class definitions for creating scenes in a mesh network+ */+public class Scene {+ private final String meshUuid;+ private String name = "nRF Scene";+ protected List<Integer> addresses = new ArrayList<>();+ private int number;++ public Scene(final int number, final String meshUuid) {+ this.number = number;+ this.meshUuid = meshUuid;+ }++ public Scene(final int number, final List<Integer> addresses, final String meshUuid) {+ this.number = number;+ this.addresses.addAll(addresses);+ this.meshUuid = meshUuid;+ }++ public String getMeshUuid() {+ return meshUuid;+ }++ /**+ * Friendly name of the scene+ *+ * @return name+ */+ public String getName() {+ return name;+ }++ /**+ * Sets a friendly name to a scene+ *+ * @param name friendly name+ */+ public void setName(final String name) {+ this.name = name;+ }++ /**+ * Returns the address of the scene+ *+ * @return 2 byte address+ */+ public List<Integer> getAddresses() {+ return Collections.unmodifiableList(addresses);+ }++ /**+ * Sets addresses for this group+ *+ * @param addresses list of addresses+ */+ public void setAddresses(final List<Integer> addresses) {+ this.addresses.clear();+ this.addresses.addAll(addresses);+ }++ public int getNumber() {+ return number;+ }++ public void setNumber(final int number) {+ this.number = number;+ }++ /**+ * Validates the excene number+ *+ * @param sceneNumber Scene number+ * @return true if is a valid or throws an IllegalArgument exception+ */+ public static boolean isValidSceneNumber(final int sceneNumber) {+ if (sceneNumber > 0x0000 && sceneNumber <= 0xFFFF) return true;+ throw new IllegalArgumentException("Scene number must range from 0x0001 to 0xFFFF!");+ }++ /**+ * Formats the scene number in to a 4 character hexadecimal String+ *+ * @param number Scene number+ * @param add0x Sets "0x" as prefix if set to true or false otherwise+ */+ public static String formatSceneNumber(final int number, final boolean add0x) {+ return add0x ?+ "0x" + String.format(Locale.US, "%04X", number) :+ String.format(Locale.US, "%04X", number);+ }++ @Override+ public String toString() {+ return "Scene{" ++ "meshUuid='" + meshUuid + '\'' ++ ", name='" + name + '\'' ++ ", addresses=" + addresses ++ ", number=" + number ++ '}';+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/ScenesConfig.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/ScenesConfig.javanew file mode 100644index 000000000..b7f2284a8--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/ScenesConfig.java@@ -0,0 +1,57 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import java.util.List;++public class ScenesConfig extends ExportConfig {++ /**+ * Use this class to configure all Scenes. Exported scenes will not contain addresses of excluded nodes.+ */+ public static class ExportAll implements Builder {+ @Override+ public ScenesConfig build() {+ return new ScenesConfig(this);+ }+ }++ /**+ * Use this class to configure when exporting the related Scenes, the scenes will not contain addresses of excluded nodes.+ */+ public static class ExportRelated implements Builder {+ @Override+ public ScenesConfig build() {+ return new ScenesConfig(this);+ }+ }++ /**+ * Use this class to configure when exporting some of the Scenes.+ */+ public static class ExportSome implements Builder {++ private final List<Scene> scenes;++ /**+ * Constructs ExportSome to export only a selected number of Scenes when exporting a mesh network.+ * The scenes will not contain addresses of excluded nodes.+ *+ * @param scenes List of Scenes to export.+ */+ public ExportSome(final List<Scene> scenes) {+ this.scenes = scenes;+ }++ protected List<Scene> getScenes() {+ return scenes;+ }++ @Override+ public ScenesConfig build() {+ return new ScenesConfig(this);+ }+ }++ ScenesConfig(final Builder config) {+ super(config);+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/SecureNetworkBeacon.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/SecureNetworkBeacon.javanew file mode 100644index 000000000..65276ffe9--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/SecureNetworkBeacon.java@@ -0,0 +1,180 @@+package org.openremote.agent.protocol.bluetooth.mesh;++import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.nio.ByteBuffer;+import java.util.Calendar;++/**+ * Contains the information related to a secure network beacon.+ */+public class SecureNetworkBeacon extends MeshBeacon {+ public static final int BEACON_DATA_LENGTH = 22;+ private final int flags;+ private boolean isKeyRefreshActive;+ private final byte[] networkId = new byte[8];+ private final IvIndex ivIndex;+ private final byte[] authenticationValue = new byte[8];++ /**+ * Constructs a {@link SecureNetworkBeacon} object+ *+ * @param beaconData beacon data advertised by the mesh beacon+ * @throws IllegalArgumentException if service data provide is invalid+ */+ public SecureNetworkBeacon(final byte[] beaconData) {+ super(beaconData);+ if (beaconData.length != BEACON_DATA_LENGTH)+ throw new IllegalArgumentException("Incorrect Secure Network Beacon length: " + beaconData.length+ + ", expected: " + BEACON_DATA_LENGTH + ". Check MTU and Proxy Protocol segmentation.");++ final ByteBuffer byteBuffer = ByteBuffer.wrap(beaconData);+ byteBuffer.position(1);+ flags = byteBuffer.get();+ isKeyRefreshActive = (flags & 0x01) == 1;+ final boolean isIvUpdateActive = ((flags & 0x02) >> 1) == BaseMeshNetwork.IV_UPDATE_ACTIVE;+ byteBuffer.get(networkId, 0, 8);+ ivIndex = new IvIndex(byteBuffer.getInt(), isIvUpdateActive, Calendar.getInstance());+ byteBuffer.get(authenticationValue, 0, 8);+ }++ @Override+ public String toString() {+ return "SecureNetworkBeacon {" ++ " KeyRefreshActive: " + isKeyRefreshActive ++ ", IV Index: " + ivIndex ++ ", Authentication Value: " + MeshParserUtils.bytesToHex(authenticationValue, true) + "}";+ }++ @Override+ public int getBeaconType() {+ return beaconType;+ }++ /**+ * Returns the flags of the secure network beacon+ */+ public int getFlags() {+ return flags;+ }++ /**+ * Returns true if Key Refresh Procedure is active.+ */+ public boolean isKeyRefreshActive() {+ return isKeyRefreshActive;+ }++ /**+ * Returns the network id of the beacon or the node+ */+ public byte[] getNetworkId() {+ return networkId;+ }++ /**+ * Returns the iv index of the beacon or the node+ */+ public IvIndex getIvIndex() {+ return ivIndex;+ }++ /**+ * Returns the authentication value of the beacon+ */+ public byte[] getAuthenticationValue() {+ return authenticationValue;+ }++ /**+ * This method returns whether the received Secure Network Beacon can override+ * the current IV Index.+ * <p>+ * The following restrictions apply:+ * 1. Normal Operation state must last for at least 96 hours.+ * 2. IV Update In Progress state must take at least 96 hours and may not be longer than 144h.+ * 3. IV Index must not decrease.+ * 4. If received Secure Network Beacon has IV Index greater than current IV Index + 1, the+ * device will go into IV Index Recovery procedure. In this state, the 96h rule does not apply+ * and the IV Index or IV Update Active flag may change before 96 hours.+ * 5. If received Secure Network Beacon has IV Index greater than current IV Index + 42, the+ * beacon should be ignored (unless a setting in MeshNetworkManager is set to disable this rule).+ * 6. The node shall not execute more than one IV Index Recovery within a period of 192 hours.+ * <p>+ * Note: Library versions before 2.2.2 did not store the last IV Index, so the date and IV Recovery+ * flag are optional.+ * <p>+ * - parameters:+ * - target: The IV Index to compare.+ * - date: The date of the most recent transition to the current IV Index.+ * - ivRecoveryActive: True if the IV Recovery procedure was used to restore+ * the IV Index on the previous connection.+ * - ivTestMode: True, if IV Update test mode is enabled; false otherwise.+ * - ivRecoveryOver42Allowed: Whether the IV Index Recovery procedure should be limited+ * to allow maximum increase of IV Index by 42.+ * - returns: True, if the Secure Network beacon can be applied; false otherwise.+ * - since: 2.2.2+ * - seeAlso: Bluetooth Mesh Profile 1.0.1, section 3.10.5.+ */+ protected boolean canOverwrite(final IvIndex ivIndex, final Calendar updatedAt,+ final boolean ivRecoveryActive,+ final boolean isTestMode,+ final boolean ivRecoveryOver42Allowed) {+ // IV Index must increase, or, in case it's equal to the current one,+ // the IV Update Active flag must change from true to false.+ // The new index must not be greater than the current one + 42,+ // unless this rule is disabled.+ if ((this.ivIndex.getIvIndex() > ivIndex.getIvIndex() &&+ (ivRecoveryOver42Allowed || this.ivIndex.getIvIndex() <= ivIndex.getIvIndex() + 42)) ||+ (this.ivIndex.getIvIndex() == ivIndex.getIvIndex() &&+ (ivIndex.isIvUpdateActive() || !this.ivIndex.isIvUpdateActive()))) {++ // Before version 2.2.2 the timestamp was not stored. The initial+ // Secure Network Beacon is assumed to be valid.+ return isMinimumTimeRequirementCompleted(ivIndex, updatedAt, ivRecoveryActive, isTestMode);+ } else {+ return false;+ }+ }++ private boolean isMinimumTimeRequirementCompleted(final IvIndex ivIndex,+ final Calendar updatedAt,+ final boolean isIvRecoveryActive,+ final boolean isTestMode) {+ // Let's define a "state" as a pair of IV and IV Update Active flag.+ // "States" change as follows:+ // 1. IV = X, IVUA = false (Normal Operation)+ // 2. IV = X+1, IVUA = true (Update In Progress)+ // 3. IV = X+1, IVUA = false (Normal Operation)+ // 4. IV = X+2, IVUA = true (Update In Progress)+ // 5. ...++ // Calculate number of states between the state defined by the target+ // IV Index and this Secure Network Beacon.+ int stateDiff = (this.ivIndex.getIvIndex() - ivIndex.getIvIndex()) * 2 - 1+ + (ivIndex.isIvUpdateActive() ? 1 : 0)+ + (this.ivIndex.isIvUpdateActive() ? 0 : 1)+ - (isIvRecoveryActive || isTestMode ? 1 : 0); // this may set stateDiff = -1++ // Each "state" must last for at least 96 hours.+ // Calculate the minimum number of hours that had to pass since last state+ // change for the Secure Network Beacon to be assumed valid.+ // If more has passed, it's also valid, as Normal Operation has no maximum+ // time duration.+ int numberOfHoursRequired = stateDiff * 96;++ // Get the number of hours since the state changed last time.+ final long timeDifference = Calendar.getInstance().getTimeInMillis() - updatedAt.getTimeInMillis();+ final int numberOfHoursSinceDate = (int) (timeDifference / (3600 * 1000));++ // The node shall not execute more than one IV Index Recovery within a+ // period of 192 hours.+ if (isIvRecoveryActive && stateDiff > 1 && numberOfHoursSinceDate < 192) {+ return false;+ }++ return numberOfHoursSinceDate >= numberOfHoursRequired;+ }++}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/SendDataCommand.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/SendDataCommand.javanew file mode 100644index 000000000..247a3f4e9--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/SendDataCommand.java@@ -0,0 +1,29 @@+/*+ * Copyright 2021, 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.bluetooth.mesh;++import com.welie.blessed.BluetoothCommandStatus;+import com.welie.blessed.BluetoothGattCharacteristic;+import com.welie.blessed.BluetoothPeripheral;++public interface SendDataCommand {+ boolean sendData();+ void onCharacteristicWrite(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status);+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/SendMultiDataSegmentCommand.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/SendMultiDataSegmentCommand.javanew file mode 100644index 000000000..383d00a45--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/SendMultiDataSegmentCommand.java@@ -0,0 +1,113 @@+/*+ * Copyright 2021, 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.bluetooth.mesh;++import com.welie.blessed.BluetoothCommandStatus;+import com.welie.blessed.BluetoothGattCharacteristic;+import com.welie.blessed.BluetoothPeripheral;+import org.openremote.model.syslog.SyslogCategory;++import java.util.ArrayList;+import java.util.List;+import java.util.concurrent.ScheduledExecutorService;+import java.util.logging.Logger;++public class SendMultiDataSegmentCommand implements SendDataCommand {++ public static final Logger LOG = SyslogCategory.getLogger(SyslogCategory.PROTOCOL, SendMultiDataSegmentCommand.class.getName());+++ // Private Instance Fields ----------------------------------------------------------------++ private final BluetoothMeshProxy meshProxy;+ private final MainThreadManager commandSerializer;+ private final BluetoothGattCharacteristic dataInCharacteristic;+ private final BluetoothMeshProxySendDataCallback callback;+ private final byte[] data;+ private final ScheduledExecutorService executorService;+ private final List<SendSingleDataSegmentCommand> commands;++ private volatile SendSingleDataSegmentCommand currentCommand;++ // Constructors ---------------------------------------------------------------------------++ public SendMultiDataSegmentCommand(BluetoothMeshProxy proxy, MainThreadManager commandSerializer, int mtuSize, ScheduledExecutorService executorService, BluetoothGattCharacteristic characteristic, byte[] data, BluetoothMeshProxySendDataCallback callback) {+ this.meshProxy = proxy;+ this.commandSerializer = commandSerializer;+ this.dataInCharacteristic = characteristic;+ this.callback = callback;+ this.executorService = executorService;+ this.data = data;+ this.commands = createCommands(mtuSize, executorService, characteristic, data, callback);+ }+++ // Public Instance Methods ----------------------------------------------------------------++ public boolean sendData() {+ boolean isSuccess = true;+ for (SendSingleDataSegmentCommand curCommand : commands) {+ setCurrentCommand(curCommand);+ // Note: sendData is blocking+ if (!curCommand.sendData()) {+ isSuccess = false;+ break;+ }+ }+ if (callback != null) {+ final boolean callbackResult = isSuccess;+ executorService.execute(() -> callback.onDataSent(meshProxy, data, callbackResult));+ }++ return isSuccess;+ }+++ // Implements BluetoothPeripheralCallback -------------------------------------------------++ @Override+ public synchronized void onCharacteristicWrite(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {+ if (currentCommand != null) {+ currentCommand.onCharacteristicWrite(peripheral, value, characteristic, status);+ }+ }+++ // Private Instance Methods ---------------------------------------------------------------++ private List<SendSingleDataSegmentCommand> createCommands(int mtuSize, ScheduledExecutorService executorService, BluetoothGattCharacteristic characteristic, byte[] data, BluetoothMeshProxySendDataCallback callback) {+ int numOfSegments = (data.length / mtuSize) + ((data.length % mtuSize) > 0 ? 1 : 0);+ List<SendSingleDataSegmentCommand> commandList = new ArrayList<>(numOfSegments);++ for (int i = 0; i < numOfSegments; i++) {+ int length = Math.min(data.length - mtuSize * i, mtuSize);+ byte[] segmentData = new byte[length];+ System.arraycopy(data, mtuSize * i, segmentData, 0, length);+ SendSingleDataSegmentCommand cmd = new SendSingleDataSegmentCommand(meshProxy, commandSerializer, executorService, characteristic, segmentData, /* callback */null);+ commandList.add(cmd);+ }++ return commandList;+ }++ private synchronized void setCurrentCommand(SendSingleDataSegmentCommand command) {+ this.currentCommand = command;+ }+}\ No newline at end of filediff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/SendSingleDataSegmentCommand.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/SendSingleDataSegmentCommand.javanew file mode 100644index 000000000..cd828a0af--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/SendSingleDataSegmentCommand.java@@ -0,0 +1,134 @@+/*+ * Copyright 2021, 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.bluetooth.mesh;++import com.welie.blessed.BluetoothCommandStatus;+import com.welie.blessed.BluetoothGattCharacteristic;+import com.welie.blessed.BluetoothPeripheral;+import org.openremote.model.syslog.SyslogCategory;++import java.util.concurrent.ArrayBlockingQueue;+import java.util.concurrent.BlockingQueue;+import java.util.concurrent.ScheduledExecutorService;+import java.util.concurrent.TimeUnit;+import java.util.logging.Logger;++public class SendSingleDataSegmentCommand implements SendDataCommand {++ public static final Logger LOG = SyslogCategory.getLogger(SyslogCategory.PROTOCOL, SendSingleDataSegmentCommand.class.getName());+++ // Private Instance Fields ----------------------------------------------------------------++ private final BluetoothGattCharacteristic dataInCharacteristic;+ protected final BluetoothMeshProxySendDataCallback callback;+ private final byte[] data;+ protected final ScheduledExecutorService executorService;+ private final BluetoothMeshProxy meshProxy;+ private final MainThreadManager commandSerializer;+ private volatile boolean isWaitForCallback = false;+ private final BlockingQueue<BluetoothCommandStatus> resultQueue = new ArrayBlockingQueue<>(1);+++ // Constructors ---------------------------------------------------------------------------++ public SendSingleDataSegmentCommand(BluetoothMeshProxy proxy, MainThreadManager commandSerializer, ScheduledExecutorService executorService, BluetoothGattCharacteristic characteristic, byte[] data, BluetoothMeshProxySendDataCallback callback) {+ this.meshProxy = proxy;+ this.commandSerializer = commandSerializer;+ this.executorService = executorService;+ this.dataInCharacteristic = characteristic;+ this.data = data;+ this.callback = callback;+ }+++ // Public Instance Methods ----------------------------------------------------------------++ public boolean sendData() {+ boolean isSuccess = false;+ if (isWaitForCallback) {+ return false;+ }+ isWaitForCallback = true;++ LOG.info("Sending '" + data.length + "' bytes to mesh proxy: [data=" + dataAsHexString(data) + "]");++ Runnable runnable = () -> this.dataInCharacteristic.getService().getPeripheral().writeCharacteristic(+ this.dataInCharacteristic, data, BluetoothGattCharacteristic.WriteType.WITHOUT_RESPONSE+ );+ commandSerializer.enqueue(runnable);+ try {+ // TODO: timeout constant+ BluetoothCommandStatus status = resultQueue.poll(5000, TimeUnit.MILLISECONDS);+ if (status != null) {+ isSuccess = (status == BluetoothCommandStatus.COMMAND_SUCCESS);+ if (isSuccess) {+ LOG.info("Successfully sent '" + data.length + "' bytes to mesh proxy: [data=" + dataAsHexString(data) + "]");+ } else {+ LOG.warning("Failed to send '" + data.length + "' bytes to mesh proxy: [data=" + dataAsHexString(data) + ", status=" + status + "]");+ }+ } else {+ // Callback timeout+ LOG.severe("Failed to send '" + data.length + "' bytes to mesh proxy [data=" + dataAsHexString(data) + "] because of confirmation timeout");+ isSuccess = false;+ }+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ return false;+ }+ if (callback != null) {+ final boolean callbackResult = isSuccess;+ executorService.execute(() -> callback.onDataSent(meshProxy, data, callbackResult));+ }+ return isSuccess;+ }+++ // Implements BluetoothPeripheralCallback -------------------------------------------------++ @Override+ public void onCharacteristicWrite(BluetoothPeripheral peripheral, byte[] value, BluetoothGattCharacteristic characteristic, BluetoothCommandStatus status) {+ if (dataInCharacteristic.getService().getPeripheral().getAddress().equals(peripheral.getAddress()) &&+ dataInCharacteristic.getService().getUuid().equals(characteristic.getService().getUuid()) &&+ dataInCharacteristic.getUuid().equals(characteristic.getUuid())) {+ if (resultQueue.isEmpty()) {+ try {+ resultQueue.put(status);+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ }+ }+ }+ }+++ // Private Instance Methods -------------------------------------------------------------------++ private String dataAsHexString(byte[] data) {+ if (data == null) {+ return "";+ }+ StringBuilder builder = new StringBuilder();+ for (int i = 0; i < data.length; i++) {+ builder.append(String.format("0x%02X%s", data[i] & 0xFF, i == (data.length - 1) ? "" : ", "));+ }+ return builder.toString();+ }+}\ No newline at end of filediff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/SequenceNumberPersistencyManager.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/SequenceNumberPersistencyManager.javanew file mode 100644index 000000000..e6aa3ce59--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/SequenceNumberPersistencyManager.java@@ -0,0 +1,176 @@+/*+ * Copyright 2021, 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.bluetooth.mesh;++import org.jdom.Document;+import org.jdom.Element;+import org.jdom.JDOMException;+import org.jdom.input.SAXBuilder;+import org.jdom.output.Format;+import org.jdom.output.XMLOutputter;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;+import org.openremote.model.syslog.SyslogCategory;++import java.io.File;+import java.io.FileWriter;+import java.io.IOException;+import java.net.URI;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.logging.Logger;++public class SequenceNumberPersistencyManager {++ public static final Logger LOG = SyslogCategory.getLogger(SyslogCategory.PROTOCOL, SequenceNumberPersistencyManager.class.getName());++ public static String XML_TAG_SEQUENCE_NUMBER_LIST = "SequenceNumbers";+ public static String XML_TAG_SEQUENCE_NUMBER_ITEM = "SequenceNumberItem";+ public static String XML_TAG_NETWORK_KEY = "NetworkKey";+ public static String XML_TAG_ADDRESS = "UnicastAddress";+ public static String XML_TAG_SEQUENCE_NUMBER = "SequenceNumber";++ private final Map<String, Map<String, Integer>> map = new HashMap<>();+ private final URI filePath = new File("/btmesh/sequencenumber.xml").toURI();++ public synchronized void save(NetworkKey networkKey, int unicastAddress, int sequenceNumber) {+ String key = MeshParserUtils.bytesToHex(networkKey.key, false);+ String address = String.format("%04X", unicastAddress);++ LOG.info("Save sequence number: [sourceAddress=" + address + ", sequenceNumber=" + sequenceNumber + "]");++ if (!map.containsKey(key)) {+ map.put(key, new HashMap<String, Integer>());+ }+ Map<String, Integer> addressToNumberMap = map.get(key);+ addressToNumberMap.put(address, sequenceNumber);++ save();+ }++ public synchronized void save() {+ Document doc = new Document();++ Element root = new Element(XML_TAG_SEQUENCE_NUMBER_LIST);+ doc.addContent(root);++ for (Map.Entry<String, Map<String, Integer>> mapEntry : map.entrySet()) {+ String key = mapEntry.getKey();++ for (Map.Entry<String, Integer> supMapEntry : mapEntry.getValue().entrySet()) {+ String address = supMapEntry.getKey();+ Integer number = supMapEntry.getValue();++ Element itemElement = new Element(XML_TAG_SEQUENCE_NUMBER_ITEM);+ Element keyElement = new Element(XML_TAG_NETWORK_KEY);+ keyElement.setText(key);+ Element addressElement = new Element(XML_TAG_ADDRESS);+ addressElement.setText(address);+ Element numberElement = new Element(XML_TAG_SEQUENCE_NUMBER);+ numberElement.setText(Integer.toString(number));++ itemElement.addContent(keyElement);+ itemElement.addContent(addressElement);+ itemElement.addContent(numberElement);+ root.addContent(itemElement);+ }+ }+ XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());+ FileWriter writer = null;+ File file = null;+ try {+ file = new File(filePath);+ writer = new FileWriter(new File(filePath));+ outputter.output(doc, writer);+ writer.flush();+ } catch (IOException e) {+ LOG.severe("Failed to save sequence number file: '" + file.getPath() + "' because: " + e.getMessage());+ } finally {+ if (writer != null) {+ try {+ writer.close();+ } catch (IOException e) {+ LOG.severe("Failed to close sequence number file: '" + file.getPath() + "' because: " + e.getMessage());+ }+ }+ }+ }++ public synchronized void load() {+ if (!fileExists()) {+ return;+ }+ File file = new File(filePath);+ SAXBuilder builder = new SAXBuilder();+ Document doc = null;+ try {+ doc = builder.build(file);+ } catch (JDOMException e) {+ LOG.severe("Failed to load sequence number file: '" + file.getPath() + "' because: " + e.getMessage());+ e.printStackTrace();+ return;+ } catch (IOException e) {+ LOG.severe("Failed to load sequence number file: '" + file.getPath() + "' because: " + e.getMessage());+ e.printStackTrace();+ return;+ }+ map.clear();+ Element root = doc.getRootElement();+ List<Element> itemElements = root.getChildren(XML_TAG_SEQUENCE_NUMBER_ITEM);+ for (Element itemElement : itemElements) {+ Element keyElement = itemElement.getChild(XML_TAG_NETWORK_KEY);+ Element addressElement = itemElement.getChild(XML_TAG_ADDRESS);+ Element numberElement = itemElement.getChild(XML_TAG_SEQUENCE_NUMBER);+ if (keyElement == null || addressElement == null | numberElement == null) {+ continue;+ }+ String key = keyElement.getText();+ String address = addressElement.getText();+ String number = numberElement.getText();++ if (!map.containsKey(key)) {+ map.put(key, new HashMap<String, Integer>());+ }+ try {+ map.get(key).put(address, Integer.valueOf(number));+ } catch (NumberFormatException e) {+ LOG.severe("Error while loading sequence number file: '" + file.getPath() + "' because: " + e.getMessage());+ e.printStackTrace();+ continue;+ }+ }+ }++ public synchronized Integer getSequenceNumber(NetworkKey networkKey, int unicastAddress) {+ Integer number = null;+ String key = MeshParserUtils.bytesToHex(networkKey.key, false);+ String address = String.format("%04X", unicastAddress);+ if (map.containsKey(key)) {+ number = map.get(key).get(address);+ }+ return number;+ }++ // Private Instance Methods -------------------------------------------------------------------++ private boolean fileExists() {+ return new File(filePath).exists();+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/ShadowGenericOnOffModel.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/ShadowGenericOnOffModel.javanew file mode 100644index 000000000..8387e1a8c--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/ShadowGenericOnOffModel.java@@ -0,0 +1,113 @@+/*+ * Copyright 2021, 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.bluetooth.mesh;++import org.openremote.agent.protocol.bluetooth.mesh.models.SigModelParser;+import org.openremote.agent.protocol.bluetooth.mesh.transport.GenericOnOffGet;+import org.openremote.agent.protocol.bluetooth.mesh.transport.GenericOnOffSetUnacknowledged;+import org.openremote.agent.protocol.bluetooth.mesh.transport.GenericOnOffStatus;+import org.openremote.agent.protocol.bluetooth.mesh.transport.MeshMessage;+import org.openremote.model.syslog.SyslogCategory;++import java.util.Random;+import java.util.concurrent.ScheduledExecutorService;+import java.util.logging.Logger;++import static org.openremote.agent.protocol.bluetooth.mesh.opcodes.ApplicationMessageOpCodes.GENERIC_ON_OFF_STATUS;++public class ShadowGenericOnOffModel extends ShadowMeshModel {++ public static final Logger LOG = SyslogCategory.getLogger(SyslogCategory.PROTOCOL, ShadowGenericOnOffModel.class.getName());++ public ShadowGenericOnOffModel(ScheduledExecutorService executorService, BluetoothMeshNetwork network, ShadowMeshElement element, int appKeyIndex) {+ super(executorService, network, element, appKeyIndex);+ }++ @Override+ public synchronized void onMeshMessageReceived(MeshMessage meshMessage) {+ if (meshMessage.getOpCode() == GENERIC_ON_OFF_STATUS && meshMessage instanceof GenericOnOffStatus) {+ final GenericOnOffStatus status = (GenericOnOffStatus) meshMessage;+ Boolean isOn = status.getPresentState();+ LOG.info("Received model status update: [model=GenericOnOffServer, address=" + element.getAddress() + ", state=" + (isOn ? "ON":"OFF") + "]");+ executeSensorValueConsumers(isOn);+ }+ }++ @Override+ protected MeshMessage createSetMeshMessage(ApplicationKey applicationKey, Object value) {+ MeshMessage meshMessage = null;+ int tid = new Random().nextInt();+ Boolean onOffValue = toBoolean(value);+ if (onOffValue != null) {+ meshMessage = new GenericOnOffSetUnacknowledged(applicationKey, onOffValue, tid);+ }+ return meshMessage;+ }++ @Override+ protected MeshMessage createGetMeshMessage(ApplicationKey applicationKey) {+ return new GenericOnOffGet(applicationKey);+ }++ @Override+ protected String getModelName() {+ return "Generic On Off";+ }++ @Override+ protected int getModelId() {+ return SigModelParser.GENERIC_ON_OFF_SERVER & 0xFFFF;+ }++ private Boolean toBoolean(Object value) {+ if (value == null) {+ return null;+ }+ Boolean onOffValue = null;+ if (value instanceof Boolean) {+ onOffValue = (Boolean)value;+ } else if (value instanceof Integer) {+ onOffValue = ((Integer)value) != 0;+ } else if (value instanceof Double) {+ onOffValue = ((Double)value) != 0;+ } else if (value instanceof String) {+ onOffValue = fromStringToBoolean((String) value);+ }+ return onOffValue;+ }++ private Boolean fromStringToBoolean(String stringValue) {+ if (stringValue == null) {+ return null;+ }+ Boolean boolValue = null;+ stringValue = stringValue.trim();+ if (stringValue.equalsIgnoreCase("false") ||+ stringValue.equalsIgnoreCase("off") ||+ stringValue.equalsIgnoreCase("0")) {+ boolValue = false;+ } else if (stringValue.equalsIgnoreCase("true") ||+ stringValue.equalsIgnoreCase("on") ||+ stringValue.equalsIgnoreCase("1")) {+ boolValue = true;+ }+ return boolValue;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/ShadowMeshElement.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/ShadowMeshElement.javanew file mode 100644index 000000000..0ac43d727--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/ShadowMeshElement.java@@ -0,0 +1,85 @@+/*+ * Copyright 2021, 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.bluetooth.mesh;++import org.openremote.agent.protocol.bluetooth.mesh.models.SigModelParser;+import org.openremote.agent.protocol.bluetooth.mesh.transport.MeshMessage;+import org.openremote.model.syslog.SyslogCategory;++import java.util.ArrayList;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.concurrent.ScheduledExecutorService;+import java.util.logging.Logger;++public class ShadowMeshElement {++ public static final Logger LOG = SyslogCategory.getLogger(SyslogCategory.PROTOCOL, ShadowMeshElement.class.getName());++ private final ScheduledExecutorService executorService;+ private final BluetoothMeshNetwork meshNetwork;+ private final int address;+ private final Map<Integer, ShadowMeshModel> modelMap = new HashMap<>();++ public ShadowMeshElement(ScheduledExecutorService executorService, BluetoothMeshNetwork network, int address) {+ this.executorService = executorService;+ this.meshNetwork = network;+ this.address = address;+ }++ public synchronized void addShadowModel(int modelId, int appKeyIndex) {+ ShadowMeshModel model = modelMap.get(modelId);+ if (model != null) {+ model.setAppKeyIndex(appKeyIndex);+ } else {+ model = createShadowModel(modelId, appKeyIndex);+ if (model != null) {+ modelMap.put(modelId, model);+ }+ }+ }++ public synchronized void onMeshMessageReceived(MeshMessage meshMessage) {+ for (ShadowMeshModel model : modelMap.values()) {+ model.onMeshMessageReceived(meshMessage);+ }+ }++ public synchronized int getAddress() {+ return address;+ }++ public synchronized List<ShadowMeshModel> getMeshModels() {+ return new ArrayList<>(modelMap.values());+ }++ public synchronized ShadowMeshModel searchShadowModel(int modelId) {+ return modelMap.get(modelId);+ }++ private ShadowMeshModel createShadowModel(int modelId, int appKeyIndex) {+ ShadowMeshModel model = null;+ if ((SigModelParser.GENERIC_ON_OFF_SERVER & 0xFFFF) == modelId) {+ model = new ShadowGenericOnOffModel(executorService, meshNetwork, this, appKeyIndex);+ }+ return model;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/ShadowMeshModel.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/ShadowMeshModel.javanew file mode 100644index 000000000..2457fddf5--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/ShadowMeshModel.java@@ -0,0 +1,114 @@+/*+ * Copyright 2021, 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.bluetooth.mesh;++import org.openremote.agent.protocol.bluetooth.mesh.transport.MeshMessage;+import org.openremote.model.syslog.SyslogCategory;++import java.util.ArrayList;+import java.util.List;+import java.util.concurrent.ScheduledExecutorService;+import java.util.function.Consumer;+import java.util.logging.Logger;++public abstract class ShadowMeshModel {++ public static final Logger LOG = SyslogCategory.getLogger(SyslogCategory.PROTOCOL, ShadowMeshModel.class.getName());+++ protected final ShadowMeshElement element;+ protected final BluetoothMeshNetwork meshNetwork;+ protected int appKeyIndex;+ private final List<Consumer<Object>> sensorValueConsumers = new ArrayList<>();+ protected final ScheduledExecutorService executorService;++ public ShadowMeshModel(ScheduledExecutorService executorService, BluetoothMeshNetwork network, ShadowMeshElement element, int appKeyIndex) {+ this.executorService = executorService;+ this.meshNetwork = network;+ this.element = element;+ this.appKeyIndex = appKeyIndex;+ }++ public synchronized void addSensorValueConsumer(Consumer<Object> consumer) {+ if (consumer != null && !sensorValueConsumers.contains(consumer)) {+ sensorValueConsumers.add(consumer);+ }+ }++ public synchronized void removeSensorValueConsumer(Consumer<Object> consumer) {+ if (consumer != null && sensorValueConsumers.contains(consumer)) {+ sensorValueConsumers.remove(consumer);+ }+ }++ public synchronized void setAppKeyIndex(int appKeyIndex) {+ this.appKeyIndex = appKeyIndex;+ }++ public synchronized void sendSetCommand(Object value) {+ ApplicationKey key = meshNetwork.getApplicationKey(appKeyIndex);+ if (key != null) {+ MeshMessage meshMessage = createSetMeshMessage(key, value);+ if (meshMessage != null) {+ meshNetwork.getMeshManagerApi().createMeshPdu(element.getAddress(), meshMessage);+ }+ } else {+ LOG.severe(+ "Failed to send mesh model '" + getModelName() + "' command value '" + value ++ "' because couldn't find application key for index '" + appKeyIndex + "', address: '" + element.getAddress()+ );+ }+ }++ public synchronized void sendGetCommand() {+ ApplicationKey key = meshNetwork.getApplicationKey(appKeyIndex);+ if (key != null) {+ MeshMessage meshMessage = createGetMeshMessage(key);+ if (meshMessage != null) {+ meshNetwork.getMeshManagerApi().createMeshPdu(element.getAddress(), meshMessage);+ } else {+ LOG.severe(+ "Failed to send mesh model '" + getModelName() + "' get status command " ++ "because couldn't find application key for index '" + appKeyIndex + "'"+ );+ }+ }+ }++ protected void executeSensorValueConsumers(final Object value) {+ executorService.execute(() -> {+ synchronized (ShadowMeshModel.this) {+ for (Consumer<Object> consumer : sensorValueConsumers) {+ consumer.accept(value);+ }+ }+ });+ }++ public abstract void onMeshMessageReceived(MeshMessage meshMessage);++ protected abstract MeshMessage createSetMeshMessage(ApplicationKey applicationKey, Object value);++ protected abstract MeshMessage createGetMeshMessage(ApplicationKey applicationKey);++ protected abstract String getModelName();++ protected abstract int getModelId();+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/control/BlockAcknowledgementMessage.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/control/BlockAcknowledgementMessage.javanew file mode 100644index 000000000..9f2f07d1b--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/control/BlockAcknowledgementMessage.java@@ -0,0 +1,106 @@+package org.openremote.agent.protocol.bluetooth.mesh.control;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.ArrayList;+import java.util.logging.Logger;++public class BlockAcknowledgementMessage extends TransportControlMessage {++ public static final Logger LOG = Logger.getLogger(BlockAcknowledgementMessage.class.getName());++ public BlockAcknowledgementMessage(final byte[] acknowledgementPayload) {++ }++ /**+ * Calculates the block acknowledgement payload.+ * <p>+ * This method will set the segO bit to 1+ * </p>+ *+ * @param blockAck block acknowledgement payload to be sent+ * @param segO segment index+ */+ public static Integer calculateBlockAcknowledgement(final Integer blockAck, final int segO) {+ int ack = 0;+ if (blockAck == null) {+ ack |= 1 << segO;+ LOG.info("Block ack value: " + Integer.toString(ack, 16));+ return ack;+ } else {+ ack = blockAck;+ ack |= 1 << segO;+ LOG.info("Block ack value: " + Integer.toString(ack, 16));+ return ack;+ }+ }++ /**+ * Calculates the block acknowledgement payload.+ * <p>+ * This method will set the segO bit to 1+ * </p>+ *+ * @param segN number of segments+ */+ public static int calculateBlockAcknowledgement(final int segN) {+ final int segmentCount = segN + 1;+ int ack = 0;+ for (int i = 0; i < segmentCount; i++) {+ ack |= 1 << i;+ }+ return ack;+ }++ @Override+ public TransportControlMessageState getState() {+ return TransportControlMessageState.LOWER_TRANSPORT_BLOCK_ACKNOWLEDGEMENT;+ }++ /**+ * Parses the block acknowledgement payload+ * <p>+ * This method will iterate though the block acknowledgement to find out which segments needs to be retransmitted.+ * </p>+ *+ * @param blockAcknowledgement acknowledgement payload received+ * @param segmentCount number of segments+ */+ public static ArrayList<Integer> getSegmentsToBeRetransmitted(final byte[] blockAcknowledgement, final int segmentCount) {+ final ArrayList<Integer> retransmitSegments = new ArrayList<>();+ final int blockAck = ByteBuffer.wrap(blockAcknowledgement).order(ByteOrder.BIG_ENDIAN).getInt();+ for (int i = 0; i < segmentCount; i++) {+ int bit = (blockAck >> i) & 1;+ if (bit == 1) {+ LOG.info("Segment " + i + " of " + (segmentCount - 1) + " received by peer");+ } else {+ retransmitSegments.add(i);+ LOG.info("Segment " + i + " of " + (segmentCount - 1) + " not received by peer");+ }+ }+ return retransmitSegments;+ }++ /**+ * Checks if all segments are received based on the segment count+ *+ * @param blockAcknowledgement acknowledgement payload received+ * @param segN number of segments+ */+ public static boolean hasAllSegmentsBeenReceived(final Integer blockAcknowledgement, final int segN) {+ if (blockAcknowledgement == null)+ return false;+ LOG.info("Block ack: " + blockAcknowledgement);+ final int blockAck = blockAcknowledgement;+ int setBitCount = 0;+ for (int i = 0; i < segN; i++) {+ int bit = (blockAck >> i) & 1;+ if (bit == 1) {+ setBitCount++;+ }+ }+ LOG.info("bit count: " + setBitCount);+ return setBitCount == segN + 1; //Since segN is 0 based add 1 as the bit count represents the number of segments+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/control/TransportControlMessage.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/control/TransportControlMessage.javanew file mode 100644index 000000000..8f3377a71--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/control/TransportControlMessage.java@@ -0,0 +1,24 @@+package org.openremote.agent.protocol.bluetooth.mesh.control;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.TransportLayerOpCodes;++public abstract class TransportControlMessage {++ private static final String TAG = TransportControlMessage.class.getSimpleName();++ public abstract TransportControlMessageState getState();++ public enum TransportControlMessageState {+ LOWER_TRANSPORT_BLOCK_ACKNOWLEDGEMENT(TransportLayerOpCodes.SAR_ACK_OPCODE);++ private int state;++ TransportControlMessageState(final int state) {+ this.state = state;+ }++ public int getState() {+ return state;+ }+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/ConfigurationClientModel.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/ConfigurationClientModel.javanew file mode 100644index 000000000..271626b51--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/ConfigurationClientModel.java@@ -0,0 +1,13 @@+package org.openremote.agent.protocol.bluetooth.mesh.models;++public class ConfigurationClientModel extends SigModel {++ public ConfigurationClientModel(final int modelId) {+ super(modelId);+ }++ @Override+ public String getModelName() {+ return "Configuration Client";+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/ConfigurationServerModel.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/ConfigurationServerModel.javanew file mode 100644index 000000000..0fa1a455d--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/ConfigurationServerModel.java@@ -0,0 +1,51 @@+package org.openremote.agent.protocol.bluetooth.mesh.models;++import org.openremote.agent.protocol.bluetooth.mesh.utils.HeartbeatPublication;+import org.openremote.agent.protocol.bluetooth.mesh.utils.HeartbeatSubscription;++public class ConfigurationServerModel extends SigModel {++ private HeartbeatPublication heartbeatPublication = null;+ private HeartbeatSubscription heartbeatSubscription = null;++ public ConfigurationServerModel(final int modelId) {+ super(modelId);+ }++ @Override+ public String getModelName() {+ return "Configuration Server";+ }++ /**+ * Returns the Heartbeat publication.+ */+ public HeartbeatPublication getHeartbeatPublication() {+ return heartbeatPublication;+ }++ /**+ * Sets the Heartbeat publication.+ *+ * @param heartbeatPublication Heartbeat publication.+ */+ public void setHeartbeatPublication(final HeartbeatPublication heartbeatPublication) {+ this.heartbeatPublication = heartbeatPublication;+ }++ /**+ * Returns the Heartbeat subscription.+ */+ public HeartbeatSubscription getHeartbeatSubscription() {+ return heartbeatSubscription;+ }++ /**+ * Sets the Heartbeat subscription.+ *+ * @param heartbeatSubscription Heartbeat subscription.+ */+ public void setHeartbeatSubscription(final HeartbeatSubscription heartbeatSubscription) {+ this.heartbeatSubscription = heartbeatSubscription;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/GenericOnOffClientModel.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/GenericOnOffClientModel.javanew file mode 100644index 000000000..79c18b655--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/GenericOnOffClientModel.java@@ -0,0 +1,13 @@+package org.openremote.agent.protocol.bluetooth.mesh.models;++public class GenericOnOffClientModel extends SigModel {++ public GenericOnOffClientModel(final int modelId) {+ super(modelId);+ }++ @Override+ public String getModelName() {+ return "Generic On Off Client";+ }+}\ No newline at end of filediff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/GenericOnOffServerModel.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/GenericOnOffServerModel.javanew file mode 100644index 000000000..d9e7d50d3--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/GenericOnOffServerModel.java@@ -0,0 +1,13 @@+package org.openremote.agent.protocol.bluetooth.mesh.models;++public class GenericOnOffServerModel extends SigModel {++ public GenericOnOffServerModel(final int modelId) {+ super(modelId);+ }++ @Override+ public String getModelName() {+ return "Generic On Off Server";+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/SceneServer.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/SceneServer.javanew file mode 100644index 000000000..5c51bbfee--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/SceneServer.java@@ -0,0 +1,25 @@+package org.openremote.agent.protocol.bluetooth.mesh.models;++import java.util.Collections;+import java.util.List;++public class SceneServer extends SigModel {++ public SceneServer(final int modelId) {+ super(modelId);+ }++ @Override+ public String getModelName() {+ return "Scene Server";+ }++ public List<Integer> getScenesNumbers() {+ return Collections.unmodifiableList(sceneNumbers);+ }++ public int getCurrentScene() {+ return currentScene;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/SigModel.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/SigModel.javanew file mode 100644index 000000000..4aae238a6--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/SigModel.java@@ -0,0 +1,16 @@+package org.openremote.agent.protocol.bluetooth.mesh.models;++import org.openremote.agent.protocol.bluetooth.mesh.transport.MeshModel;++public abstract class SigModel extends MeshModel {++ SigModel(final int sigModelId) {+ super(sigModelId);+ }++ @Override+ public int getModelId() {+ return mModelId;+ }++}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/SigModelParser.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/SigModelParser.javanew file mode 100644index 000000000..46886ec30--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/SigModelParser.java@@ -0,0 +1,201 @@+package org.openremote.agent.protocol.bluetooth.mesh.models;++public class SigModelParser {+ private static final String TAG = SigModelParser.class.getSimpleName();++ public static final short CONFIGURATION_SERVER = 0x0000;+ public static final short CONFIGURATION_CLIENT = 0x0001;+ private static final short HEALTH_SERVER_MODEL = 0x0002;+ private static final short HEALTH_CLIENT_MODEL = 0x0003;++ public static final short GENERIC_ON_OFF_SERVER = 0x1000;+ public static final short GENERIC_ON_OFF_CLIENT = 0x1001;+ public static final short GENERIC_LEVEL_SERVER = 0x1002;+ public static final short GENERIC_LEVEL_CLIENT = 0x1003;++ private static final short GENERIC_DEFAULT_TRANSITION_TIME_SERVER = 0x1004;+ private static final short GENERIC_DEFAULT_TRANSITION_TIME_CLIENT = 0x1005;+ private static final short GENERIC_POWER_ON_OFF_SERVER = 0x1006;+ private static final short GENERIC_POWER_ON_OFF_SETUP_SERVER = 0x1007;+ private static final short GENERIC_POWER_ON_OFF_CLIENT = 0x1008;+ private static final short GENERIC_POWER_LEVEL_SERVER = 0x1009;+ private static final short GENERIC_POWER_LEVEL_SETUP_SERVER = 0x100A;+ private static final short GENERIC_POWER_LEVEL_CLIENT = 0x100B;+ private static final short GENERIC_BATTERY_SERVER = 0x100C;+ private static final short GENERIC_BATTERY_CLIENT = 0x100D;+ private static final short GENERIC_LOCATION_SERVER = 0x100E;+ private static final short GENERIC_LOCATION_SETUP_SERVER = 0x100F;+ private static final short GENERIC_LOCATION_CLIENT = 0x1010;+ private static final short GENERIC_ADMIN_PROPERTY_SERVER = 0x1011;+ private static final short GENERIC_MANUFACTURER_PROPERTY_SERVER = 0x1012;+ private static final short GENERIC_USER_PROPERTY_SERVER = 0x1013;+ private static final short GENERIC_CLIENT_PROPERTY_SERVER = 0x1014;+ private static final short GENERIC_PROPERTY_CLIENT = 0x1015;++ // SIG Sensors, Mesh Model Spec+ private static final short SENSOR_SERVER = 0x1100;+ private static final short SENSOR_SETUP_SERVER = 0x1101;+ private static final short SENSOR_CLIENT = 0x1102;++ //SIG Time and Scene, Mesh Model Spec;+ private static final short TIME_SERVER = 0x1200;+ private static final short TIME_SETUP_SERVER = 0x1201;+ private static final short TIME_CLIENT = 0x1202;+ public static final short SCENE_SERVER = 0x1203;+ public static final short SCENE_SETUP_SERVER = 0x1204;+ private static final short SCENE_CLIENT = 0x1205;+ private static final short SCHEDULER_SERVER = 0x1206;+ private static final short SCHEDULER_SETUP_SERVER = 0x1207;+ private static final short SCHEDULER_CLIENT = 0x1208;++ // SIG Lightning, Mesh Model Spec+ private static final short LIGHT_LIGHTNESS_SERVER = 0x1300;+ private static final short LIGHT_LIGHTNESS_SETUP_SERVER = 0x1301;+ private static final short LIGHT_LIGHTNESS_CLIENT = 0x1302;+ private static final short LIGHT_CTL_SERVER = 0x1303;+ private static final short LIGHT_CTL_SETUP_SERVER = 0x1304;+ private static final short LIGHT_CTL_CLIENT = 0x1305;+ private static final short LIGHT_CTL_TEMPERATURE_SERVER = 0x1306;+ private static final short LIGHT_HSL_SERVER = 0x1307;+ private static final short LIGHT_HSL_SETUP_SERVER = 0x1308;+ private static final short LIGHT_HSL_CLIENT = 0x1309;+ private static final short LIGHT_HSL_HUE_SERVER = 0x130A;+ private static final short LIGHT_HSL_SATURATION_SERVER = 0x130B;+ private static final short LIGHT_XYL_SERVER = 0x130C;+ private static final short LIGHT_XYL_SETUP_SERVER = 0x130D;+ private static final short LIGHT_XYL_CLIENT = 0x130E;+ private static final short LIGHT_LC_SERVER = 0x130F;+ private static final short LIGHT_LC_SETUP_SERVER = 0x1310;+ private static final short LIGHT_LC_CLIENT = 0x1311;++ /**+ * Returns the Bluetooth sig model based on the model id.+ *+ * @param modelId bluetooth sig model id+ * @return SigModel+ */+ public static SigModel getSigModel(final int modelId) {+ switch (modelId) {++ case CONFIGURATION_SERVER:+ return new ConfigurationServerModel(modelId);+ case CONFIGURATION_CLIENT:+ return new ConfigurationClientModel(modelId);+ /*+ case HEALTH_SERVER_MODEL:+ return new HealthServerModel(modelId);+ case HEALTH_CLIENT_MODEL:+ return new HealthClientModel(modelId);+ */+ case GENERIC_ON_OFF_SERVER:+ return new GenericOnOffServerModel(modelId);+ case GENERIC_ON_OFF_CLIENT:+ return new GenericOnOffClientModel(modelId);+ /*+ case GENERIC_LEVEL_SERVER:+ return new GenericLevelServerModel(modelId);+ case GENERIC_LEVEL_CLIENT:+ return new GenericLevelClientModel(modelId);+ case GENERIC_DEFAULT_TRANSITION_TIME_SERVER:+ return new GenericDefaultTransitionTimeServer(modelId);+ case GENERIC_DEFAULT_TRANSITION_TIME_CLIENT:+ return new GenericDefaultTransitionTimeClient(modelId);+ case GENERIC_POWER_ON_OFF_SERVER:+ return new GenericPowerOnOffServer(modelId);+ case GENERIC_POWER_ON_OFF_SETUP_SERVER:+ return new GenericPowerOnOffSetupServer(modelId);+ case GENERIC_POWER_ON_OFF_CLIENT:+ return new GenericPowerOnOffClient(modelId);+ case GENERIC_POWER_LEVEL_SERVER:+ return new GenericPowerLevelServer(modelId);+ case GENERIC_POWER_LEVEL_SETUP_SERVER:+ return new GenericPowerLevelSetupServer(modelId);+ case GENERIC_POWER_LEVEL_CLIENT:+ return new GenericPowerLevelClient(modelId);+ case GENERIC_BATTERY_SERVER:+ return new GenericBatteryServer(modelId);+ case GENERIC_BATTERY_CLIENT:+ return new GenericBatteryClient(modelId);+ case GENERIC_LOCATION_SERVER:+ return new GenericLocationServer(modelId);+ case GENERIC_LOCATION_SETUP_SERVER:+ return new GenericLocationSetupServer(modelId);+ case GENERIC_LOCATION_CLIENT:+ return new GenericLocationClient(modelId);+ case GENERIC_ADMIN_PROPERTY_SERVER:+ return new GenericAdminPropertyServer(modelId);+ case GENERIC_MANUFACTURER_PROPERTY_SERVER:+ return new GenericManufacturerPropertyServer(modelId);+ case GENERIC_USER_PROPERTY_SERVER:+ return new GenericUserPropertyServer(modelId);+ case GENERIC_CLIENT_PROPERTY_SERVER:+ return new GenericClientPropertyServer(modelId);+ case GENERIC_PROPERTY_CLIENT:+ return new GenericPropertyClient(modelId);+ case SENSOR_SERVER:+ return new SensorServer(modelId);+ case SENSOR_SETUP_SERVER:+ return new SensorSetupServer(modelId);+ case SENSOR_CLIENT:+ return new SensorClient(modelId);+ case TIME_SERVER:+ return new TimeServer(modelId);+ case TIME_SETUP_SERVER:+ return new TimeSetupServer(modelId);+ case TIME_CLIENT:+ return new TimeClient(modelId);+ case SCENE_SERVER:+ return new SceneServer(modelId);+ case SCENE_SETUP_SERVER:+ return new SceneSetupServer(modelId);+ case SCENE_CLIENT:+ return new SceneClient(modelId);+ case SCHEDULER_SERVER:+ return new SchedulerServer(modelId);+ case SCHEDULER_SETUP_SERVER:+ return new SchedulerSetupServer(modelId);+ case SCHEDULER_CLIENT:+ return new SchedulerClient(modelId);+ case LIGHT_LIGHTNESS_SERVER:+ return new LightLightnessServer(modelId);+ case LIGHT_LIGHTNESS_SETUP_SERVER:+ return new LightLightnessSetupServer(modelId);+ case LIGHT_LIGHTNESS_CLIENT:+ return new LightLightnessClient(modelId);+ case LIGHT_CTL_SERVER:+ return new LightCtlServer(modelId);+ case LIGHT_CTL_SETUP_SERVER:+ return new LightCtlSetupServer(modelId);+ case LIGHT_CTL_CLIENT:+ return new LightCtlClient(modelId);+ case LIGHT_CTL_TEMPERATURE_SERVER:+ return new LightCtlTemperatureServer(modelId);+ case LIGHT_HSL_SERVER:+ return new LightHslServer(modelId);+ case LIGHT_HSL_SETUP_SERVER:+ return new LightHslSetupServer(modelId);+ case LIGHT_HSL_CLIENT:+ return new LightHslClient(modelId);+ case LIGHT_HSL_HUE_SERVER:+ return new LightHslHueServer(modelId);+ case LIGHT_HSL_SATURATION_SERVER:+ return new LightHslSaturationServer(modelId);+ case LIGHT_XYL_SERVER:+ return new LightXylServer(modelId);+ case LIGHT_XYL_SETUP_SERVER:+ return new LightXylSetupServer(modelId);+ case LIGHT_XYL_CLIENT:+ return new LightXylClient(modelId);+ case LIGHT_LC_SERVER:+ return new LightLcServer(modelId);+ case LIGHT_LC_SETUP_SERVER:+ return new LightLcSetupServer(modelId);+ case LIGHT_LC_CLIENT:+ return new LightLcClient(modelId);+ */+ default:+ return new UnknownModel(modelId);+ }+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/UnknownModel.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/UnknownModel.javanew file mode 100644index 000000000..292ffb0cc--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/UnknownModel.java@@ -0,0 +1,13 @@+package org.openremote.agent.protocol.bluetooth.mesh.models;++public class UnknownModel extends SigModel {++ public UnknownModel(final int modelId) {+ super(modelId);+ }++ @Override+ public String getModelName() {+ return "Unknown";+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/VendorModel.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/VendorModel.javanew file mode 100644index 000000000..74c8f7183--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/models/VendorModel.java@@ -0,0 +1,43 @@+package org.openremote.agent.protocol.bluetooth.mesh.models;++import org.openremote.agent.protocol.bluetooth.mesh.transport.MeshModel;+import org.openremote.agent.protocol.bluetooth.mesh.utils.CompanyIdentifiers;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++public class VendorModel extends MeshModel {++ public static final Logger LOG = Logger.getLogger(VendorModel.class.getName());++ private final short companyIdentifier;+ private final String companyName;++ public VendorModel(final int modelIdentifier) {+ super(modelIdentifier);+ final ByteBuffer buffer = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN);+ buffer.putInt(modelIdentifier);+ this.companyIdentifier = buffer.getShort(0);+ this.companyName = CompanyIdentifiers.getCompanyName(companyIdentifier);+ LOG.info("Company name: " + companyName);+ }++ @Override+ public int getModelId() {+ return mModelId;+ }++ @Override+ public String getModelName() {+ return "Vendor Model";+ }++ public int getCompanyIdentifier() {+ return companyIdentifier;+ }++ public String getCompanyName() {+ return companyName;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/opcodes/ApplicationMessageOpCodes.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/opcodes/ApplicationMessageOpCodes.javanew file mode 100644index 000000000..4f49e81e2--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/opcodes/ApplicationMessageOpCodes.java@@ -0,0 +1,156 @@+package org.openremote.agent.protocol.bluetooth.mesh.opcodes;++public class ApplicationMessageOpCodes {++ /**+ * Opcode for the "Generic OnOff Get" message.+ */+ public static final int GENERIC_ON_OFF_GET = 0x8201;++ /**+ * Opcode for the "Generic OnOff Set" message.+ */+ public static final int GENERIC_ON_OFF_SET = 0x8202;++ /**+ * Opcode for the "Generic OnOff Set Unacknowledged" message.+ */+ public static final int GENERIC_ON_OFF_SET_UNACKNOWLEDGED = 0x8203;++ /**+ * Opcode for the "Generic OnOff Status" message.+ */+ public static final int GENERIC_ON_OFF_STATUS = 0x8204;++ /**+ * Opcode for the "Generic Level Get" message.+ */+ public static final int GENERIC_LEVEL_GET = 0x8205;++ /**+ * Opcode for the "Generic Level Set" message.+ */+ public static final int GENERIC_LEVEL_SET = 0x8206;++ /**+ * Opcode for the "Generic Level Set Unacknowledged" message.+ */+ public static final int GENERIC_LEVEL_SET_UNACKNOWLEDGED = 0x8207;++ /**+ * Opcode for the "Generic Level Status" message.+ */+ public static final int GENERIC_LEVEL_STATUS = 0x8208;++ /**+ * Opcode for the "Light Lightness Get" message+ */+ public static final int LIGHT_LIGHTNESS_GET = 0x824B;++ /**+ * Opcode for the "Light Lightness Set" message+ */+ public static final int LIGHT_LIGHTNESS_SET = 0x824C;++ /**+ * Opcode for the "Light Lightness Set Unacknowledged" message+ */+ public static final int LIGHT_LIGHTNESS_SET_UNACKNOWLEDGED = 0x824D;++ /**+ * Opcode for the "Light Lightness Status" message+ */+ public static final int LIGHT_LIGHTNESS_STATUS = 0x824E;++ /**+ * Opcode for the "Light Ctl Get" message+ */+ public static final int LIGHT_CTL_GET = 0x825D;++ /**+ * Opcode for the "Light Ctl Set" message+ */+ public static final int LIGHT_CTL_SET = 0x825E;++ /**+ * Opcode for the "Light Ctl Set Unacknowledged" message+ */+ public static final int LIGHT_CTL_SET_UNACKNOWLEDGED = 0x825F;++ /**+ * Opcode for the "Light Ctl Status" message+ */+ public static final int LIGHT_CTL_STATUS = 0x8260;++ /**+ * Opcode for the "Light Hsl Get" message+ */+ public static final int LIGHT_HSL_GET = 0x826D;++ /**+ * Opcode for the "Light Hsl Set" message+ */+ public static final int LIGHT_HSL_SET = 0x8276;++ /**+ * Opcode for the "Light Hsl Set Unacknowledged" message+ */+ public static final int LIGHT_HSL_SET_UNACKNOWLEDGED = 0x8277;++ /**+ * Opcode for the "Light Hsl Status" message+ */+ public static final int LIGHT_HSL_STATUS = 0x8278;++ /**+ * Opcode for the "Scene Status" message+ */+ public static final int SCENE_STATUS = 0x5E;++ /**+ * Opcode for the "Scene Register Status" message+ */+ public static final int SCENE_REGISTER_STATUS = 0x8245;++ /**+ * Opcode for the "Scene Get" message+ */+ public static final int SCENE_GET = 0x8241;++ /**+ * Opcode for the "Scene Register Get" message+ */+ public static final int SCENE_REGISTER_GET = 0x8244;++ /**+ * Opcode for the "Scene Recall" message+ */+ public static final int SCENE_RECALL = 0x8242;++ /**+ * Opcode for the "Scene Recall Unacknowledged" message+ */+ public static final int SCENE_RECALL_UNACKNOWLEDGED = 0x8243;++ /**+ * Opcode for the "Scene Store" message+ */+ public static final int SCENE_STORE = 0x8246;++ /**+ * Opcode for the "Scene Store Unacknowledged" message+ */+ public static final int SCENE_STORE_UNACKNOWLEDGED = 0x8247;++ /**+ * Opcode for the "Scene Delete" message+ */+ public static final int SCENE_DELETE = 0x829E;++ /**+ * Opcode for the "Scene Delete Unacknowledged" message+ */+ public static final int SCENE_DELETE_UNACKNOWLEDGED = 0x829F;++}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/opcodes/ConfigMessageOpCodes.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/opcodes/ConfigMessageOpCodes.javanew file mode 100644index 000000000..a28bab7e4--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/opcodes/ConfigMessageOpCodes.java@@ -0,0 +1,360 @@+package org.openremote.agent.protocol.bluetooth.mesh.opcodes;++public class ConfigMessageOpCodes {++ /**+ * Opcode for the "ApplicationKey Add" message.+ */+ public static final byte CONFIG_APPKEY_ADD = 0x00;++ /**+ * Opcode for the "ApplicationKey Update" message.+ */+ public static final int CONFIG_APPKEY_UPDATE = 0x01;++ /**+ * Opcode for the "Composition Data Status" message.+ */+ public static final byte CONFIG_COMPOSITION_DATA_STATUS = 0x02;++ /**+ * Opcode for the "Config Model Publication Set" message.+ */+ public static final byte CONFIG_MODEL_PUBLICATION_SET = 0x03;++ /**+ * Opcode for the "Heartbeat Publication Status" message.+ */+ public static final int CONFIG_HEARTBEAT_PUBLICATION_STATUS = 0x06;++ /**+ * Opcode for the "ApplicationKey Delete" message.+ */+ public static final int CONFIG_APPKEY_DELETE = 0x8000;++ /**+ * Opcode for the "ApplicationKey Get" message.+ */+ public static final int CONFIG_APPKEY_GET = 0x8001;++ /**+ * Opcode for the "ApplicationKey List" message.+ */+ public static final int CONFIG_APPKEY_LIST = 0x8002;++ /**+ * Opcode for the "ApplicationKey Status" message.+ */+ public static final int CONFIG_APPKEY_STATUS = 0x8003;++ /**+ * Opcode for the "Composition Data Get" message.+ */+ public static final int CONFIG_COMPOSITION_DATA_GET = 0x8008;++ /**+ * Opcode for the "Config Beacon Get" message.+ */+ public static final int CONFIG_BEACON_GET = 0x8009;++ /**+ * Opcode for the "Config Beacon Set" message.+ */+ public static final int CONFIG_BEACON_SET = 0x800A;++ /**+ * Opcode for the "Config Beacon Status" message.+ */+ public static final int CONFIG_BEACON_STATUS = 0x800B;++ /**+ * Opcode for the "Config Default TTL Get" message.+ */+ public static final int CONFIG_DEFAULT_TTL_GET = 0x800C;++ /**+ * Opcode for the "Config Default TTL Set" message.+ */+ public static final int CONFIG_DEFAULT_TTL_SET = 0x800D;++ /**+ * Opcode for the "Config Default TTL Status" message.+ */+ public static final int CONFIG_DEFAULT_TTL_STATUS = 0x800E;++ /**+ * Opcode for the "Config Friend Get" message.+ */+ public static final int CONFIG_FRIEND_GET = 0x800F;++ /**+ * Opcode for the "Config Friend Set" message.+ */+ public static final int CONFIG_FRIEND_SET = 0x8010;++ /**+ * Opcode for the "Config Friend Status" message.+ */+ public static final int CONFIG_FRIEND_STATUS = 0x8011;++ /**+ * Opcode for the "Config GATT Proxy Get" message.+ */+ public static final int CONFIG_GATT_PROXY_GET = 0x8012;++ /**+ * Opcode for the "Config GATT Proxy Set" message.+ */+ public static final int CONFIG_GATT_PROXY_SET = 0x8013;++ /**+ * Opcode for the "Config GATT Proxy Status" message.+ */+ public static final int CONFIG_GATT_PROXY_STATUS = 0x8014;++ /**+ * Opcode for the "Config Key Refresh Phase Get" message.+ */+ public static final int CONFIG_KEY_REFRESH_PHASE_GET = 0x8015;++ /**+ * Opcode for the "Config Key Refresh Phase Set" message.+ */+ public static final int CONFIG_KEY_REFRESH_PHASE_SET = 0x8016;++ /**+ * Opcode for the "Config Key Refresh Phase Status" message.+ */+ public static final int CONFIG_KEY_REFRESH_PHASE_STATUS = 0x8017;++ /**+ * Opcode for the "Config Model Publication Get" message.+ */+ public static final int CONFIG_MODEL_PUBLICATION_GET = 0x8018;++ /**+ * Opcode for the "Config Model Publication Status" message.+ */+ public static final int CONFIG_MODEL_PUBLICATION_STATUS = 0x8019;++ /**+ * Opcode for the "Config Model Publication Virtual Address Set" message.+ */+ public static final int CONFIG_MODEL_PUBLICATION_VIRTUAL_ADDRESS_SET = 0x801A;++ /**+ * Opcode for the "Config Model Subscription Add" message.+ */+ public static final int CONFIG_MODEL_SUBSCRIPTION_ADD = 0x801B;++ /**+ * Opcode for the "Config Model Subscription Delete" message.+ */+ public static final int CONFIG_MODEL_SUBSCRIPTION_DELETE = 0x801C;++ /**+ * Opcode for the "Config Model Subscription Delete All" message.+ */+ public static final int CONFIG_MODEL_SUBSCRIPTION_DELETE_ALL = 0x801D;++ /**+ * Opcode for the "Config Model Subscription Overwrite" message.+ */+ public static final int CONFIG_MODEL_SUBSCRIPTION_OVERWRITE = 0x801E;++ /**+ * Opcode for the "Config Model Subscription Status" message.+ */+ public static final int CONFIG_MODEL_SUBSCRIPTION_STATUS = 0x801F;++ /**+ * Opcode for the "Config Model Subscription Virtual Address Add" message.+ */+ public static final int CONFIG_MODEL_SUBSCRIPTION_VIRTUAL_ADDRESS_ADD = 0x8020;++ /**+ * Opcode for the "Config Model Subscription Virtual Address Delete" message.+ */+ public static final int CONFIG_MODEL_SUBSCRIPTION_VIRTUAL_ADDRESS_DELETE = 0x8021;++ /**+ * Opcode for the "Config Model Subscription Virtual Address Overwrite" message.+ */+ public static final int CONFIG_MODEL_SUBSCRIPTION_VIRTUAL_ADDRESS_OVERWRITE = 0x8022;++ /**+ * Opcode for the "Config Network Transmit Get" message.+ */+ public static final int CONFIG_NETWORK_TRANSMIT_GET = 0x8023;++ /**+ * Opcode for the "Config Network Transmit Set" message.+ */+ public static final int CONFIG_NETWORK_TRANSMIT_SET = 0x8024;++ /**+ * Opcode for the "Config Network Transmit Status" message.+ */+ public static final int CONFIG_NETWORK_TRANSMIT_STATUS = 0x8025;++ /**+ * Opcode for the "Config Relay Get" message.+ */+ public static final int CONFIG_RELAY_GET = 0x8026;++ /**+ * Opcode for the "Config Relay Set" message.+ */+ public static final int CONFIG_RELAY_SET = 0x8027;++ /**+ * Opcode for the "Config Relay Status" message.+ */+ public static final int CONFIG_RELAY_STATUS = 0x8028;++ /**+ * Opcode for the "Config SIG Model Subscription Get" message.+ */+ public static final int CONFIG_SIG_MODEL_SUBSCRIPTION_GET = 0x8029;++ /**+ * Opcode for the "Config SIG Model Subscription List" message.+ */+ public static final int CONFIG_SIG_MODEL_SUBSCRIPTION_LIST = 0x802A;++ /**+ * Opcode for the "Config Vendor Model Subscription Get" message.+ */+ public static final int CONFIG_VENDOR_MODEL_SUBSCRIPTION_GET = 0x802B;++ /**+ * Opcode for the "Config Vendor Model Subscription List" message.+ */+ public static final int CONFIG_VENDOR_MODEL_SUBSCRIPTION_LIST = 0x802C;++ /**+ * Opcode for the "Config Low Power UnprovisionedMeshNode PollTimeout Get" message.+ */+ public static final int CONFIG_LOW_POWER_NODE_POLLTIMEOUT_GET = 0x802D;++ /**+ * Opcode for the "Config Low Power UnprovisionedMeshNode PollTimeout Status" message.+ */+ public static final int CONFIG_LOW_POWER_NODE_POLLTIMEOUT_STATUS = 0x802E;++ /**+ * Opcode for the "Heartbeat Publication Get" message.+ */+ public static final int CONFIG_HEARTBEAT_PUBLICATION_GET = 0x8038;++ /**+ * Opcode for the "Heartbeat Publication Set" message.+ */+ public static final int CONFIG_HEARTBEAT_PUBLICATION_SET = 0x8039;++ /**+ * Opcode for the "Heartbeat Subscription Get" message.+ */+ public static final int CONFIG_HEARTBEAT_SUBSCRIPTION_GET = 0x803A;++ /**+ * Opcode for the "Heartbeat Subscription Set" message.+ */+ public static final int CONFIG_HEARTBEAT_SUBSCRIPTION_SET = 0x803B;++ /**+ * Opcode for the "Heartbeat Subscription Status" message.+ */+ public static final int CONFIG_HEARTBEAT_SUBSCRIPTION_STATUS = 0x803C;++ /**+ * Opcode for the "Model App Bind" message.+ */+ public static final int CONFIG_MODEL_APP_BIND = 0x803D;++ /**+ * Opcode for the "Model App Status" message.+ */+ public static final int CONFIG_MODEL_APP_STATUS = 0x803E;++ /**+ * Opcode for the "Model App Unbind" message.+ */+ public static final int CONFIG_MODEL_APP_UNBIND = 0x803F;++ /**+ * Opcode for the "NetKey Add" message.+ */+ public static final int CONFIG_NETKEY_ADD = 0x8040;++ /**+ * Opcode for the "NetKey Delete" message.+ */+ public static final int CONFIG_NETKEY_DELETE = 0x8041;++ /**+ * Opcode for the "NetKey Get" message.+ */+ public static final int CONFIG_NETKEY_GET = 0x8042;++ /**+ * Opcode for the "NetKey List" message.+ */+ public static final int CONFIG_NETKEY_LIST = 0x8043;++ /**+ * Opcode for the "NetKey Status" message.+ */+ public static final int CONFIG_NETKEY_STATUS = 0x8044;++ /**+ * Opcode for the "NetKey Update" message.+ */+ public static final int CONFIG_NETKEY_UPDATE = 0x8045;++ /**+ * Opcode for the "UnprovisionedMeshNode Identity Get" message.+ */+ public static final int CONFIG_NODE_IDENTITY_GET = 0x8046;++ /**+ * Opcode for the "UnprovisionedMeshNode Identity Set" message.+ */+ public static final int CONFIG_NODE_IDENTITY_SET = 0x8047;++ /**+ * Opcode for the "UnprovisionedMeshNode Identity Status" message.+ */+ public static final int CONFIG_NODE_IDENTITY_STATUS = 0x8048;++ /**+ * Opcode for the "UnprovisionedMeshNode Reset" message.+ */+ public static final int CONFIG_NODE_RESET = 0x8049;++ /**+ * Opcode for the "UnprovisionedMeshNode Reset Status" message.+ */+ public static final int CONFIG_NODE_RESET_STATUS = 0x804A;++ /**+ * Opcode for the "SIG Model App Get" message.+ */+ public static final int CONFIG_SIG_MODEL_APP_GET = 0x804B;++ /**+ * Opcode for the "SIG Model App List" message.+ */+ public static final int CONFIG_SIG_MODEL_APP_LIST = 0x804C;++ /**+ * Opcode for the "Vendor Model App Get" message.+ */+ public static final int CONFIG_VENDOR_MODEL_APP_GET = 0x804D;++ /**+ * Opcode for the "Vendor Model App List" message.+ */+ public static final int CONFIG_VENDOR_MODEL_APP_LIST = 0x804E;++}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/opcodes/ProxyConfigMessageOpCodes.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/opcodes/ProxyConfigMessageOpCodes.javanew file mode 100644index 000000000..d400bc961--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/opcodes/ProxyConfigMessageOpCodes.java@@ -0,0 +1,25 @@+package org.openremote.agent.protocol.bluetooth.mesh.opcodes;++public class ProxyConfigMessageOpCodes {++ /**+ * Opcode sent by a Proxy Client to set the proxy filter type.+ */+ public static final int SET_FILTER_TYPE = 0x00;++ /**+ * Opcode sent by a Proxy Client to add addresses to the proxy filter list.+ */+ public static final int ADD_ADDRESS = 0x01;++ /**+ * Opcode sent by a Proxy Client to remove addresses from the proxy filter list.+ */+ public static final int REMOVE_ADDRESS = 0x02;++ /**+ * Acknowledgment opcode sent by a Proxy Server to a Proxy Client to report the status of the proxy filter list.+ */+ public static final int FILTER_STATUS = 0x03;++}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/opcodes/TransportLayerOpCodes.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/opcodes/TransportLayerOpCodes.javanew file mode 100644index 000000000..5cbda89f0--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/opcodes/TransportLayerOpCodes.java@@ -0,0 +1,8 @@+package org.openremote.agent.protocol.bluetooth.mesh.opcodes;++public class TransportLayerOpCodes {+ /**+ * Lower transport layer reserved opcode for block acks.+ */+ public static final int SAR_ACK_OPCODE = 0x00;+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningCapabilities.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningCapabilities.javanew file mode 100644index 000000000..782a6d171--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningCapabilities.java@@ -0,0 +1,226 @@+package org.openremote.agent.protocol.bluetooth.mesh.provisionerstates;++import org.openremote.agent.protocol.bluetooth.mesh.utils.AlgorithmType;+import org.openremote.agent.protocol.bluetooth.mesh.utils.AuthenticationOOBMethods;+import org.openremote.agent.protocol.bluetooth.mesh.utils.InputOOBAction;+import org.openremote.agent.protocol.bluetooth.mesh.utils.OutputOOBAction;++import java.util.ArrayList;+import java.util.Collections;+import java.util.List;+import java.util.logging.Logger;++public class ProvisioningCapabilities {+ private static final int PUBLIC_KEY_INFORMATION_AVAILABLE = 0x01;+ private static final int STATIC_OOB_INFO_AVAILABLE = 0x01;+++ private static final Logger LOG = java.util.logging.Logger.getLogger(ProvisioningCapabilities.class.getName());+ private byte numberOfElements;+ private short rawAlgorithm;+ private List<AlgorithmType> supportedAlgorithmTypes;+ private byte rawPublicKeyType;+ private boolean publicKeyInformationAvailable;+ private byte rawStaticOOBType;+ private boolean staticOOBInformationAvailable;+ private byte outputOOBSize;+ private short rawOutputOOBAction;+ private List<OutputOOBAction> supportedOutputOOBActions;+ private byte inputOOBSize;+ private short rawInputOOBAction;+ private List<InputOOBAction> supportedInputOOBActions;+ private AuthenticationOOBMethods supportedOOBMethods;+ private final List<AuthenticationOOBMethods> availableOOBTypes = new ArrayList<>();++ /**+ * Constructs the provisioning capabilities received from a mesh node+ *+ * @param capabilities capabilities pdu+ */+ ProvisioningCapabilities(final byte[] capabilities) {+ if (capabilities[2] == 0) {+ throw new IllegalArgumentException("Number of elements cannot be zero");+ }++ final byte numberOfElements = (capabilities[2]);+ this.numberOfElements = numberOfElements;+ LOG.info("Number of elements: " + numberOfElements);++ final short algorithm = (short) (((capabilities[3] & 0xff) << 8) | (capabilities[4] & 0xff));+ this.rawAlgorithm = algorithm;+ this.supportedAlgorithmTypes = AlgorithmType.getAlgorithmTypeFromBitMask(algorithm);++ this.rawPublicKeyType = capabilities[5];+ this.publicKeyInformationAvailable = rawPublicKeyType == PUBLIC_KEY_INFORMATION_AVAILABLE;+ LOG.info("Public key information available: " + publicKeyInformationAvailable);++ this.rawStaticOOBType = capabilities[6];+ this.staticOOBInformationAvailable = rawStaticOOBType == STATIC_OOB_INFO_AVAILABLE;+ LOG.info("Static OOB information available: : " + staticOOBInformationAvailable);++ final byte outputOOBSize = capabilities[7];+ this.outputOOBSize = outputOOBSize;+ LOG.info("Output OOB size: " + outputOOBSize);++ final short outputOOBAction = (short) (((capabilities[8] & 0xff) << 8) | (capabilities[9] & 0xff));+ this.rawOutputOOBAction = outputOOBAction;+ this.supportedOutputOOBActions = outputOOBSize == 0 ? new ArrayList<>() : OutputOOBAction.parseOutputActionsFromBitMask(outputOOBAction);++ final byte inputOOBSize = capabilities[10];+ this.inputOOBSize = inputOOBSize;+ LOG.info("Input OOB size: " + inputOOBSize);++ final short inputOOBAction = (short) (((capabilities[11] & 0xff) << 8) | (capabilities[12] & 0xff));+ this.rawInputOOBAction = inputOOBAction;+ this.supportedInputOOBActions = inputOOBSize == 0 ? new ArrayList<>() : InputOOBAction.parseInputActionsFromBitMask(inputOOBAction);+ generateAvailableOOBTypes();+ }++ private void generateAvailableOOBTypes() {+ availableOOBTypes.clear();+ availableOOBTypes.add(AuthenticationOOBMethods.NO_OOB_AUTHENTICATION);+ if (isStaticOOBInformationAvailable()) {+ availableOOBTypes.add(AuthenticationOOBMethods.STATIC_OOB_AUTHENTICATION);+ }++ if (!supportedOutputOOBActions.isEmpty()) {+ availableOOBTypes.add(AuthenticationOOBMethods.OUTPUT_OOB_AUTHENTICATION);+ }+ if (!supportedInputOOBActions.isEmpty()) {+ availableOOBTypes.add(AuthenticationOOBMethods.INPUT_OOB_AUTHENTICATION);+ }+ }++ /**+ * Returns the number of elements in the mesh node+ */+ public byte getNumberOfElements() {+ return numberOfElements;+ }++ /**+ * Sets the number of elements in the node+ */+ void setNumberOfElements(final byte numberOfElements) {+ this.numberOfElements = numberOfElements;+ }++ /**+ * Returns the raw supported algorithm value received by the node+ */+ public short getRawAlgorithm() {+ return rawAlgorithm;+ }++ void setRawAlgorithm(final short algorithm) {+ this.rawAlgorithm = algorithm;+ }++ /**+ * Returns a list of algorithm types supported by the node+ */+ public List<AlgorithmType> getSupportedAlgorithmTypes() {+ return Collections.unmodifiableList(supportedAlgorithmTypes);+ }++ /**+ * Returns the raw public key type received by the node+ */+ public byte getRawPublicKeyType() {+ return rawPublicKeyType;+ }++ void setRawPublicKeyType(final byte rawPublicKeyType) {+ this.rawPublicKeyType = rawPublicKeyType;+ }++ /**+ * Returns true if public key information is available+ */+ public boolean isPublicKeyInformationAvailable() {+ return publicKeyInformationAvailable;+ }++ /**+ * Returns the raw static OOB type received by the node+ */+ public byte getRawStaticOOBType() {+ return rawStaticOOBType;+ }++ void setRawStaticOOBType(final byte rawStaticOOBType) {+ this.rawStaticOOBType = rawStaticOOBType;+ }++ /**+ * Returns true if Static OOB information is available+ */+ public boolean isStaticOOBInformationAvailable() {+ return staticOOBInformationAvailable;+ }++ /**+ * Returns the output oob size received by the node. This is the length of+ */+ public byte getOutputOOBSize() {+ return outputOOBSize;+ }++ void setOutputOOBSize(final byte outputOOBSize) {+ this.outputOOBSize = outputOOBSize;+ }++ /**+ * Returns the raw output oob action value received by the node+ */+ public short getRawOutputOOBAction() {+ return rawOutputOOBAction;+ }++ void setRawOutputOOBAction(final short rawOutputOOBAction) {+ this.rawOutputOOBAction = rawOutputOOBAction;+ }++ /**+ * Returns the list of supported {@link OutputOOBAction} actions or an empty list if no oob is supported+ */+ public List<OutputOOBAction> getSupportedOutputOOBActions() {+ return Collections.unmodifiableList(supportedOutputOOBActions);+ }++ public byte getInputOOBSize() {+ return inputOOBSize;+ }++ /**+ * Returns the raw input oob size value received by the node+ */+ void setInputOOBSize(final byte inputOOBSize) {+ this.inputOOBSize = inputOOBSize;+ }++ /**+ * Returns the raw input oob action value received by the node+ */+ public short getRawInputOOBAction() {+ return rawInputOOBAction;+ }++ void setRawInputOOBAction(final short rawInputOOBAction) {+ this.rawInputOOBAction = rawInputOOBAction;+ }++ /**+ * Returns the list of supported {@link InputOOBAction} actions or an empty list if no oob is supported+ */+ public List<InputOOBAction> getSupportedInputOOBActions() {+ return Collections.unmodifiableList(supportedInputOOBActions);+ }++ /**+ * Returns a list of available OOB methods that can be used during provisioning+ */+ public List<AuthenticationOOBMethods> getAvailableOOBTypes() {+ return Collections.unmodifiableList(availableOOBTypes);+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningCapabilitiesState.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningCapabilitiesState.javanew file mode 100644index 000000000..ecc6c5e1f--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningCapabilitiesState.java@@ -0,0 +1,50 @@+package org.openremote.agent.protocol.bluetooth.mesh.provisionerstates;++import org.openremote.agent.protocol.bluetooth.mesh.MeshProvisioningStatusCallbacks;++import java.util.logging.Logger;++public class ProvisioningCapabilitiesState extends ProvisioningState {+ public static final Logger LOG = Logger.getLogger(ProvisioningCapabilitiesState.class.getName());++ private final UnprovisionedMeshNode mUnprovisionedMeshNode;+ private final MeshProvisioningStatusCallbacks mCallbacks;++ private ProvisioningCapabilities capabilities;++ public ProvisioningCapabilitiesState(final UnprovisionedMeshNode unprovisionedMeshNode, final MeshProvisioningStatusCallbacks callbacks) {+ super();+ this.mCallbacks = callbacks;+ this.mUnprovisionedMeshNode = unprovisionedMeshNode;+ }++ @Override+ public State getState() {+ return State.PROVISIONING_CAPABILITIES;+ }++ public ProvisioningCapabilities getCapabilities() {+ return capabilities;+ }++ @Override+ public void executeSend() {++ }++ @Override+ public boolean parseData(final byte[] data) {+ final boolean flag = parseProvisioningCapabilities(data);+ //We store the provisioning capabilities pdu to be used when generating confirmation inputs+ mUnprovisionedMeshNode.setProvisioningCapabilitiesPdu(data);+ mUnprovisionedMeshNode.setProvisioningCapabilities(capabilities);+ mCallbacks.onProvisioningStateChanged(mUnprovisionedMeshNode, States.PROVISIONING_CAPABILITIES, data);+ return flag;+ }++ private boolean parseProvisioningCapabilities(final byte[] provisioningCapabilities) {+ this.capabilities = new ProvisioningCapabilities(provisioningCapabilities);+ return true;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningCompleteState.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningCompleteState.javanew file mode 100644index 000000000..e9cd27231--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningCompleteState.java@@ -0,0 +1,30 @@+package org.openremote.agent.protocol.bluetooth.mesh.provisionerstates;++public class ProvisioningCompleteState extends ProvisioningState {++ private final UnprovisionedMeshNode unprovisionedMeshNode;++ public ProvisioningCompleteState(final UnprovisionedMeshNode unprovisionedMeshNode) {+ super();+ this.unprovisionedMeshNode = unprovisionedMeshNode;+ unprovisionedMeshNode.setIsProvisioned(true);+ unprovisionedMeshNode.setProvisionedTime(System.currentTimeMillis());+ }++ @Override+ public State getState() {+ return State.PROVISIONING_COMPLETE;+ }++ @Override+ public void executeSend() {++ }++ @Override+ public boolean parseData(final byte[] data) {+ return true;+ }++}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningConfirmationState.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningConfirmationState.javanew file mode 100644index 000000000..275b6e31c--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningConfirmationState.java@@ -0,0 +1,130 @@+package org.openremote.agent.protocol.bluetooth.mesh.provisionerstates;++import org.openremote.agent.protocol.bluetooth.mesh.InternalProvisioningCallbacks;+import org.openremote.agent.protocol.bluetooth.mesh.InternalTransportCallbacks;+import org.openremote.agent.protocol.bluetooth.mesh.MeshManagerApi;+import org.openremote.agent.protocol.bluetooth.mesh.MeshProvisioningStatusCallbacks;+import org.openremote.agent.protocol.bluetooth.mesh.utils.InputOOBAction;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;+import org.openremote.agent.protocol.bluetooth.mesh.utils.OutputOOBAction;+import org.openremote.agent.protocol.bluetooth.mesh.utils.SecureUtils;++import java.nio.ByteBuffer;+import java.util.logging.Logger;++public class ProvisioningConfirmationState extends ProvisioningState {++ public static final Logger LOG = Logger.getLogger(ProvisioningConfirmationState.class.getName());+ private static final byte[] NO_OOB_AUTH = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};+ public static final int AUTH_VALUE_LENGTH = 16;+ private final InternalProvisioningCallbacks provisioningCallbacks;+ private final UnprovisionedMeshNode mNode;+ private final MeshProvisioningStatusCallbacks mStatusCallbacks;+ private final InternalTransportCallbacks mInternalTransportCallbacks;+ private String authentication;+ private byte[] authenticationValue;++ public ProvisioningConfirmationState(final InternalProvisioningCallbacks callbacks,+ final UnprovisionedMeshNode node,+ final InternalTransportCallbacks internalTransportCallbacks,+ final MeshProvisioningStatusCallbacks provisioningStatusCallbacks) {+ super();+ this.provisioningCallbacks = callbacks;+ this.mNode = node;+ this.mInternalTransportCallbacks = internalTransportCallbacks;+ this.mStatusCallbacks = provisioningStatusCallbacks;+ }++ /**+ * Sets the provisioning confirmation+ *+ * @param authentication authentication value+ */+ public void setProvisioningAuthentication(final String authentication) {+ this.authentication = authentication;+ }++ @Override+ public State getState() {+ return State.PROVISIONING_CONFIRMATION;+ }++ @Override+ public void executeSend() {++ final byte[] provisioningConfirmationPDU = createProvisioningConfirmation();+ mStatusCallbacks.onProvisioningStateChanged(mNode, States.PROVISIONING_CONFIRMATION_SENT, provisioningConfirmationPDU);+ mInternalTransportCallbacks.sendProvisioningPdu(mNode, provisioningConfirmationPDU);+ }++ @Override+ public boolean parseData(final byte[] data) {+ mStatusCallbacks.onProvisioningStateChanged(mNode, States.PROVISIONING_CONFIRMATION_RECEIVED, data);+ parseProvisioneeConfirmation(data);+ return true;+ }++ private byte[] createProvisioningConfirmation() {++ final byte[] confirmationInputs = provisioningCallbacks.generateConfirmationInputs(mNode.getProvisionerPublicKeyXY(), mNode.getProvisioneePublicKeyXY());+ LOG.info("Confirmation inputs: " + MeshParserUtils.bytesToHex(confirmationInputs, false));++ //Generate a confirmation salt of the confirmation inputs+ final byte[] confirmationSalt = SecureUtils.calculateSalt(confirmationInputs);+ LOG.info("Confirmation salt: " + MeshParserUtils.bytesToHex(confirmationSalt, false));++ final byte[] ecdhSecret = mNode.getSharedECDHSecret();++ //Generate the confirmationKey by calculating the K1 of ECDH, confirmationSalt and ASCII value of "prck".+ final byte[] confirmationKey = SecureUtils.calculateK1(ecdhSecret, confirmationSalt, SecureUtils.PRCK);+ LOG.info("Confirmation key: " + MeshParserUtils.bytesToHex(confirmationKey, false));++ //Generate provisioner random number+ final byte[] provisionerRandom = SecureUtils.generateRandomNumber();+ mNode.setProvisionerRandom(provisionerRandom);+ LOG.info("Provisioner random: " + MeshParserUtils.bytesToHex(provisionerRandom, false));++ //Generate authentication value from the user input authentication+ final byte[] authenticationValue = generateAuthenticationValue();+ mNode.setAuthenticationValue(authenticationValue);+ LOG.info("Authentication value: " + MeshParserUtils.bytesToHex(authenticationValue, false));++ ByteBuffer buffer = ByteBuffer.allocate(provisionerRandom.length + 16);+ buffer.put(provisionerRandom);+ buffer.put(authenticationValue);+ final byte[] confirmationData = buffer.array();++ final byte[] confirmationValue = SecureUtils.calculateCMAC(confirmationData, confirmationKey);++ buffer = ByteBuffer.allocate(confirmationValue.length + 2);+ buffer.put(new byte[]{MeshManagerApi.PDU_TYPE_PROVISIONING, TYPE_PROVISIONING_CONFIRMATION});+ buffer.put(confirmationValue);+ final byte[] provisioningConfirmationPDU = buffer.array();+ LOG.info("Provisioning confirmation: " + MeshParserUtils.bytesToHex(provisioningConfirmationPDU, false));++ return provisioningConfirmationPDU;+ }++ private byte[] generateAuthenticationValue() {+ switch (mNode.authMethodUsed) {+ case NO_OOB_AUTHENTICATION:+ return NO_OOB_AUTH;+ case STATIC_OOB_AUTHENTICATION:+ return MeshParserUtils.toByteArray(authentication);+ case OUTPUT_OOB_AUTHENTICATION:+ final OutputOOBAction action = OutputOOBAction.fromValue(mNode.getAuthActionUsed());+ return OutputOOBAction.generateOutputOOBAuthenticationValue(action, authentication);+ case INPUT_OOB_AUTHENTICATION:+ final InputOOBAction inputOOBAction = InputOOBAction.fromValue(mNode.getAuthActionUsed());+ return InputOOBAction.generateInputOOBAuthenticationValue(inputOOBAction, mNode.getInputAuthentication());+ }+ return null;+ }++ private void parseProvisioneeConfirmation(final byte[] provisioneeConfirmation) {+ final ByteBuffer buffer = ByteBuffer.allocate(provisioneeConfirmation.length - 2);+ buffer.put(provisioneeConfirmation, 2, buffer.limit());+ mNode.setProvisioneeConfirmation(buffer.array());+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningDataState.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningDataState.javanew file mode 100644index 000000000..844a50728--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningDataState.java@@ -0,0 +1,153 @@+package org.openremote.agent.protocol.bluetooth.mesh.provisionerstates;++import org.openremote.agent.protocol.bluetooth.mesh.InternalProvisioningCallbacks;+import org.openremote.agent.protocol.bluetooth.mesh.InternalTransportCallbacks;+import org.openremote.agent.protocol.bluetooth.mesh.MeshManagerApi;+import org.openremote.agent.protocol.bluetooth.mesh.MeshProvisioningStatusCallbacks;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;+import org.openremote.agent.protocol.bluetooth.mesh.utils.SecureUtils;++import java.nio.ByteBuffer;+import java.util.logging.Logger;++public class ProvisioningDataState extends ProvisioningState {++ public static final Logger LOG = Logger.getLogger(ProvisioningDataState.class.getName());+ private final UnprovisionedMeshNode mUnprovisionedMeshNode;+ private final MeshProvisioningStatusCallbacks mStatusCallbacks;+ private final InternalProvisioningCallbacks provisioningCallbacks;+ private final InternalTransportCallbacks mInternalTransportCallbacks;++ public ProvisioningDataState(final InternalProvisioningCallbacks callbacks,+ final UnprovisionedMeshNode unprovisionedMeshNode,+ final InternalTransportCallbacks mInternalTransportCallbacks,+ final MeshProvisioningStatusCallbacks meshProvisioningStatusCallbacks) {+ super();+ this.provisioningCallbacks = callbacks;+ this.mUnprovisionedMeshNode = unprovisionedMeshNode;+ this.mInternalTransportCallbacks = mInternalTransportCallbacks;+ this.mStatusCallbacks = meshProvisioningStatusCallbacks;+ }++ @Override+ public State getState() {+ return State.PROVISIONING_DATA;+ }++ @Override+ public void executeSend() {+ sendProvisioningData();+ }++ @Override+ public boolean parseData(final byte[] data) {+ return true;+ }++ private void sendProvisioningData() {+ final byte[] provisioningDataPDU = createProvisioningDataPDU();+ mStatusCallbacks.onProvisioningStateChanged(mUnprovisionedMeshNode, States.PROVISIONING_DATA_SENT, provisioningDataPDU);+ mInternalTransportCallbacks.sendProvisioningPdu(mUnprovisionedMeshNode, provisioningDataPDU);+ }++ private byte[] createProvisioningDataPDU() {++ final byte[] provisioningSalt = generateProvisioningSalt();+ LOG.info("Provisioning salt: " + MeshParserUtils.bytesToHex(provisioningSalt, false));++ final byte[] ecdh = mUnprovisionedMeshNode.getSharedECDHSecret();++ final byte[] t = SecureUtils.calculateCMAC(ecdh, provisioningSalt);+ /* Calculating the session key */+ final byte[] sessionKey = SecureUtils.calculateCMAC(SecureUtils.PRSK, t);+ LOG.info("Session key: " + MeshParserUtils.bytesToHex(sessionKey, false));++ /* Calculate the Session nonce */+ final byte[] sessionNonce = generateSessionNonce(ecdh, provisioningSalt);+ LOG.info("Session nonce: " + MeshParserUtils.bytesToHex(sessionNonce, false));++ /* Calculate the Device key */+ final byte[] deviceKey = SecureUtils.calculateCMAC(SecureUtils.PRDK, t);+ LOG.info("Device key: " + MeshParserUtils.bytesToHex(deviceKey, false));+ mUnprovisionedMeshNode.setDeviceKey(deviceKey);++ /* Generate 16 byte Random network key */+ final byte[] networkKey = mUnprovisionedMeshNode.getNetworkKey();+ LOG.info("Network key: " + MeshParserUtils.bytesToHex(networkKey, false));++ /* Generate random 2 byte Key index*/+ final byte[] keyIndex = MeshParserUtils.addKeyIndexPadding(mUnprovisionedMeshNode.getKeyIndex());+ LOG.info("Key index: " + MeshParserUtils.bytesToHex(keyIndex, false));++ /* Generate random 1 byte Flags */+ byte[] flags = mUnprovisionedMeshNode.getFlags();+ LOG.info("Flags: " + MeshParserUtils.bytesToHex(flags, false));++ /* Generate random 4 byte IV Index */+ final byte[] ivIndex = mUnprovisionedMeshNode.getIvIndex();+ LOG.info("IV index: " + MeshParserUtils.bytesToHex(ivIndex, false));++ /* Generate random 2 byte unicast address*/+ final byte[] unicastAddress = MeshAddress.addressIntToBytes(mUnprovisionedMeshNode.getUnicastAddress());++ LOG.info("Unicast address: " + MeshParserUtils.bytesToHex(unicastAddress, false));+ ByteBuffer buffer = ByteBuffer.allocate(networkKey.length + keyIndex.length + flags.length + ivIndex.length + unicastAddress.length);+ buffer.put(networkKey);+ buffer.put(keyIndex);+ buffer.put(flags);+ buffer.put(ivIndex);+ buffer.put(unicastAddress);++ final byte[] provisioningData = buffer.array();+ LOG.info("Provisioning data: " + MeshParserUtils.bytesToHex(provisioningData, false));++ final byte[] encryptedProvisioningData = SecureUtils.encryptCCM(provisioningData, sessionKey, sessionNonce, 8);+ LOG.info("Encrypted provisioning data: " + MeshParserUtils.bytesToHex(encryptedProvisioningData, false));++ buffer = ByteBuffer.allocate(2 + encryptedProvisioningData.length);+ buffer.put(MeshManagerApi.PDU_TYPE_PROVISIONING);+ buffer.put(TYPE_PROVISIONING_DATA);+ buffer.put(encryptedProvisioningData);++ final byte[] provisioningPDU = buffer.array();+ LOG.info("Prov Data: " + MeshParserUtils.bytesToHex(provisioningPDU, false));+ return provisioningPDU;+ }++ /**+ * Generate the provisioning salt.+ * This is done by calculating the salt containing array created by appending the confirmationSalt, provisionerRandom and the provisioneeRandom.+ *+ * @return a byte array+ */+ private byte[] generateProvisioningSalt() {++ final byte[] confirmationSalt = SecureUtils.calculateSalt(provisioningCallbacks.generateConfirmationInputs(mUnprovisionedMeshNode.getProvisionerPublicKeyXY(), mUnprovisionedMeshNode.getProvisioneePublicKeyXY()));+ final byte[] provisionerRandom = mUnprovisionedMeshNode.getProvisionerRandom();+ final byte[] provisioneeRandom = mUnprovisionedMeshNode.getProvisioneeRandom();++ final ByteBuffer buffer = ByteBuffer.allocate(confirmationSalt.length + provisionerRandom.length + provisioneeRandom.length);+ buffer.put(confirmationSalt);+ buffer.put(provisionerRandom);+ buffer.put(provisioneeRandom);++ /* After appending calculate the salt */+ return SecureUtils.calculateSalt(buffer.array());+ }++ /**+ * Calculate the Session nonce+ *+ * @param ecdh shared ECDH secret+ * @param provisioningSalt provisioning salt+ * @return sessionNonce+ */+ private byte[] generateSessionNonce(final byte[] ecdh, final byte[] provisioningSalt) {+ final byte[] nonce = SecureUtils.calculateK1(ecdh, provisioningSalt, SecureUtils.PRSN);+ final ByteBuffer buffer = ByteBuffer.allocate(nonce.length - 3);+ buffer.put(nonce, 3, buffer.limit());+ return buffer.array();+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningFailedState.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningFailedState.javanew file mode 100644index 000000000..2cdceb912--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningFailedState.java@@ -0,0 +1,92 @@+package org.openremote.agent.protocol.bluetooth.mesh.provisionerstates;++public class ProvisioningFailedState extends ProvisioningState {++ private int error;++ public ProvisioningFailedState() {+ super();+ }++ @Override+ public State getState() {+ return State.PROVISIONING_FAILED;+ }++ @Override+ public void executeSend() {++ }++ @Override+ public boolean parseData(final byte[] data) {+ error = data[2];++ return true;+ }++ public int getErrorCode() {+ return error;+ }++ public static String parseProvisioningFailure(final int errorCode) {+ switch (ProvisioningFailureCode.fromErrorCode(errorCode)) {+ case PROHIBITED:+ return "PROHIBITED";/* context.getString(R.string.error_prohibited);*/+ case INVALID_PDU:+ return "INVALID_PDU";/*context.getString(R.string.error_invalid_pdu);*/+ case INVALID_FORMAT:+ return "INVALID_FORMAT";/*context.getString(R.string.error_invalid_format);*/+ case UNEXPECTED_PDU:+ return "UNEXPECTED_PDU";/*context.getString(R.string.error_prohibited);*/+ case CONFIRMATION_FAILED:+ return "CONFIRMATION_FAILED";/*context.getString(R.string.error_confirmation_failed);*/+ case OUT_OF_RESOURCES:+ return "OUT_OF_RESOURCES";/*context.getString(R.string.error_prohibited);*/+ case DECRYPTION_FAILED:+ return "DECRYPTION_FAILED";/*context.getString(R.string.error_decryption_failed);*/+ case UNEXPECTED_ERROR:+ return "UNEXPECTED_ERROR";/*context.getString(R.string.error_unexpected_error);*/+ case CANNOT_ASSIGN_ADDRESSES:+ return "CANNOT_ASSIGN_ADDRESSES";/*context.getString(R.string.error_cannot_assign_addresses);*/+ case UNKNOWN_ERROR_CODE:+ default:+ return "UNKNOWN_ERROR_CODE";/*context.getString(R.string.error_rfu);*/+ }+ }++ public enum ProvisioningFailureCode {+ PROHIBITED(0x00),+ INVALID_PDU(0x01),+ INVALID_FORMAT(0x02),+ UNEXPECTED_PDU(0x03),+ CONFIRMATION_FAILED(0x04),+ OUT_OF_RESOURCES(0x05),+ DECRYPTION_FAILED(0x06),+ UNEXPECTED_ERROR(0x07),+ CANNOT_ASSIGN_ADDRESSES(0x08),+ UNKNOWN_ERROR_CODE(0x09);++ private final int errorCode;++ ProvisioningFailureCode(final int errorCode) {+ this.errorCode = errorCode;+ }++ public static ProvisioningFailureCode fromErrorCode(final int errorCode) {+ for (ProvisioningFailureCode failureCode : ProvisioningFailureCode.values()) {+ if (failureCode.getErrorCode() == errorCode) {+ return failureCode;+ }+ }+ return UNKNOWN_ERROR_CODE;+ //throw new RuntimeException("Enum not found");+ }++ public final int getErrorCode() {+ return errorCode;+ }+ }++}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningInputCompleteState.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningInputCompleteState.javanew file mode 100644index 000000000..94c87186f--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningInputCompleteState.java@@ -0,0 +1,49 @@+package org.openremote.agent.protocol.bluetooth.mesh.provisionerstates;++import org.openremote.agent.protocol.bluetooth.mesh.InternalTransportCallbacks;+import org.openremote.agent.protocol.bluetooth.mesh.MeshManagerApi;+import org.openremote.agent.protocol.bluetooth.mesh.MeshProvisioningStatusCallbacks;++public class ProvisioningInputCompleteState extends ProvisioningState {++ private final UnprovisionedMeshNode mNode;+ private final InternalTransportCallbacks mInternalTransportCallbacks;+ private final MeshProvisioningStatusCallbacks mMeshProvisioningStatusCallbacks;++ /**+ * Constructs the provisioning input complete state+ *+ * @param node {@link UnprovisionedMeshNode} node+ * @param internalTransportCallbacks {@link InternalTransportCallbacks} callbacks+ * @param provisioningStatusCallbacks {@link MeshProvisioningStatusCallbacks} callbacks+ */+ public ProvisioningInputCompleteState(final UnprovisionedMeshNode node,+ final InternalTransportCallbacks internalTransportCallbacks,+ final MeshProvisioningStatusCallbacks provisioningStatusCallbacks) {+ super();+ this.mNode = node;+ this.mInternalTransportCallbacks = internalTransportCallbacks;+ this.mMeshProvisioningStatusCallbacks = provisioningStatusCallbacks;+ }++ @Override+ public State getState() {+ return State.PROVISIONING_INPUT_COMPLETE;+ }++ @Override+ public void executeSend() {+ //Do nothing here+ }++ @Override+ public boolean parseData(final byte[] data) {+ if (data.length == 2 &&+ data[0] == MeshManagerApi.PDU_TYPE_PROVISIONING &&+ data[1] == TYPE_PROVISIONING_INPUT_COMPLETE) {+ mMeshProvisioningStatusCallbacks.onProvisioningStateChanged(mNode, States.PROVISIONING_AUTHENTICATION_INPUT_ENTERED, null);+ return true;+ }+ return false;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningInviteState.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningInviteState.javanew file mode 100644index 000000000..51dff322c--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningInviteState.java@@ -0,0 +1,57 @@+package org.openremote.agent.protocol.bluetooth.mesh.provisionerstates;++import org.openremote.agent.protocol.bluetooth.mesh.InternalTransportCallbacks;+import org.openremote.agent.protocol.bluetooth.mesh.MeshManagerApi;+import org.openremote.agent.protocol.bluetooth.mesh.MeshProvisioningStatusCallbacks;++import java.util.logging.Logger;++public class ProvisioningInviteState extends ProvisioningState {++ public static final Logger LOG = Logger.getLogger(ProvisioningInviteState.class.getName());+ private final UnprovisionedMeshNode mUnprovisionedMeshNode;+ private final int attentionTimer;+ private final MeshProvisioningStatusCallbacks mStatusCallbacks;+ private final InternalTransportCallbacks mInternalTransportCallbacks;++ public ProvisioningInviteState(final UnprovisionedMeshNode unprovisionedMeshNode, final int attentionTimer, final InternalTransportCallbacks mInternalTransportCallbacks, final MeshProvisioningStatusCallbacks meshProvisioningStatusCallbacks) {+ super();+ this.mUnprovisionedMeshNode = unprovisionedMeshNode;+ this.attentionTimer = attentionTimer;+ this.mStatusCallbacks = meshProvisioningStatusCallbacks;+ this.mInternalTransportCallbacks = mInternalTransportCallbacks;+ }++ @Override+ public State getState() {+ return State.PROVISIONING_INVITE;+ }++ @Override+ public void executeSend() {+ final byte[] invitePDU = createInvitePDU();+ //We store the provisioning invite pdu to be used when generating confirmation inputs+ mUnprovisionedMeshNode.setProvisioningInvitePdu(invitePDU);+ mStatusCallbacks.onProvisioningStateChanged(mUnprovisionedMeshNode, States.PROVISIONING_INVITE, invitePDU);+ mInternalTransportCallbacks.sendProvisioningPdu(mUnprovisionedMeshNode, invitePDU);+ }++ @Override+ public boolean parseData(final byte[] data) {+ return true;+ }++ /**+ * Generates the invitePDU for provisioning based on the attention timer provided by the user.+ */+ private byte[] createInvitePDU() {++ final byte[] data = new byte[3];+ data[0] = MeshManagerApi.PDU_TYPE_PROVISIONING; //Provisioning Opcode;+ //noinspection ConstantConditions+ data[1] = TYPE_PROVISIONING_INVITE; //PDU type in+ data[2] = (byte) attentionTimer;+ return data;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningPublicKeyState.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningPublicKeyState.javanew file mode 100644index 000000000..d0365511e--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningPublicKeyState.java@@ -0,0 +1,181 @@+package org.openremote.agent.protocol.bluetooth.mesh.provisionerstates;++import org.openremote.agent.protocol.bluetooth.mesh.InternalTransportCallbacks;+import org.openremote.agent.protocol.bluetooth.mesh.MeshManagerApi;+import org.openremote.agent.protocol.bluetooth.mesh.MeshProvisioningStatusCallbacks;+++import org.bouncycastle.jce.ECNamedCurveTable;+import org.bouncycastle.jce.interfaces.ECPrivateKey;+import org.bouncycastle.jce.interfaces.ECPublicKey;+import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec;+import org.bouncycastle.jce.spec.ECParameterSpec;+import org.bouncycastle.jce.spec.ECPublicKeySpec;+import org.bouncycastle.math.ec.ECCurve;+import org.bouncycastle.math.ec.ECPoint;+import org.bouncycastle.util.BigIntegers;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import javax.crypto.KeyAgreement;+import java.math.BigInteger;+import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.security.InvalidKeyException;+import java.security.KeyFactory;+import java.security.KeyPair;+import java.security.KeyPairGenerator;+import java.security.NoSuchAlgorithmException;+import java.security.NoSuchProviderException;+import java.security.spec.InvalidKeySpecException;+import java.util.logging.Logger;++public class ProvisioningPublicKeyState extends ProvisioningState {++ private static final int PROVISIONING_PUBLIC_KEY_XY_PDU_LENGTH = 69;+ public static final Logger LOG = Logger.getLogger(ProvisioningPublicKeyState.class.getName());+ private final byte[] publicKeyXY = new byte[PROVISIONING_PUBLIC_KEY_XY_PDU_LENGTH];+ private final MeshProvisioningStatusCallbacks mStatusCallbacks;+ private final UnprovisionedMeshNode mUnprovisionedMeshNode;+ private final InternalTransportCallbacks mInternalTransportCallbacks;++ private byte[] mTempProvisioneeXY;+ private int segmentCount = 0;+ private ECPrivateKey mProvisionerPrivaetKey;+++ public ProvisioningPublicKeyState(final UnprovisionedMeshNode unprovisionedMeshNode, final InternalTransportCallbacks mInternalTransportCallbacks, final MeshProvisioningStatusCallbacks meshProvisioningStatusCallbacks) {+ super();+ this.mUnprovisionedMeshNode = unprovisionedMeshNode;+ this.mStatusCallbacks = meshProvisioningStatusCallbacks;+ this.mInternalTransportCallbacks = mInternalTransportCallbacks;+ }++ @Override+ public State getState() {+ return State.PROVISIONING_PUBLIC_KEY;+ }++ @Override+ public void executeSend() {+ generateKeyPairs();+ final byte[] pdu = generatePublicKeyXYPDU();+ mStatusCallbacks.onProvisioningStateChanged(mUnprovisionedMeshNode, States.PROVISIONING_PUBLIC_KEY_SENT, pdu);+ mInternalTransportCallbacks.sendProvisioningPdu(mUnprovisionedMeshNode, pdu);+ }++ @Override+ public boolean parseData(final byte[] data) {+ mStatusCallbacks.onProvisioningStateChanged(mUnprovisionedMeshNode, States.PROVISIONING_PUBLIC_KEY_RECEIVED, data);+ generateSharedECDHSecret(data);+ return true;+ }++ private void generateKeyPairs() {++ try {+ final ECNamedCurveParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec("secp256r1");+ final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("ECDH", "SC");+ keyPairGenerator.initialize(parameterSpec);+ final KeyPair keyPair = keyPairGenerator.generateKeyPair();+ final ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();++ mProvisionerPrivaetKey = (ECPrivateKey) keyPair.getPrivate();++ final ECPoint point = publicKey.getQ();++ final BigInteger x = point.getXCoord().toBigInteger();+ final BigInteger y = point.getYCoord().toBigInteger();+ final byte[] tempX = BigIntegers.asUnsignedByteArray(32, x);+ final byte[] tempY = BigIntegers.asUnsignedByteArray(32, y);++ LOG.info("X: length: " + tempX.length + " " + MeshParserUtils.bytesToHex(tempX, false));+ LOG.info("Y: length: " + tempY.length + " " + MeshParserUtils.bytesToHex(tempY, false));++ final byte[] tempXY = new byte[64];+ System.arraycopy(tempX, 0, tempXY, 0, tempX.length);+ System.arraycopy(tempY, 0, tempXY, tempY.length, tempY.length);++ mUnprovisionedMeshNode.setProvisionerPublicKeyXY(tempXY);++ LOG.info("XY: " + MeshParserUtils.bytesToHex(tempXY, true));++ } catch (Exception e) {+ e.printStackTrace();+ }+ }++ private byte[] generatePublicKeyXYPDU() {++ final byte[] tempXY = mUnprovisionedMeshNode.getProvisionerPublicKeyXY();++ ByteBuffer buffer = ByteBuffer.allocate(tempXY.length + 2);+ buffer.put(MeshManagerApi.PDU_TYPE_PROVISIONING);+ buffer.put(TYPE_PROVISIONING_PUBLIC_KEY);+ buffer.put(tempXY);++ return buffer.array();+ }++ private void generateSharedECDHSecret(final byte[] provisioneePublicKeyXYPDU) {+ if (provisioneePublicKeyXYPDU.length != 66) {+ throw new IllegalArgumentException("Invalid Provisionee Public Key PDU," ++ " length of the Provisionee public key must be 66 bytes, but was " + provisioneePublicKeyXYPDU.length);+ }+ final ByteBuffer buffer = ByteBuffer.allocate(provisioneePublicKeyXYPDU.length - 2);+ buffer.put(provisioneePublicKeyXYPDU, 2, buffer.limit());+ final byte[] xy = mTempProvisioneeXY = buffer.array();+ mUnprovisionedMeshNode.setProvisioneePublicKeyXY(xy);++ final byte[] xComponent = new byte[32];+ System.arraycopy(xy, 0, xComponent, 0, xComponent.length);++ final byte[] yComponent = new byte[32];+ System.arraycopy(xy, 32, yComponent, 0, xComponent.length);++ final byte[] provisioneeX = convertToLittleEndian(xComponent, ByteOrder.LITTLE_ENDIAN);+ LOG.info("Provsionee X: " + MeshParserUtils.bytesToHex(provisioneeX, false));++ final byte[] provisioneeY = convertToLittleEndian(yComponent, ByteOrder.LITTLE_ENDIAN);+ LOG.info("Provsionee Y: " + MeshParserUtils.bytesToHex(provisioneeY, false));++ final BigInteger x = BigIntegers.fromUnsignedByteArray(xy, 0, 32);+ final BigInteger y = BigIntegers.fromUnsignedByteArray(xy, 32, 32);++ final ECParameterSpec ecParameters = ECNamedCurveTable.getParameterSpec("secp256r1");+ ECCurve curve = ecParameters.getCurve();+ ECPoint ecPoint = curve.validatePoint(x, y);+++ ECPublicKeySpec keySpec = new ECPublicKeySpec(ecPoint, ecParameters);+ KeyFactory keyFactory;+ try {+ keyFactory = KeyFactory.getInstance("ECDH", "SC");+ ECPublicKey publicKey = (ECPublicKey) keyFactory.generatePublic(keySpec);++ KeyAgreement a = KeyAgreement.getInstance("ECDH", "SC");+ a.init(mProvisionerPrivaetKey);+ a.doPhase(publicKey, true);++ final byte[] sharedECDHSecret = a.generateSecret();+ mUnprovisionedMeshNode.setSharedECDHSecret(sharedECDHSecret);+ LOG.info("ECDH Secret: " + MeshParserUtils.bytesToHex(sharedECDHSecret, false));++ } catch (NoSuchAlgorithmException e) {+ e.printStackTrace();+ } catch (NoSuchProviderException e) {+ e.printStackTrace();+ } catch (InvalidKeySpecException e) {+ e.printStackTrace();+ } catch (InvalidKeyException e) {+ e.printStackTrace();+ }+ }++ private byte[] convertToLittleEndian(final byte[] data, final ByteOrder order) {+ ByteBuffer buffer = ByteBuffer.allocate(data.length);+ buffer.order(order);+ buffer.put(data);+ return buffer.array();+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningRandomConfirmationState.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningRandomConfirmationState.javanew file mode 100644index 000000000..69a78b54f--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningRandomConfirmationState.java@@ -0,0 +1,104 @@+package org.openremote.agent.protocol.bluetooth.mesh.provisionerstates;++import org.openremote.agent.protocol.bluetooth.mesh.InternalProvisioningCallbacks;+import org.openremote.agent.protocol.bluetooth.mesh.InternalTransportCallbacks;+import org.openremote.agent.protocol.bluetooth.mesh.MeshManagerApi;+import org.openremote.agent.protocol.bluetooth.mesh.MeshProvisioningStatusCallbacks;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;+import org.openremote.agent.protocol.bluetooth.mesh.utils.SecureUtils;++import java.nio.ByteBuffer;+import java.util.Arrays;+import java.util.logging.Logger;++public class ProvisioningRandomConfirmationState extends ProvisioningState {++ public static final Logger LOG = Logger.getLogger(ProvisioningRandomConfirmationState.class.getName());+ private final UnprovisionedMeshNode mUnprovisionedMeshNode;+ private final MeshProvisioningStatusCallbacks mStatusCallbacks;+ private final InternalProvisioningCallbacks provisioningCallbacks;+ private final InternalTransportCallbacks mInternalTransportCallbacks;++ public ProvisioningRandomConfirmationState(final InternalProvisioningCallbacks callbacks,+ final UnprovisionedMeshNode unprovisionedMeshNode,+ final InternalTransportCallbacks mInternalTransportCallbacks,+ final MeshProvisioningStatusCallbacks meshProvisioningStatusCallbacks) {+ super();+ this.provisioningCallbacks = callbacks;+ this.mUnprovisionedMeshNode = unprovisionedMeshNode;+ this.mInternalTransportCallbacks = mInternalTransportCallbacks;+ this.mStatusCallbacks = meshProvisioningStatusCallbacks;+ }++ @Override+ public State getState() {+ return State.PROVISIONING_RANDOM;+ }++ @Override+ public void executeSend() {+ final byte[] provisionerRandomConfirmationPDU = createProvisionerRandomPDU();+ mStatusCallbacks.onProvisioningStateChanged(mUnprovisionedMeshNode, States.PROVISIONING_CONFIRMATION_SENT, provisionerRandomConfirmationPDU);+ mInternalTransportCallbacks.sendProvisioningPdu(mUnprovisionedMeshNode, provisionerRandomConfirmationPDU);+ }++ @Override+ public boolean parseData(final byte[] data) {+ mStatusCallbacks.onProvisioningStateChanged(mUnprovisionedMeshNode, States.PROVISIONING_RANDOM_RECEIVED, data);+ parseProvisioneeRandom(data);+ return provisioneeMatches();+ }++ private byte[] createProvisionerRandomPDU() {+ final byte[] provisionerRandom = mUnprovisionedMeshNode.getProvisionerRandom();+ final ByteBuffer buffer = ByteBuffer.allocate(provisionerRandom.length + 2);+ buffer.put(new byte[]{MeshManagerApi.PDU_TYPE_PROVISIONING, TYPE_PROVISIONING_RANDOM_CONFIRMATION});+ buffer.put(provisionerRandom);+ final byte[] data = buffer.array();+ LOG.info("Provisioner random PDU: " + MeshParserUtils.bytesToHex(data, false));+ return data;+ }++ private boolean provisioneeMatches() {+ final byte[] provisioneeRandom = mUnprovisionedMeshNode.getProvisioneeRandom();++ final byte[] confirmationInputs = provisioningCallbacks.generateConfirmationInputs(mUnprovisionedMeshNode.getProvisionerPublicKeyXY(),+ mUnprovisionedMeshNode.getProvisioneePublicKeyXY());+ LOG.info("Confirmation inputs: " + MeshParserUtils.bytesToHex(confirmationInputs, false));++ //Generate a confirmation salt of the confirmation inputs+ final byte[] confirmationSalt = SecureUtils.calculateSalt(confirmationInputs);+ LOG.info("Confirmation salt: " + MeshParserUtils.bytesToHex(confirmationSalt, false));++ final byte[] ecdhSecret = mUnprovisionedMeshNode.getSharedECDHSecret();++ //Generate the confirmationKey by calculating the K1 of ECDH, confirmationSalt and ASCII value of "prck".+ final byte[] confirmationKey = SecureUtils.calculateK1(ecdhSecret, confirmationSalt, SecureUtils.PRCK);+ LOG.info("Confirmation key: " + MeshParserUtils.bytesToHex(confirmationKey, false));++ //Generate authentication value from the user input pin+ final byte[] authenticationValue = mUnprovisionedMeshNode.getAuthenticationValue();+ LOG.info("Authentication value: " + MeshParserUtils.bytesToHex(authenticationValue, false));++ ByteBuffer buffer = ByteBuffer.allocate(provisioneeRandom.length + authenticationValue.length);+ buffer.put(provisioneeRandom);+ buffer.put(authenticationValue);+ final byte[] confirmationData = buffer.array();++ final byte[] confirmationValue = SecureUtils.calculateCMAC(confirmationData, confirmationKey);++ if (Arrays.equals(confirmationValue, mUnprovisionedMeshNode.getProvisioneeConfirmation())) {+ LOG.info("Confirmation values match!!!!: " + MeshParserUtils.bytesToHex(confirmationValue, false));+ return true;+ }++ return false;+ }++ private void parseProvisioneeRandom(final byte[] provisioneeRandomPDU) {+ final ByteBuffer buffer = ByteBuffer.allocate(provisioneeRandomPDU.length - 2);+ buffer.put(provisioneeRandomPDU, 2, buffer.limit());+ mUnprovisionedMeshNode.setProvisioneeRandom(buffer.array());+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningStartState.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningStartState.javanew file mode 100644index 000000000..2407f52af--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningStartState.java@@ -0,0 +1,128 @@+package org.openremote.agent.protocol.bluetooth.mesh.provisionerstates;++import org.openremote.agent.protocol.bluetooth.mesh.InternalTransportCallbacks;+import org.openremote.agent.protocol.bluetooth.mesh.MeshManagerApi;+import org.openremote.agent.protocol.bluetooth.mesh.MeshProvisioningStatusCallbacks;+import org.openremote.agent.protocol.bluetooth.mesh.utils.AlgorithmType;+import org.openremote.agent.protocol.bluetooth.mesh.utils.AuthenticationOOBMethods;+import org.openremote.agent.protocol.bluetooth.mesh.utils.InputOOBAction;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;+import org.openremote.agent.protocol.bluetooth.mesh.utils.OutputOOBAction;+import org.openremote.agent.protocol.bluetooth.mesh.utils.StaticOOBType;++import java.util.logging.Logger;++public class ProvisioningStartState extends ProvisioningState {++ public static final Logger LOG = Logger.getLogger(ProvisioningStartState.class.getName());+ private final UnprovisionedMeshNode mNode;+ private final MeshProvisioningStatusCallbacks mMeshProvisioningStatusCallbacks;+ private final InternalTransportCallbacks mInternalTransportCallbacks;++ private int numberOfElements;+ private int algorithm;+ private int publicKeyType;+ private int staticOOBType;+ private int outputOOBSize;+ private int outputOOBAction;+ private int inputOOBSize;+ private int inputOOBAction;+ private short outputActionType;+ private short inputActionType;++ public ProvisioningStartState(final UnprovisionedMeshNode node,+ final InternalTransportCallbacks internalTransportCallbacks,+ final MeshProvisioningStatusCallbacks provisioningStatusCallbacks) {+ super();+ this.mNode = node;+ this.mInternalTransportCallbacks = internalTransportCallbacks;+ this.mMeshProvisioningStatusCallbacks = provisioningStatusCallbacks;+ }++ public void setUseStaticOOB(final StaticOOBType actionType) {+ mNode.setAuthMethodUsed(AuthenticationOOBMethods.STATIC_OOB_AUTHENTICATION);+ mNode.setAuthActionUsed(actionType.getStaticOobType());+ }++ public void setUseOutputOOB(final OutputOOBAction actionType) {+ mNode.setAuthMethodUsed(AuthenticationOOBMethods.OUTPUT_OOB_AUTHENTICATION);+ this.outputActionType = actionType.getOutputOOBAction();+ mNode.setAuthActionUsed(actionType.getOutputOOBAction());+ }++ public void setUseInputOOB(final InputOOBAction actionType) {+ mNode.setAuthMethodUsed(AuthenticationOOBMethods.INPUT_OOB_AUTHENTICATION);+ this.inputActionType = actionType.getInputOOBAction();+ mNode.setAuthActionUsed(actionType.getInputOOBAction());+ }++ @Override+ public State getState() {+ return State.PROVISIONING_START;+ }++ @Override+ public void executeSend() {+ final byte[] provisioningStartPDU = createProvisioningStartPDU();+ //We store the provisioning start pdu to be used when generating confirmation inputs+ mNode.setProvisioningStartPdu(provisioningStartPDU);+ mMeshProvisioningStatusCallbacks.onProvisioningStateChanged(mNode, States.PROVISIONING_START, provisioningStartPDU);+ mInternalTransportCallbacks.sendProvisioningPdu(mNode, provisioningStartPDU);+ }++ @Override+ public boolean parseData(final byte[] data) {+ return true;+ }++ private byte[] createProvisioningStartPDU() {+ final byte[] provisioningPDU = new byte[7];+ provisioningPDU[0] = MeshManagerApi.PDU_TYPE_PROVISIONING;+ provisioningPDU[1] = TYPE_PROVISIONING_START;+ provisioningPDU[2] = AlgorithmType.getAlgorithmValue((short) algorithm);+ provisioningPDU[3] = 0; // (byte) publicKeyType;+ provisioningPDU[4] = (byte) mNode.getAuthMethodUsed().ordinal();+ switch (mNode.getAuthMethodUsed()) {+ case NO_OOB_AUTHENTICATION:+ provisioningPDU[5] = 0;+ provisioningPDU[6] = 0;+ break;+ case STATIC_OOB_AUTHENTICATION:+ provisioningPDU[5] = 0;+ provisioningPDU[6] = 0;+ break;+ case OUTPUT_OOB_AUTHENTICATION:+ provisioningPDU[5] = (byte) OutputOOBAction.getOutputOOBActionValue(this.outputActionType);+ provisioningPDU[6] = (byte) outputOOBSize;+ break;+ case INPUT_OOB_AUTHENTICATION:+ provisioningPDU[5] = (byte) InputOOBAction.getInputOOBActionValue(this.inputActionType);+ provisioningPDU[6] = (byte) inputOOBSize;+ mNode.setInputAuthentication(InputOOBAction.getInputOOOBAuthenticationValue(inputActionType, (byte) inputOOBSize));+ break;++ }+ LOG.info("Provisioning start PDU: " + MeshParserUtils.bytesToHex(provisioningPDU, true));++ return provisioningPDU;+ }++ public void setProvisioningCapabilities(final int numberOfElements,+ final int algorithm,+ final int publicKeyType,+ final int staticOOBType,+ final int outputOOBSize,+ final int outputOOBAction,+ final int inputOOBSize,+ final int inputOOBAction) {+ this.numberOfElements = numberOfElements;+ this.algorithm = algorithm;+ this.publicKeyType = publicKeyType;+ this.staticOOBType = staticOOBType;+ this.outputOOBSize = outputOOBSize;+ this.outputOOBAction = outputOOBAction;+ this.inputOOBSize = inputOOBSize;+ this.inputOOBAction = inputOOBAction;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningState.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningState.javanew file mode 100644index 000000000..ce6c63f78--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/ProvisioningState.java@@ -0,0 +1,89 @@+package org.openremote.agent.protocol.bluetooth.mesh.provisionerstates;++public abstract class ProvisioningState {++ static final byte TYPE_PROVISIONING_INVITE = 0x00;+ static final byte TYPE_PROVISIONING_CAPABILITIES = 0x01;+ static final byte TYPE_PROVISIONING_START = 0x02;+ static final byte TYPE_PROVISIONING_PUBLIC_KEY = 0x03;+ static final byte TYPE_PROVISIONING_INPUT_COMPLETE = 0x04;+ static final byte TYPE_PROVISIONING_CONFIRMATION = 0x05;+ static final byte TYPE_PROVISIONING_RANDOM_CONFIRMATION = 0x06;+ static final byte TYPE_PROVISIONING_DATA = 0x07;+ static final byte TYPE_PROVISIONING_COMPLETE = 0x08;++ public ProvisioningState() {+ }++ public abstract State getState();++ public abstract void executeSend();++ public abstract boolean parseData(final byte[] data);++ public enum State {+ PROVISIONING_INVITE(0), PROVISIONING_CAPABILITIES(1), PROVISIONING_START(2), PROVISIONING_PUBLIC_KEY(3),+ PROVISIONING_INPUT_COMPLETE(4), PROVISIONING_CONFIRMATION(5), PROVISIONING_RANDOM(6),+ PROVISIONING_DATA(7), PROVISIONING_COMPLETE(8), PROVISIONING_FAILED(9);++ private int state;++ State(final int state) {+ this.state = state;+ }++ public int getState() {+ return state;+ }++ }++ public enum States {+ PROVISIONING_INVITE(0),+ PROVISIONING_CAPABILITIES(1),+ PROVISIONING_START(2),+ PROVISIONING_PUBLIC_KEY_SENT(3),+ PROVISIONING_PUBLIC_KEY_RECEIVED(4),+ PROVISIONING_AUTHENTICATION_INPUT_OOB_WAITING(5),+ PROVISIONING_AUTHENTICATION_OUTPUT_OOB_WAITING(6),+ PROVISIONING_AUTHENTICATION_STATIC_OOB_WAITING(7),+ PROVISIONING_AUTHENTICATION_INPUT_ENTERED(8),+ PROVISIONING_INPUT_COMPLETE(9),+ PROVISIONING_CONFIRMATION_SENT(10),+ PROVISIONING_CONFIRMATION_RECEIVED(11),+ PROVISIONING_RANDOM_SENT(12),+ PROVISIONING_RANDOM_RECEIVED(13),+ PROVISIONING_DATA_SENT(14),+ PROVISIONING_COMPLETE(15),+ PROVISIONING_FAILED(16),+ COMPOSITION_DATA_GET_SENT(17),+ COMPOSITION_DATA_STATUS_RECEIVED(18),+ SENDING_DEFAULT_TTL_GET(19),+ DEFAULT_TTL_STATUS_RECEIVED(20),+ SENDING_APP_KEY_ADD(21),+ APP_KEY_STATUS_RECEIVED(22),+ SENDING_NETWORK_TRANSMIT_SET(23),+ NETWORK_TRANSMIT_STATUS_RECEIVED(24),+ SENDING_BLOCK_ACKNOWLEDGEMENT(98),+ BLOCK_ACKNOWLEDGEMENT_RECEIVED(99);++ private int state;++ States(final int state) {+ this.state = state;+ }++ public int getState() {+ return state;+ }++ public static States fromStatusCode(final int statusCode) {+ for (States state : States.values()) {+ if (state.getState() == statusCode) {+ return state;+ }+ }+ throw new IllegalStateException("Invalid state");+ }+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/UnprovisionedBaseMeshNode.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/UnprovisionedBaseMeshNode.javanew file mode 100644index 000000000..4bd48c69b--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/UnprovisionedBaseMeshNode.java@@ -0,0 +1,219 @@+package org.openremote.agent.protocol.bluetooth.mesh.provisionerstates;++import org.openremote.agent.protocol.bluetooth.mesh.utils.AuthenticationOOBMethods;+import org.openremote.agent.protocol.bluetooth.mesh.utils.InputOOBAction;+import org.openremote.agent.protocol.bluetooth.mesh.utils.OutputOOBAction;+import org.openremote.agent.protocol.bluetooth.mesh.utils.StaticOOBType;++import java.util.UUID;+import java.util.logging.Logger;++public class UnprovisionedBaseMeshNode {++ public static final Logger LOG = Logger.getLogger(UnprovisionedBaseMeshNode.class.getName());++ private int mConfigurationSrc;+ protected byte[] ivIndex;+ boolean isProvisioned;+ boolean isConfigured;+ protected String nodeName = "My Node";+ byte[] provisionerPublicKeyXY;+ byte[] provisioneePublicKeyXY;+ byte[] sharedECDHSecret;+ byte[] provisionerRandom;+ byte[] provisioneeConfirmation;+ byte[] authenticationValue;+ byte[] provisioneeRandom;+ protected byte[] networkKey;+ byte[] identityKey;+ protected int keyIndex;+ byte[] mFlags;+ protected int unicastAddress;+ byte[] deviceKey;+ protected int ttl = 5;+ private String bluetoothDeviceAddress;+ long mTimeStampInMillis;+ ProvisioningCapabilities provisioningCapabilities;+ int numberOfElements;+ UUID deviceUuid;+ byte[] provisioningInvitePdu;+ //capabilties pdu received by the provisioner+ byte[] provisioningCapabilitiesPdu;+ //provisioning start pdu sent by the provisioner+ byte[] provisioningStartPdu;+ AuthenticationOOBMethods authMethodUsed = AuthenticationOOBMethods.NO_OOB_AUTHENTICATION;+ short authActionUsed;+ byte[] inputAuthentication;++ UnprovisionedBaseMeshNode(final UUID uuid) {+ deviceUuid = uuid;+ }++ public boolean isProvisioned() {+ return isProvisioned;+ }++ public final boolean isConfigured() {+ return isConfigured;+ }++ public final void setConfigured(final boolean configured) {+ isConfigured = configured;+ }++ public final String getNodeName() {+ return nodeName;+ }++ public final void setNodeName(final String nodeName) {+ if (nodeName != null && nodeName.length() > 0)+ this.nodeName = nodeName;+ }++ public final int getUnicastAddress() {+ return unicastAddress;+ }++ public final void setUnicastAddress(final int unicastAddress) {+ this.unicastAddress = unicastAddress;+ }++ public byte[] getDeviceKey() {+ return deviceKey;+ }++ public int getTtl() {+ return ttl;+ }++ public final byte[] getIdentityKey() {+ return identityKey;+ }++ public final int getKeyIndex() {+ return keyIndex;+ }++ public final void setKeyIndex(final int keyIndex) {+ this.keyIndex = keyIndex;+ }++ public final byte[] getFlags() {+ return mFlags;+ }++ public final void setFlags(final byte[] flags) {+ this.mFlags = flags;+ }++ public final byte[] getIvIndex() {+ return ivIndex;+ }++ public final void setIvIndex(final byte[] ivIndex) {+ this.ivIndex = ivIndex;+ }++ public void setTtl(final int ttl) {+ this.ttl = ttl;+ }++ public long getTimeStamp() {+ return mTimeStampInMillis;+ }++ public final int getConfigurationSrc() {+ return mConfigurationSrc;+ }++ public final void setConfigurationSrc(final int src) {+ mConfigurationSrc = src;+ }++ public ProvisioningCapabilities getProvisioningCapabilities() {+ return provisioningCapabilities;+ }++ public int getNumberOfElements() {+ return numberOfElements;+ }++ public UUID getDeviceUuid() {+ return deviceUuid;+ }++ public byte[] getProvisioningInvitePdu() {+ return provisioningInvitePdu;+ }++ void setProvisioningInvitePdu(final byte[] provisioningInvitePdu) {+ this.provisioningInvitePdu = provisioningInvitePdu;+ }++ public byte[] getProvisioningStartPdu() {+ return provisioningStartPdu;+ }++ void setProvisioningStartPdu(final byte[] provisioningStartPdu) {+ this.provisioningStartPdu = provisioningStartPdu;+ }++ public byte[] getProvisioningCapabilitiesPdu() {+ return provisioningCapabilitiesPdu;+ }++ void setProvisioningCapabilitiesPdu(final byte[] provisioningCapabilitiesPdu) {+ this.provisioningCapabilitiesPdu = provisioningCapabilitiesPdu;+ }++ /**+ * Returns the authentication method used during the provisioning process+ */+ public AuthenticationOOBMethods getAuthMethodUsed() {+ return authMethodUsed;+ }++ /**+ * Sets the authentication method used during the provisioning process+ *+ * @param authMethodUsed {@link AuthenticationOOBMethods} authentication methods+ */+ void setAuthMethodUsed(final AuthenticationOOBMethods authMethodUsed) {+ this.authMethodUsed = authMethodUsed;+ }++ /**+ * Returns the auth action value and this depends on the {@link AuthenticationOOBMethods} used and the possible values are+ * {@link StaticOOBType}+ * {@link OutputOOBAction}+ * {@link InputOOBAction}+ */+ public short getAuthActionUsed() {+ return authActionUsed;+ }++ /**+ * Sets the authentication action used when sending the provisioning invite.+ *+ * @param authActionUsed auth action used+ */+ void setAuthActionUsed(final short authActionUsed) {+ this.authActionUsed = authActionUsed;+ }++ /**+ * Returns the input authentication value to be input by the provisioner if Input OOB was selected+ */+ public byte[] getInputAuthentication() {+ return inputAuthentication;+ }++ /**+ * Sets the input authentication value to be input by the provisioner if Input OOB was selected+ *+ * @param inputAuthentication generated input authentication+ */+ void setInputAuthentication(final byte[] inputAuthentication) {+ this.inputAuthentication = inputAuthentication;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/UnprovisionedMeshNode.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/UnprovisionedMeshNode.javanew file mode 100644index 000000000..bcc1c43a4--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/provisionerstates/UnprovisionedMeshNode.java@@ -0,0 +1,103 @@+package org.openremote.agent.protocol.bluetooth.mesh.provisionerstates;++import org.openremote.agent.protocol.bluetooth.mesh.utils.SecureUtils;++import java.util.UUID;++public final class UnprovisionedMeshNode extends UnprovisionedBaseMeshNode {++ public UnprovisionedMeshNode(final UUID uuid) {+ super(uuid);+ }++ public final byte[] getSharedECDHSecret() {+ return sharedECDHSecret;+ }++ final void setSharedECDHSecret(final byte[] sharedECDHSecret) {+ this.sharedECDHSecret = sharedECDHSecret;+ }++ public final byte[] getProvisionerPublicKeyXY() {+ return provisionerPublicKeyXY;+ }++ public final void setProvisionerPublicKeyXY(final byte[] rawProvisionerKey) {+ this.provisionerPublicKeyXY = rawProvisionerKey;+ }++ public final byte[] getProvisioneePublicKeyXY() {+ return provisioneePublicKeyXY;+ }++ final void setProvisioneePublicKeyXY(final byte[] provisioneePublicKeyXY) {+ this.provisioneePublicKeyXY = provisioneePublicKeyXY;+ }++ public final byte[] getProvisionerRandom() {+ return provisionerRandom;+ }++ final void setProvisionerRandom(final byte[] provisionerRandom) {+ this.provisionerRandom = provisionerRandom;+ }++ public final byte[] getProvisioneeConfirmation() {+ return provisioneeConfirmation;+ }++ final void setProvisioneeConfirmation(final byte[] provisioneeConfirmation) {+ this.provisioneeConfirmation = provisioneeConfirmation;+ }++ /**+ * Returns the 128-bit authentication value generated based on the user selected OOB type+ */+ public final byte[] getAuthenticationValue() {+ return authenticationValue;+ }++ /**+ * Sets the 128-bit authentication value generated based on the user input if the user input was selected+ * @param authenticationValue 128-bit auth value+ */+ final void setAuthenticationValue(final byte[] authenticationValue) {+ this.authenticationValue = authenticationValue;+ }++ public final byte[] getProvisioneeRandom() {+ return provisioneeRandom;+ }++ final void setProvisioneeRandom(final byte[] provisioneeRandom) {+ this.provisioneeRandom = provisioneeRandom;+ }++ public final byte[] getNetworkKey() {+ return networkKey;+ }++ public final void setNetworkKey(final byte[] networkKey) {+ this.networkKey = networkKey;+ }++ final void setDeviceKey(final byte[] deviceKey) {+ this.deviceKey = deviceKey;+ }++ final void setProvisionedTime(final long timeStampInMillis) {+ mTimeStampInMillis = timeStampInMillis;+ }++ void setProvisioningCapabilities(final ProvisioningCapabilities provisioningCapabilities) {+ numberOfElements = provisioningCapabilities.getNumberOfElements();+ this.provisioningCapabilities = provisioningCapabilities;+ }++ final void setIsProvisioned(final boolean isProvisioned) {+ this.isProvisioned = isProvisioned;+ if (isProvisioned) {+ identityKey = SecureUtils.calculateIdentityKey(networkKey);+ }+ }+}\ No newline at end of filediff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/AccessLayer.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/AccessLayer.javanew file mode 100644index 000000000..2d9c4aeed--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/AccessLayer.java@@ -0,0 +1,108 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++import static org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils.bytesToHex;+import static org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils.createVendorOpCode;+import static org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils.getOpCode;+import static org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils.getOpCodeLength;+++/**+ * AccessLayer implementation of the mesh network architecture as per the mesh profile specification.+ * <p>+ * AccessLayer class generates/parses a raw mesh message containing the specific OpCode and Parameters.+ * </p>+ */+abstract class AccessLayer {++ public static final Logger LOG = Logger.getLogger(AccessLayer.class.getName());+ //protected Context mContext;+ //Handler mHandler;+ ProvisionedMeshNode mMeshNode;++ //protected abstract void initHandler();++ /**+ * Creates an access message+ *+ * @param message Access message containing the required opcodes and parameters to create access message pdu.+ */+ synchronized void createMeshMessage(final Message message) {+ createAccessMessage((AccessMessage) message);+ }++ /**+ * Creates a vendor model access message+ *+ * @param message Access message containing the required opcodes and parameters to create access message pdu.+ */+ synchronized void createVendorMeshMessage(final Message message) {+ createCustomAccessMessage((AccessMessage) message);+ }++ /**+ * Creates an access message+ *+ * @param accessMessage Access message containing the required opcodes and parameters to create access message pdu.+ */+ synchronized final void createAccessMessage(final AccessMessage accessMessage) {+ final byte[] opCodes = getOpCode(accessMessage.getOpCode());+ final byte[] parameters = accessMessage.getParameters();+ final ByteBuffer accessMessageBuffer;+ if (parameters != null) {+ accessMessageBuffer = ByteBuffer.allocate(opCodes.length + parameters.length);+ accessMessageBuffer.put(opCodes).put(parameters);+ } else {+ accessMessageBuffer = ByteBuffer.allocate(opCodes.length);+ accessMessageBuffer.put(opCodes);+ }+ final byte[] accessPdu = accessMessageBuffer.array();++ LOG.info("Created Access PDU " + bytesToHex(accessPdu, false));+ accessMessage.setAccessPdu(accessMessageBuffer.array());+ }++ /**+ * Creates an access message+ *+ * @param accessMessage Access message containing the required opcodes and parameters to create access message pdu.+ */+ synchronized final void createCustomAccessMessage(final AccessMessage accessMessage) {+ final byte[] parameters = accessMessage.getParameters();+ final byte[] vendorOpcode = createVendorOpCode(accessMessage.getOpCode(),+ accessMessage.getCompanyIdentifier());+ final ByteBuffer accessMessageBuffer;+ if (parameters != null) {+ accessMessageBuffer = ByteBuffer.allocate(vendorOpcode.length + parameters.length);+ accessMessageBuffer.put(vendorOpcode);+ accessMessageBuffer.put(parameters);+ } else {+ accessMessageBuffer = ByteBuffer.allocate(vendorOpcode.length);+ accessMessageBuffer.put(vendorOpcode);+ }+ final byte[] accessPdu = accessMessageBuffer.array();+ LOG.info("Created Access PDU " + bytesToHex(accessPdu, false));+ accessMessage.setAccessPdu(accessPdu);+ }++ /**+ * Parse access pdu+ *+ * @param message underlying message containing the access pdu+ */+ synchronized final void parseAccessLayerPDU(final AccessMessage message) {+ //MSB of the first octet defines the length of opcodes.+ //if MSB = 0 length is 1 and so forth+ final byte[] accessPayload = message.getAccessPdu();+ final int opCodeLength = getOpCodeLength(accessPayload[0] & 0xFF);+ message.setOpCode(getOpCode(accessPayload, opCodeLength));+ final int length = accessPayload.length - opCodeLength;+ final ByteBuffer paramsBuffer = ByteBuffer.allocate(length).order(ByteOrder.BIG_ENDIAN);+ paramsBuffer.put(accessPayload, opCodeLength, length);+ message.setParameters(paramsBuffer.array());+ LOG.info("Received Access PDU " + bytesToHex(accessPayload, false));+ }+}\ No newline at end of filediff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/AccessMessage.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/AccessMessage.javanew file mode 100644index 000000000..375ef79ce--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/AccessMessage.java@@ -0,0 +1,54 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import java.util.HashMap;+import java.util.Map;+import java.util.UUID;++public final class AccessMessage extends Message {++ private UUID label; // Label UUID for destination address+ protected Map<Integer, byte[]> lowerTransportAccessPdu = new HashMap<>();+ private byte[] accessPdu;+ private byte[] transportPdu;++ public AccessMessage() {+ this.ctl = 0;+ }++ @Override+ public int getCtl() {+ return ctl;+ }++ public UUID getLabel() {+ return label;+ }++ public void setLabel(final UUID label) {+ this.label = label;+ }++ public final byte[] getAccessPdu() {+ return accessPdu;+ }++ public final void setAccessPdu(final byte[] accessPdu) {+ this.accessPdu = accessPdu;+ }++ public final byte[] getUpperTransportPdu() {+ return transportPdu;+ }++ public final void setUpperTransportPdu(final byte[] transportPdu) {+ this.transportPdu = transportPdu;+ }++ public final Map<Integer, byte[]> getLowerTransportAccessPdu() {+ return lowerTransportAccessPdu;+ }++ public final void setLowerTransportAccessPdu(final Map<Integer, byte[]> lowerTransportAccessPdu) {+ this.lowerTransportAccessPdu = lowerTransportAccessPdu;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/BaseMeshMessageHandler.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/BaseMeshMessageHandler.javanew file mode 100644index 000000000..6bdafb0c4--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/BaseMeshMessageHandler.java@@ -0,0 +1,321 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.bouncycastle.crypto.InvalidCipherTextException;+import org.openremote.agent.protocol.bluetooth.mesh.InternalTransportCallbacks;+import org.openremote.agent.protocol.bluetooth.mesh.MeshManagerApi;+import org.openremote.agent.protocol.bluetooth.mesh.MeshNetwork;+import org.openremote.agent.protocol.bluetooth.mesh.MeshStatusCallbacks;+import org.openremote.agent.protocol.bluetooth.mesh.NetworkKey;+import org.openremote.agent.protocol.bluetooth.mesh.utils.ExtendedInvalidCipherTextException;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;+import org.openremote.agent.protocol.bluetooth.mesh.utils.SecureUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.UUID;+import java.util.logging.Logger;++import static org.openremote.agent.protocol.bluetooth.mesh.transport.NetworkLayer.createNetworkNonce;+import static org.openremote.agent.protocol.bluetooth.mesh.transport.NetworkLayer.createProxyNonce;+import static org.openremote.agent.protocol.bluetooth.mesh.transport.NetworkLayer.deObfuscateNetworkHeader;++/**+ * Abstract class that handles mesh messages+ */+public abstract class BaseMeshMessageHandler implements MeshMessageHandlerApi, InternalMeshMsgHandlerCallbacks {++ public static final Logger LOG = Logger.getLogger(BaseMeshMessageHandler.class.getName());++ protected final InternalTransportCallbacks mInternalTransportCallbacks;+ private final NetworkLayerCallbacks networkLayerCallbacks;+ private final UpperTransportLayerCallbacks upperTransportLayerCallbacks;+ protected MeshStatusCallbacks mStatusCallbacks;+ private final Map<Integer, MeshTransport> transportSparseArray = new HashMap<>();+ private final Map<Integer, MeshMessageState> stateSparseArray = new HashMap<>();++ /**+ * Constructs BaseMessageHandler+ *+ * @param internalTransportCallbacks {@link InternalTransportCallbacks} Callbacks+ * @param networkLayerCallbacks {@link NetworkLayerCallbacks} network layer callbacks+ * @param upperTransportLayerCallbacks {@link UpperTransportLayerCallbacks} upper transport layer callbacks+ */+ protected BaseMeshMessageHandler(final InternalTransportCallbacks internalTransportCallbacks,+ final NetworkLayerCallbacks networkLayerCallbacks,+ final UpperTransportLayerCallbacks upperTransportLayerCallbacks) {+ this.mInternalTransportCallbacks = internalTransportCallbacks;+ this.networkLayerCallbacks = networkLayerCallbacks;+ this.upperTransportLayerCallbacks = upperTransportLayerCallbacks;+ }++ /**+ * Sets the mesh status callbacks.+ *+ * @param statusCallbacks {@link MeshStatusCallbacks} callbacks+ */+ protected abstract void setMeshStatusCallbacks(final MeshStatusCallbacks statusCallbacks);++ /**+ * Parse the mesh network/proxy pdus+ * <p>+ * This method will try to network layer de-obfuscation and decryption using the available network keys+ * </p>+ *+ * @param pdu mesh pdu that was sent+ * @param network {@link MeshNetwork}+ */+ protected synchronized void parseMeshPduNotifications(final byte[] pdu, final MeshNetwork network) throws ExtendedInvalidCipherTextException {+ final List<NetworkKey> networkKeys = network.getNetKeys();+ final int ivi = ((pdu[1] & 0xFF) >>> 7) & 0x01;+ final int nid = pdu[1] & 0x7F;+ final int acceptedIvIndex = network.getIvIndex().getIvIndex();+ int ivIndex = acceptedIvIndex == 0 ? 0 : acceptedIvIndex - 1;+ NetworkKey networkKey;+ SecureUtils.K2Output k2Output;+ byte[] networkHeader;+ int ctlTtl;+ int ctl;+ int ttl;+ // while (ivIndex <= ivIndex + 1) {+ {+ ivIndex = 0;+ //Here we go through all the network keys and filter out network keys based on the nid.+ for (int i = 0; i < networkKeys.size(); i++) {+ networkKey = networkKeys.get(i);+ k2Output = getMatchingK2Output(networkKey, nid);+ if (k2Output != null) {+ networkHeader = deObfuscateNetworkHeader(pdu, MeshParserUtils.intToBytes(ivIndex), k2Output.getPrivacyKey());+ ctlTtl = networkHeader[0];+ ctl = (ctlTtl >> 7) & 0x01;+ ttl = ctlTtl & 0x7F;+ LOG.info("ivIndex=" + ivIndex + "i(keyIndex)=" + i);+ LOG.info("TTL for received message: " + ttl);+ final int src = MeshParserUtils.unsignedBytesToInt(networkHeader[5], networkHeader[4]);+ LOG.info("Source address of received message: " + src);+ final ProvisionedMeshNode node = network.getNode(src);+ if (node == null) {+ LOG.warning("Couldn't find a node for source address: " + src);+ continue;+ }+ final byte[] sequenceNumber = ByteBuffer.allocate(3).order(ByteOrder.BIG_ENDIAN).put(networkHeader, 1, 3).array();+ LOG.info("Sequence number of received access message: " + MeshParserUtils.convert24BitsToInt(sequenceNumber));+ //TODO validate ivi+ byte[] nonce;+ try {+ final int networkPayloadLength = pdu.length - (2 + networkHeader.length);+ final byte[] transportPdu = new byte[networkPayloadLength];+ System.arraycopy(pdu, 8, transportPdu, 0, networkPayloadLength);+ final byte[] decryptedPayload;+ final MeshMessageState state;+ if (pdu[0] == MeshManagerApi.PDU_TYPE_NETWORK) {+ nonce = createNetworkNonce((byte) ctlTtl, sequenceNumber, src, MeshParserUtils.intToBytes(ivIndex));+ decryptedPayload = SecureUtils.decryptCCM(transportPdu, k2Output.getEncryptionKey(), nonce, SecureUtils.getNetMicLength(ctl));+ state = getState(src);+ } else {+ nonce = createProxyNonce(sequenceNumber, src, MeshParserUtils.intToBytes(ivIndex));+ decryptedPayload = SecureUtils.decryptCCM(transportPdu, k2Output.getEncryptionKey(), nonce, SecureUtils.getNetMicLength(ctl));+ state = getState(MeshAddress.UNASSIGNED_ADDRESS);+ }+ if (state != null) {+ //TODO look in to proxy filter messages+ ((DefaultNoOperationMessageState) state).parseMeshPdu(networkKey, node, pdu, networkHeader, decryptedPayload, ivIndex, sequenceNumber);+ return;+ }+ } catch (InvalidCipherTextException ex) {+ if (i == networkKeys.size() - 1) {+ throw new ExtendedInvalidCipherTextException(ex.getMessage(), ex.getCause(), BaseMeshMessageHandler.class.getName());+ }+ }+ }+ }+ ivIndex++;+ }+ }++ /**+ * Returns the K2output for a given Network Key matching the received NID+ *+ * @param networkKey NetworkKey+ * @param nid NID+ * @return {@link SecureUtils.K2Output} or null if the NID doesn't match.+ */+ private SecureUtils.K2Output getMatchingK2Output(final NetworkKey networkKey, final int nid) {+ if(nid == networkKey.getDerivatives().getNid())+ return networkKey.getDerivatives();+ else if(networkKey.getOldDerivatives() != null && nid == networkKey.getOldDerivatives().getNid())+ return networkKey.getOldDerivatives();+ return null;+ }++ @Override+ public synchronized final void onIncompleteTimerExpired(final int address) {+ //We switch no operation state if the incomplete timer has expired so that we don't wait on the same state if a particular message fails.+ stateSparseArray.put(address, toggleState(getTransport(address), getState(address).getMeshMessage()));+ }++ /**+ * Toggles the current state to default state of a node+ *+ * @param transport mesh transport of the current state+ * @param meshMessage Mesh message+ */+ private DefaultNoOperationMessageState toggleState(final MeshTransport transport, /* @Nullable */ final MeshMessage meshMessage) {+ final DefaultNoOperationMessageState state = new DefaultNoOperationMessageState(meshMessage, transport, this);+ state.setTransportCallbacks(mInternalTransportCallbacks);+ state.setStatusCallbacks(mStatusCallbacks);+ return state;+ }++ /**+ * Returns the existing state or a new state if nothing exists for a node+ *+ * @param address address of the node+ */+ protected synchronized MeshMessageState getState(final int address) {+ MeshMessageState state = stateSparseArray.get(address);+ if (state == null) {+ state = new DefaultNoOperationMessageState(null, getTransport(address), this);+ state.setTransportCallbacks(mInternalTransportCallbacks);+ state.setStatusCallbacks(mStatusCallbacks);+ stateSparseArray.put(address, state);+ }+ return state;+ }++ /**+ * Returns the existing transport of the node or a new transport if nothing exists+ *+ * @param address address of the node+ */+ private MeshTransport getTransport(final int address) {+ MeshTransport transport = transportSparseArray.get(address);+ if (transport == null) {+ transport = new MeshTransport();+ transport.setNetworkLayerCallbacks(networkLayerCallbacks);+ transport.setUpperTransportLayerCallbacks(upperTransportLayerCallbacks);+ transportSparseArray.put(address, transport);+ }+ return transport;+ }++ /**+ * Resets the state and transport for a given node address+ *+ * @param address unicast address of the node+ */+ public synchronized void resetState(final int address) {+ stateSparseArray.remove(address);+ transportSparseArray.remove(address);+ }++ @Override+ public synchronized void createMeshMessage(final int src, final int dst, final UUID label, final MeshMessage meshMessage) {+ if (meshMessage instanceof ProxyConfigMessage) {+ createProxyConfigMeshMessage(src, dst, (ProxyConfigMessage) meshMessage);+ } else if (meshMessage instanceof ConfigMessage) {+ createConfigMeshMessage(src, dst, (ConfigMessage) meshMessage);+ } else if (meshMessage instanceof GenericMessage) {+ if (label == null) {+ createAppMeshMessage(src, dst, (GenericMessage) meshMessage);+ } else {+ createAppMeshMessage(src, dst, label, (GenericMessage) meshMessage);+ }+ }+ }++ /**+ * Sends a mesh message specified within the {@link MeshMessage} object+ *+ * @param configurationMessage {@link ProxyConfigMessage} Mesh message containing the message opcode and message parameters+ */+ private void createProxyConfigMeshMessage(final int src, final int dst, final ProxyConfigMessage configurationMessage) {+ final ProxyConfigMessageState currentState = new ProxyConfigMessageState(src, dst, configurationMessage, getTransport(dst), this);+ currentState.setTransportCallbacks(mInternalTransportCallbacks);+ currentState.setStatusCallbacks(mStatusCallbacks);+ stateSparseArray.put(dst, toggleState(currentState.getMeshTransport(), configurationMessage));+ currentState.executeSend();+ }++ /**+ * Sends a mesh message specified within the {@link MeshMessage} object+ *+ * @param configurationMessage {@link ConfigMessage} Mesh message containing the message opcode and message parameters+ */+ private void createConfigMeshMessage(final int src, final int dst, final ConfigMessage configurationMessage) {+ final ProvisionedMeshNode node = mInternalTransportCallbacks.getNode(dst);+ if (node == null) {+ return;+ }++ final ConfigMessageState currentState = new ConfigMessageState(src, dst, node.getDeviceKey(), configurationMessage, getTransport(dst), this);+ currentState.setTransportCallbacks(mInternalTransportCallbacks);+ currentState.setStatusCallbacks(mStatusCallbacks);+ if (MeshAddress.isValidUnicastAddress(dst)) {+ stateSparseArray.put(dst, toggleState(getTransport(dst), configurationMessage));+ }+ currentState.executeSend();+ }++ /**+ * Sends a mesh message specified within the {@link GenericMessage} object+ * <p> This method can be used specifically when sending an application message with a unicast address or a group address.+ * Application messages currently supported in the library are {@link GenericOnOffGet},{@link GenericOnOffSet}, {@link GenericOnOffSetUnacknowledged},+ * {@link GenericLevelGet}, {@link GenericLevelSet}, {@link GenericLevelSetUnacknowledged},+ * {@link VendorModelMessageAcked} and {@link VendorModelMessageUnacked}</p>+ *+ * @param src source address where the message is originating from+ * @param dst Destination to which the message must be sent to, this could be a unicast address or a group address.+ * @param genericMessage Mesh message containing the message opcode and message parameters.+ */+ private void createAppMeshMessage(final int src, final int dst, final GenericMessage genericMessage) {+ final GenericMessageState currentState;+ if (genericMessage instanceof VendorModelMessageAcked) {+ currentState = new VendorModelMessageAckedState(src, dst, (VendorModelMessageAcked) genericMessage, getTransport(dst), this);+ } else if (genericMessage instanceof VendorModelMessageUnacked) {+ currentState = new VendorModelMessageUnackedState(src, dst, (VendorModelMessageUnacked) genericMessage, getTransport(dst), this);+ } else {+ currentState = new GenericMessageState(src, dst, genericMessage, getTransport(dst), this);+ }+ currentState.setTransportCallbacks(mInternalTransportCallbacks);+ currentState.setStatusCallbacks(mStatusCallbacks);+ if (MeshAddress.isValidUnicastAddress(dst)) {+ stateSparseArray.put(dst, toggleState(getTransport(dst), genericMessage));+ }+ currentState.executeSend();+ }+++ /**+ * Sends a mesh message specified within the {@link GenericMessage} object+ * <p> This method can be used specifically when sending an application message with a unicast address or a group address.+ * Application messages currently supported in the library are {@link GenericOnOffGet},{@link GenericOnOffSet}, {@link GenericOnOffSetUnacknowledged},+ * {@link GenericLevelGet}, {@link GenericLevelSet}, {@link GenericLevelSetUnacknowledged},+ * {@link VendorModelMessageAcked} and {@link VendorModelMessageUnacked}</p>+ *+ * @param src source address where the message is originating from+ * @param dst Destination to which the message must be sent to, this could be a unicast address or a group address.+ * @param label Label UUID of destination address+ * @param genericMessage Mesh message containing the message opcode and message parameters.+ */+ private void createAppMeshMessage(final int src, final int dst, UUID label, final GenericMessage genericMessage) {+ final GenericMessageState currentState;+ if (genericMessage instanceof VendorModelMessageAcked) {+ currentState = new VendorModelMessageAckedState(src, dst, label, (VendorModelMessageAcked) genericMessage, getTransport(dst), this);+ } else if (genericMessage instanceof VendorModelMessageUnacked) {+ currentState = new VendorModelMessageUnackedState(src, dst, label, (VendorModelMessageUnacked) genericMessage, getTransport(dst), this);+ } else {+ currentState = new GenericMessageState(src, dst, label, genericMessage, getTransport(dst), this);+ }+ currentState.setTransportCallbacks(mInternalTransportCallbacks);+ currentState.setStatusCallbacks(mStatusCallbacks);+ if (MeshAddress.isValidUnicastAddress(dst)) {+ stateSparseArray.put(dst, toggleState(getTransport(dst), genericMessage));+ }+ currentState.executeSend();+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigAppKeyAdd.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigAppKeyAdd.javanew file mode 100644index 000000000..e00d9dcb5--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigAppKeyAdd.java@@ -0,0 +1,80 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.ApplicationKey;+import org.openremote.agent.protocol.bluetooth.mesh.NetworkKey;+import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++/**+ * To be used as a wrapper class to create the ConfigAppKeyAdd message.+ */+public class ConfigAppKeyAdd extends ConfigMessage {++ public static final Logger LOG = Logger.getLogger(ConfigAppKeyAdd.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_APPKEY_ADD;++ private final NetworkKey mNetKey;+ private final ApplicationKey mAppKey;++ /**+ * Constructs ConfigAppKeyAdd message.+ *+ * @param appKey application key for this message+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public ConfigAppKeyAdd(final NetworkKey networkKey, final ApplicationKey appKey) throws IllegalArgumentException {+ if (networkKey.getKey().length != 16)+ throw new IllegalArgumentException("Network key must be 16 bytes");++ if (appKey.getKey().length != 16)+ throw new IllegalArgumentException("App key must be 16 bytes");++ this.mNetKey = networkKey;+ this.mAppKey = appKey;+ assembleMessageParameters();+ }++ /**+ * Returns the Network key that is needs to be sent to the node+ *+ * @return app key+ */+ public NetworkKey getNetKey() {+ return mNetKey;+ }++ /**+ * Returns the application key that is needs to be sent to the node+ *+ * @return app key+ */+ public ApplicationKey getAppKey() {+ return mAppKey;+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }+++ @Override+ void assembleMessageParameters() {+ LOG.info("NetKeyIndex: " + mNetKey.getKeyIndex());+ LOG.info("AppKeyIndex: " + mAppKey.getKeyIndex());+ final byte[] netKeyIndex = MeshParserUtils.addKeyIndexPadding(mNetKey.getKeyIndex());+ final byte[] appKeyIndex = MeshParserUtils.addKeyIndexPadding(mAppKey.getKeyIndex());+ final ByteBuffer paramsBuffer = ByteBuffer.allocate(19).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.put(netKeyIndex[1]);+ paramsBuffer.put((byte) (((appKeyIndex[1] & 0xFF) << 4) | (netKeyIndex[0] & 0xFF) & 0x0F));+ paramsBuffer.put((byte) (((appKeyIndex[0] & 0xFF) << 4) | (appKeyIndex[1] & 0xFF) >> 4));+ paramsBuffer.put(mAppKey.getKey());++ mParameters = paramsBuffer.array();+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigAppKeyDelete.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigAppKeyDelete.javanew file mode 100644index 000000000..91dd497ab--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigAppKeyDelete.java@@ -0,0 +1,79 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.ApplicationKey;+import org.openremote.agent.protocol.bluetooth.mesh.NetworkKey;+import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++/**+ * To be used as a wrapper class to create the ConfigAppKeyAdd message.+ */+public class ConfigAppKeyDelete extends ConfigMessage {++ public static final Logger LOG = Logger.getLogger(ConfigAppKeyDelete.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_APPKEY_DELETE;++ private final NetworkKey mNetKey;+ private final ApplicationKey mAppKey;++ /**+ * Constructs ConfigAppKeyAdd message.+ *+ * @param appKey application key for this message+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public ConfigAppKeyDelete(final NetworkKey networkKey, final ApplicationKey appKey) throws IllegalArgumentException {+ if (networkKey.getKey().length != 16)+ throw new IllegalArgumentException("Network key must be 16 bytes");++ if (appKey.getKey().length != 16)+ throw new IllegalArgumentException("App key must be 16 bytes");++ this.mNetKey = networkKey;+ this.mAppKey = appKey;+ assembleMessageParameters();+ }++ /**+ * Returns the Network key that is needs to be sent to the node+ *+ * @return app key+ */+ public NetworkKey getNetKey() {+ return mNetKey;+ }++ /**+ * Returns the application key that is needs to be sent to the node+ *+ * @return app key+ */+ public ApplicationKey getAppKey() {+ return mAppKey;+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }+++ @Override+ void assembleMessageParameters() {+ LOG.info("NetKeyIndex: " + mNetKey.getKeyIndex());+ LOG.info("AppKeyIndex: " + mAppKey.getKeyIndex());+ final byte[] netKeyIndex = MeshParserUtils.addKeyIndexPadding(mNetKey.getKeyIndex());+ final byte[] appKeyIndex = MeshParserUtils.addKeyIndexPadding(mAppKey.getKeyIndex());++ final ByteBuffer paramsBuffer = ByteBuffer.allocate(3).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.put(netKeyIndex[1]);+ paramsBuffer.put((byte) (((appKeyIndex[1] & 0xFF) << 4) | (netKeyIndex[0] & 0xFF) & 0x0F));+ paramsBuffer.put((byte) (((appKeyIndex[0] & 0xFF) << 4) | (appKeyIndex[1] & 0xFF) >> 4));+ mParameters = paramsBuffer.array();+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigAppKeyList.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigAppKeyList.javanew file mode 100644index 000000000..e7d9c50f3--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigAppKeyList.java@@ -0,0 +1,71 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;++import java.util.ArrayList;+import java.util.List;+import java.util.logging.Logger;++/**+ * Creates the ConfigAppKeyList Message.+ */+public class ConfigAppKeyList extends ConfigStatusMessage {++ public static final Logger LOG = Logger.getLogger(ConfigAppKeyList.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_APPKEY_LIST;+ private int mNetKeyIndex;+ private final List<Integer> mKeyIndexes;++ /**+ * Constructs the ConfigNetKeyList mMessage.+ *+ * @param message Access Message+ */+ public ConfigAppKeyList(final AccessMessage message) {+ super(message);+ mKeyIndexes = new ArrayList<>();+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ final void parseStatusParameters() {+ mStatusCode = mParameters[0];+ mStatusCodeName = getStatusCodeName(mStatusCode);+ mNetKeyIndex = decode(3, 1).get(0);+ LOG.info("NetKey Index: " + Integer.toHexString(mNetKeyIndex));+ mKeyIndexes.addAll(decode(mParameters.length, 3));+ for (Integer keyIndex : mKeyIndexes) {+ LOG.info("AppKey Index: " + Integer.toHexString(keyIndex));+ }+ }++ @Override+ public final int getOpCode() {+ return OP_CODE;+ }++ /**+ * Returns if the message was successful+ *+ * @return true if the message was successful or false otherwise+ */+ public final boolean isSuccessful() {+ return mStatusCode == 0x00;+ }++ /**+ * Returns the NetKey index to which the app keys are bound+ */+ public int getNetKeyIndex() {+ return mNetKeyIndex;+ }++ /**+ * Returns the bound app key indexes+ */+ public List<Integer> getKeyIndexes() {+ return mKeyIndexes;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigAppKeyStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigAppKeyStatus.javanew file mode 100644index 000000000..6053c96ee--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigAppKeyStatus.java@@ -0,0 +1,76 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;++import java.util.ArrayList;+import java.util.logging.Logger;++/**+ * To be used as a wrapper class for when creating the ConfigAppKeyStatus Message.+ */+public class ConfigAppKeyStatus extends ConfigStatusMessage {++ public static final Logger LOG = Logger.getLogger(ConfigAppKeyStatus.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_APPKEY_STATUS;+ private int mNetKeyIndex;+ private int mAppKeyIndex;++ /**+ * Constructs the ConfigAppKeyStatus mMessage.+ *+ * @param message Access Message+ */+ public ConfigAppKeyStatus(final AccessMessage message) {+ super(message);+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ final void parseStatusParameters() {+ mStatusCode = mParameters[0];+ mStatusCodeName = getStatusCodeName(mStatusCode);++ final ArrayList<Integer> keyIndexes = decode(mParameters.length, 1);+ mNetKeyIndex = keyIndexes.get(0);+ mAppKeyIndex = keyIndexes.get(1);++ LOG.info("Status code: " + mStatusCode);+ LOG.info("Status message: " + mStatusCodeName);+ LOG.info("Net key index: " + Integer.toHexString(mNetKeyIndex));+ LOG.info("App key index: " + Integer.toHexString(mAppKeyIndex));+ }++ @Override+ public final int getOpCode() {+ return OP_CODE;+ }++ /**+ * Returns the global index of the net key.+ *+ * @return netkey index+ */+ public final int getNetKeyIndex() {+ return mNetKeyIndex;+ }++ /**+ * Returns the global app key index.+ *+ * @return appkey index+ */+ public final int getAppKeyIndex() {+ return mAppKeyIndex;+ }++ /**+ * Returns if the message was successful+ *+ * @return true if the message was successful or false otherwise+ */+ public final boolean isSuccessful() {+ return mStatusCode == 0x00;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigAppKeyUpdate.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigAppKeyUpdate.javanew file mode 100644index 000000000..2ca330288--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigAppKeyUpdate.java@@ -0,0 +1,64 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.ApplicationKey;+import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++/**+ * Creates the ConfigAppKeyUpdate message.+ */+public class ConfigAppKeyUpdate extends ConfigMessage {++ public static final Logger LOG = Logger.getLogger(ConfigAppKeyUpdate.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_APPKEY_UPDATE;++ private final ApplicationKey mAppKey;++ /**+ * Constructs ConfigAppKeyUpdate message.+ *+ * @param appKey application key for this message+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public ConfigAppKeyUpdate(final ApplicationKey appKey) throws IllegalArgumentException {+ if (appKey.getKey().length != 16)+ throw new IllegalArgumentException("App key must be 16 bytes");++ this.mAppKey = appKey;+ assembleMessageParameters();+ }++ /**+ * Returns the application key that is needs to be sent to the node+ *+ * @return app key+ */+ public ApplicationKey getAppKey() {+ return mAppKey;+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }+++ @Override+ void assembleMessageParameters() {+ LOG.info("NetKeyIndex: " + mAppKey.getBoundNetKeyIndex());+ LOG.info("AppKeyIndex: " + mAppKey.getKeyIndex());+ final byte[] netKeyIndex = MeshParserUtils.addKeyIndexPadding(mAppKey.getBoundNetKeyIndex());+ final byte[] appKeyIndex = MeshParserUtils.addKeyIndexPadding(mAppKey.getKeyIndex());+ final ByteBuffer paramsBuffer = ByteBuffer.allocate(19).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.put(netKeyIndex[1]);+ paramsBuffer.put((byte) (((appKeyIndex[1] & 0xFF) << 4) | (netKeyIndex[0] & 0xFF) & 0x0F));+ paramsBuffer.put((byte) (((appKeyIndex[0] & 0xFF) << 4) | (appKeyIndex[1] & 0xFF) >> 4));+ paramsBuffer.put(mAppKey.getKey());++ mParameters = paramsBuffer.array();+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigBeaconStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigBeaconStatus.javanew file mode 100644index 000000000..c6b7564f2--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigBeaconStatus.java@@ -0,0 +1,47 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.util.logging.Logger;++/**+ * Creates the ConfigBeaconStatus message.+ */+public class ConfigBeaconStatus extends ConfigStatusMessage {++ public static final Logger LOG = Logger.getLogger(ConfigBeaconStatus.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_BEACON_STATUS;++ private boolean enable;++ /**+ * Constructs ConfigBeaconStatus message.+ *+ * @param message {@link AccessMessage}+ */+ public ConfigBeaconStatus(final AccessMessage message) {+ super(message);+ mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ void parseStatusParameters() {+ enable = MeshParserUtils.unsignedByteToInt(mParameters[0]) == ProvisionedBaseMeshNode.ENABLED;+ LOG.info("Secure Network Beacon State: " + enable);+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ /**+ * Returns the true if the Secure Network beacon State is set to send periodic Secure Network Beacons or false otherwise.+ */+ public boolean isEnable() {+ return enable;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigCompositionDataStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigCompositionDataStatus.javanew file mode 100644index 000000000..b6be9f7b4--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigCompositionDataStatus.java@@ -0,0 +1,275 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.models.SigModelParser;+import org.openremote.agent.protocol.bluetooth.mesh.models.VendorModel;+import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.DeviceFeatureUtils;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.LinkedHashMap;+import java.util.Locale;+import java.util.Map;+import java.util.logging.Logger;++/**+ * To be used as a wrapper class for when creating the ConfigCompositionDataStatus Message.+ */+public class ConfigCompositionDataStatus extends ConfigStatusMessage{++ public static final Logger LOG = Logger.getLogger(ConfigCompositionDataStatus.class.getName());++ private static final String TAG = ConfigCompositionDataStatus.class.getSimpleName();+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_COMPOSITION_DATA_STATUS;+ private static final int ELEMENTS_OFFSET = 12;+ private int companyIdentifier;+ private int productIdentifier;+ private int versionIdentifier;+ private int crpl;+ private int features;+ private boolean relayFeatureSupported;+ private boolean proxyFeatureSupported;+ private boolean friendFeatureSupported;+ private boolean lowPowerFeatureSupported;+ private Map<Integer, Element> mElements = new LinkedHashMap<>();++ /**+ * Constructs the ConfigCompositionDataStatus mMessage.+ *+ * @param message Access Message+ */+ public ConfigCompositionDataStatus(final AccessMessage message) {+ super(message);+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ final void parseStatusParameters() {+ parseCompositionDataPages();+ }++ /**+ * Parses composition data status received from the mesh node+ */+ private void parseCompositionDataPages() {+ final AccessMessage message = (AccessMessage) mMessage;+ final byte[] accessPayload = message.getAccessPdu();++ //Bluetooth SIG 16-bit company identifier+ companyIdentifier = MeshParserUtils.unsignedBytesToInt(accessPayload[2], accessPayload[3]);+ LOG.info("Company identifier: " + String.format(Locale.US, "%04X", companyIdentifier));++ //16-bit vendor-assigned product identifier;+ productIdentifier = MeshParserUtils.unsignedBytesToInt(accessPayload[4], accessPayload[5]);+ LOG.info("Product identifier: " + String.format(Locale.US, "%04X", productIdentifier));++ //16-bit vendor-assigned product version identifier;+ versionIdentifier = MeshParserUtils.unsignedBytesToInt(accessPayload[6], accessPayload[7]);+ LOG.info("Version identifier: " + String.format(Locale.US, "%04X", versionIdentifier));++ //16-bit representation of the minimum number of replay protection list entries in a device+ crpl = MeshParserUtils.unsignedBytesToInt(accessPayload[8], accessPayload[9]);+ LOG.info("crpl: " + String.format(Locale.US, "%04X", crpl));++ //16-bit device features+ features = MeshParserUtils.unsignedBytesToInt(accessPayload[10], accessPayload[11]);+ LOG.info("Features: " + String.format(Locale.US, "%04X", features));++ relayFeatureSupported = DeviceFeatureUtils.supportsRelayFeature(features);+ LOG.info("Relay feature: " + relayFeatureSupported);++ proxyFeatureSupported = DeviceFeatureUtils.supportsProxyFeature(features);+ LOG.info("Proxy feature: " + proxyFeatureSupported);++ friendFeatureSupported = DeviceFeatureUtils.supportsFriendFeature(features);+ LOG.info("Friend feature: " + friendFeatureSupported);++ lowPowerFeatureSupported = DeviceFeatureUtils.supportsLowPowerFeature(features);+ LOG.info("Low power feature: " + lowPowerFeatureSupported);++ // Parsing the elements which is a variable number of octets+ // Elements contain following+ // location descriptor,+ // Number of SIG model IDs in this element+ // Number of vendor model in this element+ // SIG model ID octents - Variable+ // Vendor model ID octents - Variable+ parseElements(accessPayload, message.getSrc());+ LOG.info("Number of elements: " + mElements.size());+ }++ /**+ * Parses the elements within the composition data status+ *+ * @param accessPayload underlying payload containing the elements+ * @param src source address+ */+ private void parseElements(final byte[] accessPayload, final int src) {+ int tempOffset = ELEMENTS_OFFSET;+ int counter = 0;+ int elementAddress = 0;+ while (tempOffset < accessPayload.length) {+ final Map<Integer, MeshModel> models = new LinkedHashMap<>();+ final int locationDescriptor = accessPayload[tempOffset + 1] << 8 | accessPayload[tempOffset];+ LOG.info("Location identifier: " + String.format(Locale.US, "%04X", locationDescriptor));++ tempOffset = tempOffset + 2;+ final int numSigModelIds = accessPayload[tempOffset];+ LOG.info("Number of sig models: " + String.format(Locale.US, "%04X", numSigModelIds));++ tempOffset = tempOffset + 1;+ final int numVendorModelIds = accessPayload[tempOffset];+ LOG.info("Number of vendor models: " + String.format(Locale.US, "%04X", numVendorModelIds));++ tempOffset = tempOffset + 1;+ if (numSigModelIds > 0) {+ for (int i = 0; i < numSigModelIds; i++) {+ final int modelId = MeshParserUtils.unsignedBytesToInt(accessPayload[tempOffset], accessPayload[tempOffset + 1]);+ models.put(modelId, SigModelParser.getSigModel(modelId)); // sig models are 16-bit+ LOG.info("Sig model ID " + i + " : " + String.format(Locale.US, "%04X", modelId));+ tempOffset = tempOffset + 2;+ }+ }++ if (numVendorModelIds > 0) {+ for (int i = 0; i < numVendorModelIds; i++) {+ // vendor models are 32-bit that contains a 16-bit company identifier and a 16-bit model identifier+ final int companyIdentifier = MeshParserUtils.unsignedBytesToInt(accessPayload[tempOffset], accessPayload[tempOffset + 1]);+ final int modelIdentifier = MeshParserUtils.unsignedBytesToInt(accessPayload[tempOffset + 2], accessPayload[tempOffset + 3]);+ final int vendorModelIdentifier = companyIdentifier << 16 | modelIdentifier;+ models.put(vendorModelIdentifier, new VendorModel(vendorModelIdentifier));+ LOG.info("Vendor - model ID " + i + " : " + String.format(Locale.US, "%08X", vendorModelIdentifier));+ tempOffset = tempOffset + 4;+ }+ }++ if (counter == 0) {+ elementAddress = src;+ } else {+ elementAddress++;+ }+ counter++;+ final Element element = new Element(elementAddress, locationDescriptor, models);+ final int unicastAddress = elementAddress;+ mElements.put(unicastAddress, element);+ }+ }++ /**+ * Returns the 16-bit company identifier assigned by Bluetooth SIG.+ *+ * @return company identifier+ */+ public int getCompanyIdentifier() {+ return companyIdentifier;+ }++ /**+ * Returns the 16-bit vendor assigned assigned product identifier.+ *+ * @return product identifier+ */+ public int getProductIdentifier() {+ return productIdentifier;+ }++ /**+ * Returns the 16-bit vendor assigned product version identifier.+ *+ * @return version identifier+ */+ public int getVersionIdentifier() {+ return versionIdentifier;+ }++ /**+ * Returns a 16-bit value representing the minimum number of replay protection list entries in a device.+ *+ * @return crpl+ */+ public int getCrpl() {+ return crpl;+ }++ /**+ * Returns a 16-bit features field indicating the device features.+ *+ * @return features field+ */+ public int getFeatures() {+ return features;+ }++ /**+ * Returns if the relay feature is supported.+ *+ * @return true if relay features is supported or false otherwise+ */+ public boolean isRelayFeatureSupported() {+ return relayFeatureSupported;+ }++ /**+ * Returns if the proxy feature is supported.+ *+ * @return true if proxy feature is supported or false otherwise+ */+ public boolean isProxyFeatureSupported() {+ return proxyFeatureSupported;+ }++ /**+ * Returns if the friend feature is supported.+ *+ * @return true if friend feature is supported or false otherwise+ */+ public boolean isFriendFeatureSupported() {+ return friendFeatureSupported;+ }++ /**+ * Returns if the low power feature is supported.+ *+ * @return true if low power feature is supported or false otherwise+ */+ public boolean isLowPowerFeatureSupported() {+ return lowPowerFeatureSupported;+ }++ /**+ * Returns the number of elements existing in this node.+ *+ * @return number of elements+ */+ public Map<Integer, Element> getElements() {+ return mElements;+ }++ private int parseCompanyIdentifier(final short companyIdentifier) {+ return ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN).putShort(companyIdentifier).getShort(0);+ }++ private int parseProductIdentifier(final short productIdentifier) {+ return ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN).putShort(productIdentifier).getShort(0);+ }++ private int parseVersionIdentifier(final short versionIdentifier) {+ return ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN).putShort(versionIdentifier).getShort(0);+ }++ private int parseCrpl(final short companyIdentifier) {+ return ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN).putShort(companyIdentifier).getShort(0);+ }++ private int parseFeatures(final short companyIdentifier) {+ return ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN).putShort(companyIdentifier).getShort(0);+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigDefaultTtlStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigDefaultTtlStatus.javanew file mode 100644index 000000000..db49dd324--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigDefaultTtlStatus.java@@ -0,0 +1,44 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++/**+ * Creates the ConfigDefaultTtlSet message.+ */+public class ConfigDefaultTtlStatus extends ConfigStatusMessage {++ private static final String TAG = ConfigDefaultTtlStatus.class.getSimpleName();+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_DEFAULT_TTL_STATUS;++ private int mTtl;++ /**+ * Constructs ConfigDefaultTtlStatus message.+ *+ * @param message {@link AccessMessage}+ */+ public ConfigDefaultTtlStatus(final AccessMessage message) {+ super(message);+ mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ void parseStatusParameters() {+ mTtl = MeshParserUtils.unsignedByteToInt(mParameters[0]);+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ /**+ * Returns the ttl value+ */+ public int getTtl() {+ return mTtl;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigFriendStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigFriendStatus.javanew file mode 100644index 000000000..ab7f2137a--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigFriendStatus.java@@ -0,0 +1,47 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.util.logging.Logger;++/**+ * Creates the ConfigFriendStatus message.+ */+public class ConfigFriendStatus extends ConfigStatusMessage {++ public static final Logger LOG = Logger.getLogger(ConfigFriendStatus.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_FRIEND_STATUS;++ private boolean enable;++ /**+ * Constructs ConfigFriendStatus message.+ *+ * @param message {@link AccessMessage}+ */+ public ConfigFriendStatus(final AccessMessage message) {+ super(message);+ mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ void parseStatusParameters() {+ enable = MeshParserUtils.unsignedByteToInt(mParameters[0]) == ProvisionedBaseMeshNode.ENABLED;+ LOG.info("Friend status: " + enable);+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ /**+ * Returns the true if the Friend feature is enabled or not.+ */+ public boolean isEnable() {+ return enable;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigHeartbeatPublicationStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigHeartbeatPublicationStatus.javanew file mode 100644index 000000000..e4a65df72--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigHeartbeatPublicationStatus.java@@ -0,0 +1,72 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.Features;+import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.DeviceFeatureUtils;+import org.openremote.agent.protocol.bluetooth.mesh.utils.HeartbeatPublication;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.util.logging.Logger;++/**+ * ConfigHeartbeatPublicationStatus message.+ */+public class ConfigHeartbeatPublicationStatus extends ConfigStatusMessage {++ public static final Logger LOG = Logger.getLogger(ConfigHeartbeatPublicationStatus.class.getName());++ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_HEARTBEAT_PUBLICATION_STATUS;+ private HeartbeatPublication heartbeatPublication;++ /**+ * Constructs ConfigHeartbeatPublicationStatus message.+ *+ * @param message Message+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public ConfigHeartbeatPublicationStatus(final AccessMessage message) {+ super(message);+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ @Override+ void parseStatusParameters() {+ mStatusCode = mParameters[0];+ mStatusCodeName = getStatusCodeName(mStatusCode);+ final int dst = MeshParserUtils.unsignedBytesToInt(mParameters[1], mParameters[2]);+ final int countLog = MeshParserUtils.unsignedByteToInt(mParameters[3]);+ final int periodLog = MeshParserUtils.unsignedByteToInt(mParameters[4]);+ final int ttl = MeshParserUtils.unsignedByteToInt(mParameters[5]);++ final int featuresInt = MeshParserUtils.unsignedBytesToInt(mParameters[6], mParameters[7]);+ final Features features = new Features(DeviceFeatureUtils.getFriendFeature(featuresInt),+ DeviceFeatureUtils.getLowPowerFeature(featuresInt),+ DeviceFeatureUtils.getProxyFeature(featuresInt),+ DeviceFeatureUtils.getRelayFeature(featuresInt));+ final int netKeyIndex = MeshParserUtils.unsignedBytesToInt((mParameters[8]), mParameters[9]);+ heartbeatPublication = new HeartbeatPublication(dst, (byte) countLog, (byte) periodLog, ttl, features, netKeyIndex);+ LOG.info("Status code: " + mStatusCode);+ LOG.info("Status message: " + mStatusCodeName);+ LOG.info("Heartbeat publication: " + heartbeatPublication.toString());+ }++ /**+ * Returns if the message was successful+ *+ * @return true if the message was successful or false otherwise+ */+ public final boolean isSuccessful() {+ return mStatusCode == 0x00;+ }++ public HeartbeatPublication getHeartbeatPublication() {+ return heartbeatPublication;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigHeartbeatSubscriptionStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigHeartbeatSubscriptionStatus.javanew file mode 100644index 000000000..d277d52bb--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigHeartbeatSubscriptionStatus.java@@ -0,0 +1,69 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.HeartbeatSubscription;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.util.logging.Logger;++/**+ * ConfigHeartbeatPublicationStatus message.+ */+@SuppressWarnings({"WeakerAccess"})+public class ConfigHeartbeatSubscriptionStatus extends ConfigStatusMessage {++ public static final Logger LOG = Logger.getLogger(ConfigHeartbeatSubscriptionStatus.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_HEARTBEAT_SUBSCRIPTION_STATUS;+ private HeartbeatSubscription heartbeatSubscription;++ /**+ * Constructs ConfigHeartbeatSubscriptionStatus message.+ *+ * @param message Message+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public ConfigHeartbeatSubscriptionStatus(final AccessMessage message) {+ super(message);+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ @Override+ void parseStatusParameters() {+ mStatusCode = mParameters[0];+ mStatusCodeName = getStatusCodeName(mStatusCode);+ final int srcAddress = MeshParserUtils.unsignedBytesToInt(mParameters[1], mParameters[2]);+ final int dstAddress = MeshParserUtils.unsignedBytesToInt(mParameters[3], mParameters[4]);+ final int periodLog = MeshParserUtils.unsignedByteToInt(mParameters[5]);+ final int countLog = MeshParserUtils.unsignedByteToInt(mParameters[6]);+ final int minHops = MeshParserUtils.unsignedByteToInt(mParameters[7]);+ final int maxHops = MeshParserUtils.unsignedByteToInt(mParameters[8]);++ heartbeatSubscription = new HeartbeatSubscription(srcAddress, dstAddress, (byte)periodLog, (byte)countLog, minHops, maxHops);+ LOG.info("Status code: " + mStatusCode);+ LOG.info("Status message: " + mStatusCodeName);+ LOG.info("Heartbeat subscription: " + heartbeatSubscription.toString());+ }++ /**+ * Returns the Heartbeat subscription.+ */+ public HeartbeatSubscription getHeartbeatSubscription() {+ return heartbeatSubscription;+ }++ /**+ * Returns if the message was successful+ *+ * @return true if the message was successful or false otherwise+ */+ public final boolean isSuccessful() {+ return mStatusCode == 0x00;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigKeyRefreshPhaseSet.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigKeyRefreshPhaseSet.javanew file mode 100644index 000000000..6894e72cc--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigKeyRefreshPhaseSet.java@@ -0,0 +1,44 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.NetworkKey;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.util.logging.Logger;++import static org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes.CONFIG_KEY_REFRESH_PHASE_SET;++/**+ * Creates the ConfigKeyRefreshPhaseSet message.+ */+public class ConfigKeyRefreshPhaseSet extends ConfigMessage {++ public static final Logger LOG = Logger.getLogger(ConfigKeyRefreshPhaseSet.class.getName());+ private static final int OP_CODE = CONFIG_KEY_REFRESH_PHASE_SET;+ private final NetworkKey mNetKey;+ private final /* @KeyRefreshPhaseTransition */+ int transition;++ /**+ * Constructs ConfigKeyRefreshPhaseSet message.+ *+ * @param networkKey {@link NetworkKey}+ */+ public ConfigKeyRefreshPhaseSet(final NetworkKey networkKey, /* @KeyRefreshPhaseTransition */ final int transition) {+ mNetKey = networkKey;+ this.transition = transition;+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ @Override+ void assembleMessageParameters() {+ LOG.info("NetKeyIndex: " + mNetKey.getKeyIndex());+ final byte[] netKeyIndex = MeshParserUtils.addKeyIndexPadding(mNetKey.getKeyIndex());+ mParameters = new byte[]{netKeyIndex[1], (byte) ((netKeyIndex[0] & 0xFF) & 0x0F), (byte) transition};+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigKeyRefreshPhaseStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigKeyRefreshPhaseStatus.javanew file mode 100644index 000000000..17770d08b--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigKeyRefreshPhaseStatus.java@@ -0,0 +1,78 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import java.util.ArrayList;+import java.util.logging.Logger;++// import static org.openremote.agent.protocol.bluetooth.mesh.NetworkKey.KeyRefreshPhase;+// import static org.openremote.agent.protocol.bluetooth.mesh.NetworkKey.KeyRefreshPhaseTransition;+import static org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes.CONFIG_KEY_REFRESH_PHASE_STATUS;+++/**+ * To be used as a wrapper class for when creating the ConfigAppKeyStatus Message.+ */+public class ConfigKeyRefreshPhaseStatus extends ConfigStatusMessage {++ public static final Logger LOG = Logger.getLogger(ConfigKeyRefreshPhaseStatus.class.getName());+ private static final int OP_CODE = CONFIG_KEY_REFRESH_PHASE_STATUS;+ private int mNetKeyIndex;+ private /* @KeyRefreshPhase */ int transition;++ /**+ * Constructs the ConfigAppKeyStatus mMessage.+ *+ * @param message Access Message+ */+ public ConfigKeyRefreshPhaseStatus(final AccessMessage message) {+ super(message);+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ final void parseStatusParameters() {+ mStatusCode = mParameters[0];+ mStatusCodeName = getStatusCodeName(mStatusCode);++ final ArrayList<Integer> keyIndexes = decode(mParameters.length, 1);+ mNetKeyIndex = keyIndexes.get(0);+ transition = mParameters[3];++ LOG.info("Status code: " + mStatusCode);+ LOG.info("Status message: " + mStatusCodeName);+ LOG.info("Net key index: " + Integer.toHexString(mNetKeyIndex));+ LOG.info("Transition: " + transition);+ }++ @Override+ public final int getOpCode() {+ return OP_CODE;+ }++ /**+ * Returns the global index of the net key.+ *+ * @return netkey index+ */+ public final int getNetKeyIndex() {+ return mNetKeyIndex;+ }++ /**+ * Returns the current key refresh phase.+ */+ /* @KeyRefreshPhaseTransition */+ public final int getTransition() {+ return transition;+ }++ /**+ * Returns if the message was successful+ *+ * @return true if the message was successful or false otherwise+ */+ public final boolean isSuccessful() {+ return mStatusCode == 0x00;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigLowPowerNodePollTimeoutStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigLowPowerNodePollTimeoutStatus.javanew file mode 100644index 000000000..cd9aff059--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigLowPowerNodePollTimeoutStatus.java@@ -0,0 +1,53 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++/**+ * Creates the ConfigLowPowerNodePollTimeoutStatus message.+ */+public class ConfigLowPowerNodePollTimeoutStatus extends ConfigStatusMessage {++ private static final String TAG = ConfigLowPowerNodePollTimeoutStatus.class.getSimpleName();+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_LOW_POWER_NODE_POLLTIMEOUT_STATUS;++ private int address;+ private int pollTimeout;++ /**+ * Constructs ConfigLowPowerNodePollTimeoutStatus message.+ *+ * @param message {@link AccessMessage}+ */+ public ConfigLowPowerNodePollTimeoutStatus(final AccessMessage message) {+ super(message);+ mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ void parseStatusParameters() {+ address = MeshParserUtils.unsignedBytesToInt(mParameters[0], mParameters[1]);+ pollTimeout = MeshParserUtils.convert24BitsToInt(new byte[] {mParameters[2], mParameters[3], mParameters[4]});+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ /**+ * Returns the Unicast address of the low power node+ */+ public int getAddress() {+ return address;+ }++ /**+ * Returns the Poll Timeout value for Low Power Node.+ */+ public int getPollTimeout() {+ return pollTimeout;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigMessage.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigMessage.javanew file mode 100644index 000000000..99c6382ef--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigMessage.java@@ -0,0 +1,24 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++abstract class ConfigMessage extends MeshMessage {++ /**+ * Creates the parameters for a given mesh message.+ */+ abstract void assembleMessageParameters();++ @Override+ public final int getAkf() {+ return 0;+ }++ @Override+ public final int getAid() {+ return 0;+ }++ @Override+ public final byte[] getParameters() {+ return mParameters;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigMessageState.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigMessageState.javanew file mode 100644index 000000000..2a6bcadaf--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigMessageState.java@@ -0,0 +1,50 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++/**+ * ConfigMessageState class that handles configuration message state.+ */+class ConfigMessageState extends MeshMessageState {++ private final byte[] mDeviceKey;++ /**+ * Constructs the ConfigMessageState+ *+ * @param src Source address+ * @param dst Destination address+ * @param deviceKey Device key+ * @param meshMessage {@link MeshMessage} Mesh message to be sent+ * @param meshTransport {@link MeshTransport} Mesh transport+ * @param callbacks {@link InternalMeshMsgHandlerCallbacks} callbacks+ */+ ConfigMessageState(final int src,+ final int dst,+ final byte[] deviceKey,+ final MeshMessage meshMessage,+ final MeshTransport meshTransport,+ final InternalMeshMsgHandlerCallbacks callbacks) {+ super(meshMessage, meshTransport, callbacks);+ this.mSrc = src;+ this.mDst = dst;+ this.mDeviceKey = deviceKey;+ createAccessMessage();+ }++ @Override+ public synchronized MessageState getState() {+ return MessageState.CONFIG_MESSAGE_STATE;+ }++ private synchronized void createAccessMessage() throws IllegalArgumentException {+ final ConfigMessage configMessage = (ConfigMessage) mMeshMessage;+ final int akf = configMessage.getAkf();+ final int aid = configMessage.getAid();+ final int aszmic = configMessage.getAszmic();+ final int opCode = configMessage.getOpCode();+ final byte[] parameters = configMessage.getParameters();+ message = mMeshTransport.createMeshMessage(mSrc, mDst, configMessage.messageTtl,+ mDeviceKey, akf, aid, aszmic, opCode, parameters);+ configMessage.setMessage(message);+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelAppBind.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelAppBind.javanew file mode 100644index 000000000..4debedd5e--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelAppBind.java@@ -0,0 +1,103 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++/**+ * To be used as a wrapper class to create ConfigModelAppBind message.+ */+public final class ConfigModelAppBind extends ConfigMessage {++ public static final Logger LOG = Logger.getLogger(ConfigModelAppBind.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_MODEL_APP_BIND;++ private static final int SIG_MODEL_APP_KEY_BIND_PARAMS_LENGTH = 6;+ private static final int VENDOR_MODEL_APP_KEY_BIND_PARAMS_LENGTH = 8;++ private final int mElementAddress;+ private final int mModelIdentifier;+ private final int mAppKeyIndex;++ /**+ * Constructs ConfigModelAppBind message.+ *+ * @param elementAddress Element address+ * @param modelIdentifier Model id+ * @param appKeyIndex Application key index of this message+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public ConfigModelAppBind(final int elementAddress,+ final int modelIdentifier,+ final int appKeyIndex) throws IllegalArgumentException {+ if (!MeshAddress.isValidUnicastAddress(elementAddress))+ throw new IllegalArgumentException("Invalid unicast address, unicast address must be a 16-bit value, and must range from 0x0001 to 0x7FFF");+ this.mElementAddress = elementAddress;+ this.mModelIdentifier = modelIdentifier;+ this.mAppKeyIndex = appKeyIndex;+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ void assembleMessageParameters() {+ final ByteBuffer paramsBuffer;+ final byte[] applicationKeyIndex = MeshParserUtils.addKeyIndexPadding(mAppKeyIndex);+ //We check if the model identifier value is within the range of a 16-bit value here. If it is then it is a sigmodel+ if (mModelIdentifier >= Short.MIN_VALUE && mModelIdentifier <= Short.MAX_VALUE) {+ paramsBuffer = ByteBuffer.allocate(SIG_MODEL_APP_KEY_BIND_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.putShort((short) mElementAddress);+ paramsBuffer.put(applicationKeyIndex[1]);+ paramsBuffer.put(applicationKeyIndex[0]);+ paramsBuffer.putShort((short) mModelIdentifier);+ mParameters = paramsBuffer.array();+ } else {+ paramsBuffer = ByteBuffer.allocate(VENDOR_MODEL_APP_KEY_BIND_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.putShort((short) mElementAddress);+ paramsBuffer.put(applicationKeyIndex[1]);+ paramsBuffer.put(applicationKeyIndex[0]);+ final byte[] modelIdentifier = new byte[]{(byte) ((mModelIdentifier >> 24) & 0xFF),+ (byte) ((mModelIdentifier >> 16) & 0xFF), (byte) ((mModelIdentifier >> 8) & 0xFF), (byte) (mModelIdentifier & 0xFF)};+ paramsBuffer.put(modelIdentifier[1]);+ paramsBuffer.put(modelIdentifier[0]);+ paramsBuffer.put(modelIdentifier[3]);+ paramsBuffer.put(modelIdentifier[2]);+ mParameters = paramsBuffer.array();+ }+ }++ /**+ * Returns the element address to which the app key must be bound.+ *+ * @return element address+ */+ public int getElementAddress() {+ return mElementAddress;+ }++ /**+ * Returns the model identifier to which the key is to be bound.+ *+ * @return 16-bit or 32-bit vendor model identifier+ */+ public int getModelIdentifier() {+ return mModelIdentifier;+ }++ /**+ * Returns the global index of the app key to be bound.+ *+ * @return app key index+ */+ public int getAppKeyIndex() {+ return mAppKeyIndex;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelAppStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelAppStatus.javanew file mode 100644index 000000000..a7737d9e4--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelAppStatus.java@@ -0,0 +1,101 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++public class ConfigModelAppStatus extends ConfigStatusMessage {++ public static final Logger LOG = Logger.getLogger(ConfigModelAppStatus.class.getName());++ private static final String TAG = ConfigModelAppStatus.class.getSimpleName();+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_MODEL_APP_STATUS;+ private static final int CONFIG_MODEL_APP_BIND_STATUS_SIG_MODEL = 7;+ private static final int CONFIG_MODEL_APP_BIND_STATUS_VENDOR_MODEL = 9;+ private int mElementAddress;+ private int mAppKeyIndex;+ private int mModelIdentifier;++ /**+ * Constructs the ConfigModelAppStatus mMessage.+ *+ * @param message Access Message+ */+ public ConfigModelAppStatus(final AccessMessage message) {+ super(message);+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ final void parseStatusParameters() {+ final AccessMessage message = (AccessMessage) mMessage;+ final ByteBuffer buffer = ByteBuffer.wrap(message.getParameters()).order(ByteOrder.LITTLE_ENDIAN);+ buffer.position(0);+ mStatusCode = buffer.get();+ mStatusCodeName = getStatusCodeName(mStatusCode);+ mElementAddress = MeshParserUtils.unsignedBytesToInt(mParameters[1], mParameters[2]);+ final byte[] appKeyIndex = new byte[]{(byte) (mParameters[4] & 0x0F), mParameters[3]};+ mAppKeyIndex = ByteBuffer.wrap(appKeyIndex).order(ByteOrder.BIG_ENDIAN).getShort();++ final byte[] modelIdentifier;+ if (mParameters.length == CONFIG_MODEL_APP_BIND_STATUS_SIG_MODEL) {+ mModelIdentifier = MeshParserUtils.unsignedBytesToInt(mParameters[5], mParameters[6]);+ } else {+ modelIdentifier = new byte[]{mParameters[6], mParameters[5], mParameters[8], mParameters[7]};+ mModelIdentifier = ByteBuffer.wrap(modelIdentifier).order(ByteOrder.BIG_ENDIAN).getInt();+ }++ LOG.info("Status code: " + mStatusCode);+ LOG.info("Status message: " + mStatusCodeName);+ LOG.info("Element address: " + MeshAddress.formatAddress(mElementAddress, false));+ LOG.info("App key index: " + MeshParserUtils.bytesToHex(appKeyIndex, false));+ LOG.info("Model identifier: " + Integer.toHexString(mModelIdentifier));+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ /**+ * Returns the element address that the key was bound to+ *+ * @return element address+ */+ public int getElementAddress() {+ return mElementAddress;+ }++ /**+ * Returns the global app key index.+ *+ * @return appkey index+ */+ public final int getAppKeyIndex() {+ return mAppKeyIndex;+ }++ /**+ * Returns the model identifier+ *+ * @return 16-bit sig model identifier or 32-bit vendor model identifier+ */+ public final int getModelIdentifier() {+ return mModelIdentifier;+ }++ /**+ * Returns if the message was successful or not.+ *+ * @return true if succesful or false otherwise+ */+ public boolean isSuccessful() {+ return mStatusCode == 0x00;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelPublicationGet.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelPublicationGet.javanew file mode 100644index 000000000..5202e2aa2--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelPublicationGet.java@@ -0,0 +1,90 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.CompositionDataParser;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++/**+ * To be used as a wrapper class to create a ConfigModelPublicationSet message.+ */+public class ConfigModelPublicationGet extends ConfigMessage {++ public static final Logger LOG = Logger.getLogger(ConfigModelPublicationGet.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_MODEL_PUBLICATION_GET;++ private static final int SIG_MODEL_PUBLISH_GET_PARAMS_LENGTH = 4;+ private static final int VENDOR_MODEL_PUBLISH_GET_PARAMS_LENGTH = 6;++ private final int elementAddress;+ private final int modelIdentifier;++ /**+ * Constructs a ConfigModelPublicationGet message+ *+ * @param elementAddress Element address that should publish+ * @param modelIdentifier identifier for this model that will do publication+ * @throws IllegalArgumentException for invalid arguments+ */+ public ConfigModelPublicationGet(final int elementAddress,+ final int modelIdentifier) throws IllegalArgumentException {+ if (!MeshAddress.isValidUnicastAddress(elementAddress))+ throw new IllegalArgumentException("Invalid unicast address, unicast address must be a 16-bit value, and must range from 0x0001 to 0x7FFF");+ this.elementAddress = elementAddress;+ this.modelIdentifier = modelIdentifier;+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }+++ @Override+ void assembleMessageParameters() {+ final ByteBuffer paramsBuffer;+ LOG.info("Element address: " + MeshAddress.formatAddress(elementAddress, true));+ LOG.info("Model: " + CompositionDataParser.formatModelIdentifier(modelIdentifier, false));++ //We check if the model identifier value is within the range of a 16-bit value here. If it is then it is a sigmodel+ if (modelIdentifier >= Short.MIN_VALUE && modelIdentifier <= Short.MAX_VALUE) {+ paramsBuffer = ByteBuffer.allocate(SIG_MODEL_PUBLISH_GET_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.putShort((short) elementAddress);+ paramsBuffer.putShort((short) modelIdentifier);+ mParameters = paramsBuffer.array();+ } else {+ paramsBuffer = ByteBuffer.allocate(VENDOR_MODEL_PUBLISH_GET_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.putShort((short) elementAddress);+ final byte[] modelIdentifier = new byte[]{(byte) ((this.modelIdentifier >> 24) & 0xFF), (byte) ((this.modelIdentifier >> 16) & 0xFF),+ (byte) ((this.modelIdentifier >> 8) & 0xFF), (byte) (this.modelIdentifier & 0xFF)};+ paramsBuffer.put(modelIdentifier[1]);+ paramsBuffer.put(modelIdentifier[0]);+ paramsBuffer.put(modelIdentifier[3]);+ paramsBuffer.put(modelIdentifier[2]);+ mParameters = paramsBuffer.array();+ }+ }++ /**+ * Returns the element address to which the app key must be bound.+ *+ * @return element address+ */+ public int getElementAddress() {+ return elementAddress;+ }++ /**+ * Returns the model identifier to which the key is to be bound.+ *+ * @return 16-bit or 32-bit vendor model identifier+ */+ public int getModelIdentifier() {+ return modelIdentifier;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelPublicationSet.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelPublicationSet.javanew file mode 100644index 000000000..76e9e7804--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelPublicationSet.java@@ -0,0 +1,241 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++import static org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress.UNASSIGNED_ADDRESS;+import static org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress.addressIntToBytes;+import static org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress.formatAddress;+import static org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress.isAddressInRange;+import static org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress.isValidUnicastAddress;+++/**+ * To be used as a wrapper class to create a ConfigModelPublicationSet message.+ */+public class ConfigModelPublicationSet extends ConfigMessage {++ public static final Logger LOG = Logger.getLogger(ConfigModelPublicationSet.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_MODEL_PUBLICATION_SET;++ private static final int SIG_MODEL_PUBLISH_SET_PARAMS_LENGTH = 11;+ private static final int VENDOR_MODEL_PUBLISH_SET_PARAMS_LENGTH = 13;++ private final int elementAddress;+ private final int publishAddress;+ private final int appKeyIndex;+ private final boolean credentialFlag;+ private final int publishTtl;+ private final int publicationSteps;+ private final int publicationResolution;+ private final int publishRetransmitCount;+ private final int publishRetransmitIntervalSteps;+ private final int modelIdentifier;++ /**+ * Constructs a ConfigModelPublicationSet message. Use this constructor to clear publications+ *+ * @param elementAddress Element address that should publish+ * @param modelIdentifier identifier for this model that will do publication+ * @throws IllegalArgumentException for invalid arguments+ */+ public ConfigModelPublicationSet(final int elementAddress,+ final int modelIdentifier) throws IllegalArgumentException {+ this(elementAddress, UNASSIGNED_ADDRESS, 0, false, 0,+ 0, 0, 0, 0, modelIdentifier);+ }++ /**+ * Constructs a ConfigModelPublicationSet message.+ *+ * @param elementAddress Element address that should publish+ * @param publishAddress Address to which the element must publish+ * @param appKeyIndex Index of the application key+ * @param credentialFlag Credentials flag define which credentials to be used,+ * set true to use friendship credentials and false for master credentials.+ * Currently supports only master credentials+ * @param publishTtl Publication ttl+ * @param publicationSteps Publication steps for the publication period+ * @param publicationResolution Publication resolution of the publication period+ * @param retransmitCount Number of publication retransmits+ * @param retransmitIntervalSteps Publish retransmit interval steps+ * @param modelIdentifier identifier for this model that will do publication+ * @throws IllegalArgumentException for invalid arguments+ */+ public ConfigModelPublicationSet(final int elementAddress,+ final int publishAddress,+ final int appKeyIndex,+ final boolean credentialFlag,+ final int publishTtl,+ final int publicationSteps,+ final int publicationResolution,+ final int retransmitCount,+ final int retransmitIntervalSteps,+ final int modelIdentifier) throws IllegalArgumentException {+ if (!isValidUnicastAddress(elementAddress))+ throw new IllegalArgumentException("Invalid unicast address, unicast address must be a 16-bit value, and must range from 0x0001 to 0x7FFF");+ this.elementAddress = elementAddress;+ if (!isAddressInRange(publishAddress))+ throw new IllegalArgumentException("Invalid publish address, publish address must be a 16-bit value");+ this.publishAddress = publishAddress;++ this.credentialFlag = credentialFlag;+ this.publishTtl = publishTtl;+ this.publicationSteps = publicationSteps;+ this.publicationResolution = publicationResolution;+ this.publishRetransmitCount = retransmitCount;+ this.publishRetransmitIntervalSteps = retransmitIntervalSteps;+ this.modelIdentifier = modelIdentifier;+ this.appKeyIndex = appKeyIndex;+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }+++ @Override+ void assembleMessageParameters() {+ final ByteBuffer paramsBuffer;+ final byte[] applicationKeyIndex = MeshParserUtils.addKeyIndexPadding(appKeyIndex);+ LOG.info("AppKeyIndex: " + appKeyIndex);+ LOG.info("Element address: " + formatAddress(elementAddress, true));+ LOG.info("Publish address: " + formatAddress(publishAddress, true));+ LOG.info("Publish ttl: " + publishTtl);+ LOG.info("Publish steps: " + publicationSteps);+ LOG.info("Publish resolution: " + publicationResolution);+ LOG.info("Retransmission count: " + publishRetransmitCount);+ LOG.info("Retransmission interval steps: " + publishRetransmitIntervalSteps);+ LOG.info("Model: " + MeshParserUtils.bytesToHex(addressIntToBytes(modelIdentifier), false));++ final int rfu = 0; // We ignore the rfu here+ final int octet5 = (applicationKeyIndex[0] | (credentialFlag ? 0b01 : 0b00) << 4);+ final byte publishPeriod = (byte) ((publicationResolution << 6) | (publicationSteps & 0x3F));+ final int octet8 = (publishRetransmitIntervalSteps << 3) | (publishRetransmitCount & 0x07);+ //We check if the model identifier value is within the range of a 16-bit value here. If it is then it is a sig model+ if (modelIdentifier >= Short.MIN_VALUE && modelIdentifier <= Short.MAX_VALUE) {+ paramsBuffer = ByteBuffer.allocate(SIG_MODEL_PUBLISH_SET_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.putShort((short) this.elementAddress);+ paramsBuffer.putShort((short) this.publishAddress);+ paramsBuffer.put((applicationKeyIndex[1]));+ paramsBuffer.put((byte) octet5);+ paramsBuffer.put((byte) publishTtl);+ paramsBuffer.put(publishPeriod);+ paramsBuffer.put((byte) octet8);+ paramsBuffer.putShort((short) modelIdentifier);+ mParameters = paramsBuffer.array();+ } else {+ paramsBuffer = ByteBuffer.allocate(VENDOR_MODEL_PUBLISH_SET_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.putShort((short) this.elementAddress);+ paramsBuffer.putShort((short) this.publishAddress);+ paramsBuffer.put(applicationKeyIndex[1]);+ paramsBuffer.put((byte) octet5);+ paramsBuffer.put((byte) publishTtl);+ paramsBuffer.put(publishPeriod);+ paramsBuffer.put((byte) octet8);+ final byte[] modelIdentifier = new byte[]{(byte) ((this.modelIdentifier >> 24) & 0xFF),+ (byte) ((this.modelIdentifier >> 16) & 0xFF), (byte) ((this.modelIdentifier >> 8) & 0xFF), (byte) (this.modelIdentifier & 0xFF)};+ paramsBuffer.put(modelIdentifier[1]);+ paramsBuffer.put(modelIdentifier[0]);+ paramsBuffer.put(modelIdentifier[3]);+ paramsBuffer.put(modelIdentifier[2]);+ mParameters = paramsBuffer.array();+ }+ LOG.info("Publication set: " + MeshParserUtils.bytesToHex(mParameters, false));+ }++ /**+ * Returns the element address to which the app key must be bound.+ *+ * @return element address+ */+ public int getElementAddress() {+ return elementAddress;+ }++ /**+ * Returns the publish address to which the model must publish to+ */+ public int getPublishAddress() {+ return publishAddress;+ }++ /**+ * Returns the global index of the app key to be used for publication.+ *+ * @return app key index+ */+ public int getAppKeyIndex() {+ return appKeyIndex;+ }++ /**+ * Returns the credential flag to be used for this message.+ *+ * @return true if friendship credentials to be used or false if master credentials is to be used.+ */+ public boolean getCredentialFlag() {+ return credentialFlag;+ }++ /**+ * Returns the ttl of publication messages+ *+ * @return publication ttl+ */+ public int getPublishTtl() {+ return publishTtl;+ }++ /**+ * Returns the number of publication steps.+ *+ * @return number of steps+ */+ public int getPublicationSteps() {+ return publicationSteps;+ }++ /**+ * Returns the resolution for the publication steps.+ *+ * @return resolution+ */+ public int getPublicationResolution() {+ return publicationResolution;+ }++ /**+ * Returns the number of retransmissions for each published message.+ *+ * @return number of retransmits+ */+ public int getPublishRetransmitCount() {+ return publishRetransmitCount;+ }++ /**+ * Returns the number of 50-milliseconds steps between retransmissions.+ *+ * @return retransmit interval steps+ */+ public int getPublishRetransmitIntervalSteps() {+ return publishRetransmitIntervalSteps;+ }++ /**+ * Returns the model identifier to which the key is to be bound.+ *+ * @return 16-bit or 32-bit vendor model identifier+ */+ public int getModelIdentifier() {+ return modelIdentifier;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelPublicationStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelPublicationStatus.javanew file mode 100644index 000000000..ba0e8b9b3--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelPublicationStatus.java@@ -0,0 +1,185 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++/**+ * To be used as a wrapper class for when creating the ConfigModelAppStatus Message.+ */+public class ConfigModelPublicationStatus extends ConfigStatusMessage {++ public static final Logger LOG = Logger.getLogger(ConfigModelPublicationStatus.class.getName());++ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_MODEL_PUBLICATION_STATUS;+ private static final int CONFIG_MODEL_PUBLICATION_STATUS_SIG_MODEL_PDU_LENGTH = 12;+ private static final int CONFIG_MODEL_APP_BIND_STATUS_VENDOR_MODEL_PDU_LENGTH = 14;+ private int mElementAddress;+ private int publishAddress;+ private int mAppKeyIndex;+ private boolean credentialFlag;+ private int publishTtl;+ private int publicationSteps;+ private int publicationResolution;+ private int publishRetransmitCount;+ private int publishRetransmitIntervalSteps;+ private int mModelIdentifier; //16-bit SIG Model or 32-bit Vendor Model identifier++ /**+ * Constructs the ConfigModelAppStatus mMessage.+ *+ * @param message Access Message+ */+ public ConfigModelPublicationStatus(final AccessMessage message) {+ super(message);+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ final void parseStatusParameters() {+ final AccessMessage message = (AccessMessage) mMessage;+ mStatusCode = mParameters[0];+ mStatusCodeName = getStatusCodeName(mStatusCode);+ mElementAddress = MeshParserUtils.unsignedBytesToInt(mParameters[1], mParameters[2]);+ publishAddress = MeshParserUtils.unsignedBytesToInt(mParameters[3], mParameters[4]);+ final byte[] appKeyIndex = new byte[]{(byte) (mParameters[6] & 0x0F), mParameters[5]};+ mAppKeyIndex = ByteBuffer.wrap(appKeyIndex).order(ByteOrder.BIG_ENDIAN).getShort();+ credentialFlag = (mParameters[6] & 0xF0) >> 4 == 1;+ publishTtl = MeshParserUtils.unsignedByteToInt(mParameters[7]);+ final int publishPeriod = MeshParserUtils.unsignedByteToInt(mParameters[8]);+ publicationSteps = publishPeriod & 0x3F;+ publicationResolution = publishPeriod >> 6;+ final int publishRetransmission = MeshParserUtils.unsignedByteToInt(mParameters[9]);+ publishRetransmitCount = publishRetransmission & 0x07;+ publishRetransmitIntervalSteps = publishRetransmission >> 3;++ final byte[] modelIdentifier;+ if (mParameters.length == CONFIG_MODEL_PUBLICATION_STATUS_SIG_MODEL_PDU_LENGTH) {+ mModelIdentifier = MeshParserUtils.unsignedBytesToInt(mParameters[10], mParameters[11]);+ } else {+ modelIdentifier = new byte[]{mParameters[11], mParameters[10], mParameters[13], mParameters[12]};+ mModelIdentifier = ByteBuffer.wrap(modelIdentifier).order(ByteOrder.BIG_ENDIAN).getInt();+ }++ LOG.info("Status code: " + mStatusCode);+ LOG.info("Status message: " + mStatusCodeName);+ LOG.info("Element address: " + MeshAddress.formatAddress(mElementAddress, false));+ LOG.info("Publish Address: " + MeshAddress.formatAddress(publishAddress, false));+ LOG.info("App key index: " + MeshParserUtils.bytesToHex(appKeyIndex, false));+ LOG.info("Credential Flag: " + credentialFlag);+ LOG.info("Publish TTL: " + publishTtl);+ LOG.info("Publish Period where steps: " + publicationSteps + " and resolution: " + publicationResolution);+ LOG.info("Publish Retransmit Count: " + publishRetransmitCount);+ LOG.info("Publish Retransmit Interval Steps: " + publishRetransmitIntervalSteps);+ LOG.info("Model Identifier: " + Integer.toHexString(mModelIdentifier));+ LOG.info("Publication status: " + MeshParserUtils.bytesToHex(mParameters, false));+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ /**+ * Returns the element address that the key was bound to+ *+ * @return element address+ */+ public int getElementAddress() {+ return mElementAddress;+ }++ /**+ * Returns the global app key index.+ *+ * @return appkey index+ */+ public final int getAppKeyIndex() {+ return mAppKeyIndex;+ }++ /**+ * Returns if the message was successful or not.+ *+ * @return true if successful or false otherwise+ */+ public boolean isSuccessful() {+ return mStatusCode == 0x00;+ }++ /**+ * Returns the publish address to which the model must publish to+ */+ public int getPublishAddress() {+ return publishAddress;+ }++ /**+ * Returns the credential flag to be used for this message.+ *+ * @return true if friendship credentials to be used or false if master credentials is to be used.+ */+ public boolean getCredentialFlag() {+ return credentialFlag;+ }++ /**+ * Returns the ttl of publication messages+ *+ * @return publication ttl+ */+ public int getPublishTtl() {+ return publishTtl;+ }++ /**+ * Returns the number of publication steps.+ *+ * @return number of steps+ */+ public int getPublicationSteps() {+ return publicationSteps;+ }++ /**+ * Returns the resolution for the publication steps.+ *+ * @return resolution+ */+ public int getPublicationResolution() {+ return publicationResolution;+ }++ /**+ * Returns the number of retransmissions for each published message.+ *+ * @return number of retransmits+ */+ public int getPublishRetransmitCount() {+ return publishRetransmitCount;+ }++ /**+ * Returns the number of 50-milliseconds steps between retransmissions.+ *+ * @return retransmit interval steps+ */+ public int getPublishRetransmitIntervalSteps() {+ return publishRetransmitIntervalSteps;+ }++ /**+ * Returns the model identifier to which the key is to be bound.+ *+ * @return 16-bit or 32-bit vendor model identifier+ */+ public int getModelIdentifier() {+ return mModelIdentifier;+ }++}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelPublicationVirtualAddressSet.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelPublicationVirtualAddressSet.javanew file mode 100644index 000000000..9b30c0d7d--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelPublicationVirtualAddressSet.java@@ -0,0 +1,219 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.UUID;+import java.util.logging.Logger;++/**+ * This is the message class for setting a virtual address as a publication address+ */+public class ConfigModelPublicationVirtualAddressSet extends ConfigMessage {++ public static final Logger LOG = Logger.getLogger(ConfigModelPublicationVirtualAddressSet.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_MODEL_PUBLICATION_VIRTUAL_ADDRESS_SET;++ private static final int SIG_MODEL_PUBLISH_SET_PARAMS_LENGTH = 25;+ private static final int VENDOR_MODEL_PUBLISH_SET_PARAMS_LENGTH = 27;++ private final int elementAddress;+ private final UUID labelUuid;+ private final int appKeyIndex;+ private final boolean credentialFlag;+ private final int publishTtl;+ private final int publicationSteps;+ private final int publicationResolution;+ private final int publishRetransmitCount;+ private final int publishRetransmitIntervalSteps;+ private final int modelIdentifier;++ /**+ * Constructs a ConfigModelPublicationVirtualAddressSet message+ *+ * @param elementAddress Element address that should publish+ * @param labelUuid Value of the Label UUID publish address+ * @param appKeyIndex Index of the application key+ * @param credentialFlag Credentials flag define which credentials to be used, set true to use friendship credentials and false+ * for master credentials. Currently supports only master credentials+ * @param publishTtl Publication ttl+ * @param publicationSteps Publication steps for the publication period+ * @param publicationResolution Publication resolution of the publication period+ * @param retransmitCount Number of publication retransmits+ * @param retransmitIntervalSteps Publish retransmit interval steps+ * @param modelIdentifier identifier for this model that will do publication+ * @throws IllegalArgumentException for invalid arguments+ */+ public ConfigModelPublicationVirtualAddressSet(final int elementAddress,+ /* @NonNull */ final UUID labelUuid,+ final int appKeyIndex,+ final boolean credentialFlag,+ final int publishTtl,+ final int publicationSteps,+ final int publicationResolution,+ final int retransmitCount,+ final int retransmitIntervalSteps,+ final int modelIdentifier) throws IllegalArgumentException {+ if (!MeshAddress.isValidUnicastAddress(elementAddress))+ throw new IllegalArgumentException("Invalid unicast address, unicast address must be a 16-bit value, and must range from 0x0001 to 0x7FFF");+ this.elementAddress = elementAddress;+ this.labelUuid = labelUuid;+ this.credentialFlag = credentialFlag;+ this.publishTtl = publishTtl;+ this.publicationSteps = publicationSteps;+ this.publicationResolution = publicationResolution;+ this.publishRetransmitCount = retransmitCount;+ this.publishRetransmitIntervalSteps = retransmitIntervalSteps;+ this.modelIdentifier = modelIdentifier;+ this.appKeyIndex = appKeyIndex;+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }+++ @Override+ void assembleMessageParameters() {+ final ByteBuffer paramsBuffer;+ final byte[] applicationKeyIndex = MeshParserUtils.addKeyIndexPadding(appKeyIndex);+ LOG.info("AppKeyIndex: " + appKeyIndex);+ LOG.info("Element address: " + MeshAddress.formatAddress(elementAddress, true));+ LOG.info("Label UUID: " + labelUuid.toString());+ LOG.info("Publish ttl: " + publishTtl);+ LOG.info("Publish steps: " + publicationSteps);+ LOG.info("Publish resolution: " + publicationResolution);+ LOG.info("Retransmission count: " + publishRetransmitCount);+ LOG.info("Retransmission interval: " + publishRetransmitIntervalSteps);+ LOG.info("Model: " + MeshParserUtils.bytesToHex(MeshAddress.addressIntToBytes(modelIdentifier), false));+ final byte[] publishAddress = MeshParserUtils.uuidToBytes(labelUuid);+ final int rfu = 0; // We ignore the rfu here+ final int octet5 = applicationKeyIndex[0] | ((credentialFlag ? 0b01 : 0b00) << 4);+ final byte publishPeriod = (byte) ((publicationResolution << 6) | (publicationSteps & 0x3F));+ final int octet8 = (publishRetransmitIntervalSteps << 3) | (publishRetransmitCount & 0x07);+ //We check if the model identifier value is within the range of a 16-bit value here. If it is then it is a sig model+ if (modelIdentifier >= Short.MIN_VALUE && modelIdentifier <= Short.MAX_VALUE) {+ paramsBuffer = ByteBuffer.allocate(SIG_MODEL_PUBLISH_SET_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.putShort((short) elementAddress);+ paramsBuffer.put(publishAddress);+ paramsBuffer.put(applicationKeyIndex[1]);+ paramsBuffer.put((byte) octet5);+ paramsBuffer.put((byte) publishTtl);+ paramsBuffer.put(publishPeriod);+ paramsBuffer.put((byte) octet8);+ paramsBuffer.putShort((short) modelIdentifier);+ mParameters = paramsBuffer.array();+ } else {+ paramsBuffer = ByteBuffer.allocate(VENDOR_MODEL_PUBLISH_SET_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.putShort((short) elementAddress);+ paramsBuffer.put(publishAddress);+ paramsBuffer.put(applicationKeyIndex[1]);+ paramsBuffer.put((byte) octet5);+ paramsBuffer.put((byte) publishTtl);+ paramsBuffer.put(publishPeriod);+ paramsBuffer.put((byte) octet8);+ final byte[] modelIdentifier = new byte[]{(byte) ((this.modelIdentifier >> 24) & 0xFF),+ (byte) ((this.modelIdentifier >> 16) & 0xFF), (byte) ((this.modelIdentifier >> 8) & 0xFF), (byte) (this.modelIdentifier & 0xFF)};+ paramsBuffer.put(modelIdentifier[1]);+ paramsBuffer.put(modelIdentifier[0]);+ paramsBuffer.put(modelIdentifier[3]);+ paramsBuffer.put(modelIdentifier[2]);+ mParameters = paramsBuffer.array();+ }+ LOG.info("Publication set: " + MeshParserUtils.bytesToHex(mParameters, false));+ }++ /**+ * Returns the element address to which the app key must be bound.+ *+ * @return element address+ */+ public int getElementAddress() {+ return elementAddress;+ }++ /**+ * Returns the value of the Label UUID publish address+ */+ public UUID getLabelUuid() {+ return labelUuid;+ }++ /**+ * Returns the global index of the app key to be used for publication.+ *+ * @return app key index+ */+ public int getAppKeyIndex() {+ return appKeyIndex;+ }++ /**+ * Returns the credential flag to be used for this message.+ *+ * @return true if friendship credentials to be used or false if master credentials is to be used.+ */+ public boolean getCredentialFlag() {+ return credentialFlag;+ }++ /**+ * Returns the ttl of publication messages+ *+ * @return publication ttl+ */+ public int getPublishTtl() {+ return publishTtl;+ }++ /**+ * Returns the number of publication steps.+ *+ * @return number of steps+ */+ public int getPublicationSteps() {+ return publicationSteps;+ }++ /**+ * Returns the resolution for the publication steps.+ *+ * @return resolution+ */+ public int getPublicationResolution() {+ return publicationResolution;+ }++ /**+ * Returns the number of retransmissions for each published message.+ *+ * @return number of retransmits+ */+ public int getPublishRetransmitCount() {+ return publishRetransmitCount;+ }++ /**+ * Returns the number of 50-milliseconds steps between retransmissions.+ *+ * @return retransmit interval steps+ */+ public int getPublishRetransmitIntervalSteps() {+ return publishRetransmitIntervalSteps;+ }++ /**+ * Returns the model identifier to which the key is to be bound.+ *+ * @return 16-bit or 32-bit vendor model identifier+ */+ public int getModelIdentifier() {+ return modelIdentifier;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelSubscriptionAdd.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelSubscriptionAdd.javanew file mode 100644index 000000000..db0f158fb--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelSubscriptionAdd.java@@ -0,0 +1,83 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++/**+ * Creates the ConfigModelSubscriptionAdd message+ */+@SuppressWarnings("unused")+public final class ConfigModelSubscriptionAdd extends ConfigMessage {++ public static final Logger LOG = Logger.getLogger(ConfigModelSubscriptionAdd.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_MODEL_SUBSCRIPTION_ADD;++ private static final int SIG_MODEL_APP_KEY_BIND_PARAMS_LENGTH = 6;+ private static final int VENDOR_MODEL_APP_KEY_BIND_PARAMS_LENGTH = 8;++ private final int elementAddress;+ private final int mSubscriptionAddress;+ private final int mModelIdentifier;++ /**+ * Constructs ConfigModelSubscriptionAdd message.+ *+ * @param elementAddress Address of the element to which the model belongs to.+ * @param subscriptionAddress Address to whic the element should subscribe.+ * @param modelIdentifier identifier of the model, 16-bit for Sig model and 32-bit model id for vendor models.+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public ConfigModelSubscriptionAdd(final int elementAddress,+ final int subscriptionAddress,+ final int modelIdentifier) throws IllegalArgumentException {++ if (!MeshAddress.isValidUnicastAddress(elementAddress))+ throw new IllegalArgumentException("Invalid unicast address, unicast address must be a 16-bit value, and must range from 0x0001 to 0x7FFF");+ this.elementAddress = elementAddress;+ if (!MeshAddress.isAddressInRange(subscriptionAddress))+ throw new IllegalArgumentException("Invalid subscription address, subscription address must be a 16-bit value");+ this.mSubscriptionAddress = subscriptionAddress;+ this.mModelIdentifier = modelIdentifier;+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ @Override+ void assembleMessageParameters() {++ final ByteBuffer paramsBuffer;+ //We check if the model identifier value is within the range of a 16-bit value here. If it is then it is a sigmodel+ final byte[] elementAddress = MeshAddress.addressIntToBytes(this.elementAddress);+ final byte[] subscriptionAddress = MeshAddress.addressIntToBytes(this.mSubscriptionAddress);+ if (mModelIdentifier >= Short.MIN_VALUE && mModelIdentifier <= Short.MAX_VALUE) {+ paramsBuffer = ByteBuffer.allocate(SIG_MODEL_APP_KEY_BIND_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.put(elementAddress[1]);+ paramsBuffer.put(elementAddress[0]);+ paramsBuffer.put(subscriptionAddress[1]);+ paramsBuffer.put(subscriptionAddress[0]);+ paramsBuffer.putShort((short) mModelIdentifier);+ mParameters = paramsBuffer.array();+ } else {+ paramsBuffer = ByteBuffer.allocate(VENDOR_MODEL_APP_KEY_BIND_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.put(elementAddress[1]);+ paramsBuffer.put(elementAddress[0]);+ paramsBuffer.put(subscriptionAddress[1]);+ paramsBuffer.put(subscriptionAddress[0]);+ final byte[] modelIdentifier = new byte[]{(byte) ((mModelIdentifier >> 24) & 0xFF), (byte) ((mModelIdentifier >> 16) & 0xFF), (byte) ((mModelIdentifier >> 8) & 0xFF), (byte) (mModelIdentifier & 0xFF)};+ paramsBuffer.put(modelIdentifier[1]);+ paramsBuffer.put(modelIdentifier[0]);+ paramsBuffer.put(modelIdentifier[3]);+ paramsBuffer.put(modelIdentifier[2]);+ mParameters = paramsBuffer.array();+ }+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelSubscriptionDelete.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelSubscriptionDelete.javanew file mode 100644index 000000000..f4c78e686--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelSubscriptionDelete.java@@ -0,0 +1,88 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++import static org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress.addressIntToBytes;+import static org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress.isValidUnassignedAddress;+import static org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress.isValidUnicastAddress;+import static org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress.isValidVirtualAddress;++/**+ * Creates the ConfigModelSubscriptionDelete message+ */+@SuppressWarnings({"unused"})+public final class ConfigModelSubscriptionDelete extends ConfigMessage {++ public static final Logger LOG = Logger.getLogger(ConfigModelSubscriptionDelete.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_MODEL_SUBSCRIPTION_DELETE;++ private static final int SIG_MODEL_APP_KEY_BIND_PARAMS_LENGTH = 6;+ private static final int VENDOR_MODEL_APP_KEY_BIND_PARAMS_LENGTH = 8;++ private final int mElementAddress;+ private final int mSubscriptionAddress;+ private final int mModelIdentifier;++ /**+ * Constructs ConfigModelSubscriptionDelete message.+ *+ * @param elementAddress Address of the element to which the model belongs to.+ * @param subscriptionAddress Address to unsubscribe from or deleted.+ * @param modelIdentifier identifier of the model, 16-bit for Sig model and 32-bit model id for vendor models.+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public ConfigModelSubscriptionDelete(final int elementAddress,+ final int subscriptionAddress,+ final int modelIdentifier) throws IllegalArgumentException {++ if (!isValidUnicastAddress(elementAddress))+ throw new IllegalArgumentException("Invalid unicast address, unicast address must be a 16-bit value, and must range from 0x0001 to 0x7FFF");+ this.mElementAddress = elementAddress;+ if (isValidUnassignedAddress(subscriptionAddress) || isValidUnicastAddress(subscriptionAddress) || isValidVirtualAddress(subscriptionAddress) || subscriptionAddress == 0xFFFF)+ throw new IllegalArgumentException("The value of the Address field shall not be an unassigned address, unicast address, " ++ "all-nodes address or virtual address.");+ this.mSubscriptionAddress = subscriptionAddress;+ this.mModelIdentifier = modelIdentifier;+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ @Override+ void assembleMessageParameters() {++ final ByteBuffer paramsBuffer;+ //We check if the model identifier value is within the range of a 16-bit value here. If it is then it is a sigmodel+ final byte[] elementaddress = addressIntToBytes(mElementAddress);+ final byte[] subscriptionAddress = addressIntToBytes(mSubscriptionAddress);+ if (mModelIdentifier >= Short.MIN_VALUE && mModelIdentifier <= Short.MAX_VALUE) {+ paramsBuffer = ByteBuffer.allocate(SIG_MODEL_APP_KEY_BIND_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.put(elementaddress[1]);+ paramsBuffer.put(elementaddress[0]);+ paramsBuffer.put(subscriptionAddress[1]);+ paramsBuffer.put(subscriptionAddress[0]);+ paramsBuffer.putShort((short) mModelIdentifier);+ mParameters = paramsBuffer.array();+ } else {+ paramsBuffer = ByteBuffer.allocate(VENDOR_MODEL_APP_KEY_BIND_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.put(elementaddress[1]);+ paramsBuffer.put(elementaddress[0]);+ paramsBuffer.put(subscriptionAddress[1]);+ paramsBuffer.put(subscriptionAddress[0]);+ final byte[] modelIdentifier = new byte[]{(byte) ((mModelIdentifier >> 24) & 0xFF),+ (byte) ((mModelIdentifier >> 16) & 0xFF), (byte) ((mModelIdentifier >> 8) & 0xFF), (byte) (mModelIdentifier & 0xFF)};+ paramsBuffer.put(modelIdentifier[1]);+ paramsBuffer.put(modelIdentifier[0]);+ paramsBuffer.put(modelIdentifier[3]);+ paramsBuffer.put(modelIdentifier[2]);+ mParameters = paramsBuffer.array();+ }+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelSubscriptionDeleteAll.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelSubscriptionDeleteAll.javanew file mode 100644index 000000000..27dcee3d7--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelSubscriptionDeleteAll.java@@ -0,0 +1,71 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++/**+ * Creates the ConfigModelSubscriptionDeleteAll message+ */+@SuppressWarnings({"unused"})+public final class ConfigModelSubscriptionDeleteAll extends ConfigMessage {++ public static final Logger LOG = Logger.getLogger(ConfigModelSubscriptionDeleteAll.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_MODEL_SUBSCRIPTION_DELETE_ALL;++ private static final int SIG_MODEL_APP_KEY_BIND_PARAMS_LENGTH = 4;+ private static final int VENDOR_MODEL_APP_KEY_BIND_PARAMS_LENGTH = 6;++ private final int mElementAddress;+ private final int mModelIdentifier;++ /**+ * Constructs ConfigModelSubscriptionDeleteAll message.+ *+ * @param elementAddress Address of the element to which the model belongs to.+ * @param modelIdentifier identifier of the model, 16-bit for Sig model and 32-bit model id for vendor models.+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public ConfigModelSubscriptionDeleteAll(final int elementAddress,+ final int modelIdentifier) throws IllegalArgumentException {+ if (!MeshAddress.isValidUnicastAddress(elementAddress))+ throw new IllegalArgumentException("Invalid unicast address, unicast address must be a 16-bit value, and must range from 0x0001 to 0x7FFF");+ this.mElementAddress = elementAddress;+ this.mModelIdentifier = modelIdentifier;+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ @Override+ void assembleMessageParameters() {+ final ByteBuffer paramsBuffer;+ //We check if the model identifier value is within the range of a 16-bit value here. If it is then it is a sigmodel+ final byte[] elementAddress = MeshAddress.addressIntToBytes(mElementAddress);+ if (mModelIdentifier >= Short.MIN_VALUE && mModelIdentifier <= Short.MAX_VALUE) {+ paramsBuffer = ByteBuffer.allocate(SIG_MODEL_APP_KEY_BIND_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.put(elementAddress[1]);+ paramsBuffer.put(elementAddress[0]);+ paramsBuffer.putShort((short) mModelIdentifier);+ mParameters = paramsBuffer.array();+ } else {+ paramsBuffer = ByteBuffer.allocate(VENDOR_MODEL_APP_KEY_BIND_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.put(elementAddress[1]);+ paramsBuffer.put(elementAddress[0]);+ final byte[] modelIdentifier = new byte[]{(byte) ((mModelIdentifier >> 24) & 0xFF),+ (byte) ((mModelIdentifier >> 16) & 0xFF), (byte) ((mModelIdentifier >> 8) & 0xFF), (byte) (mModelIdentifier & 0xFF)};+ paramsBuffer.put(modelIdentifier[1]);+ paramsBuffer.put(modelIdentifier[0]);+ paramsBuffer.put(modelIdentifier[3]);+ paramsBuffer.put(modelIdentifier[2]);+ mParameters = paramsBuffer.array();+ }+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelSubscriptionOverwrite.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelSubscriptionOverwrite.javanew file mode 100644index 000000000..9dbcefa58--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelSubscriptionOverwrite.java@@ -0,0 +1,83 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++/**+ * This class handles subscribing a model to subscription address.+ */+@SuppressWarnings("unused")+public final class ConfigModelSubscriptionOverwrite extends ConfigMessage {++ public static final Logger LOG = Logger.getLogger(ConfigModelSubscriptionOverwrite.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_MODEL_SUBSCRIPTION_OVERWRITE;++ private static final int SIG_MODEL_APP_KEY_BIND_PARAMS_LENGTH = 6;+ private static final int VENDOR_MODEL_APP_KEY_BIND_PARAMS_LENGTH = 8;++ private final int elementAddress;+ private final int mSubscriptionAddress;+ private final int mModelIdentifier;++ /**+ * Constructs ConfigModelSubscriptionDelete message.+ *+ * @param elementAddress Address of the element to which the model belongs to.+ * @param subscriptionAddress Address to whic the element should subscribe.+ * @param modelIdentifier identifier of the model, 16-bit for Sig model and 32-bit model id for vendor models.+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public ConfigModelSubscriptionOverwrite(final int elementAddress,+ final int subscriptionAddress,+ final int modelIdentifier) throws IllegalArgumentException {++ if (!MeshAddress.isValidUnicastAddress(elementAddress))+ throw new IllegalArgumentException("Invalid unicast address, unicast address must be a 16-bit value, and must range from 0x0001 to 0x7FFF");+ this.elementAddress = elementAddress;+ if (!MeshAddress.isAddressInRange(subscriptionAddress))+ throw new IllegalArgumentException("Invalid subscription address, subscription address must be a 16-bit value");+ this.mSubscriptionAddress = subscriptionAddress;+ this.mModelIdentifier = modelIdentifier;+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ @Override+ void assembleMessageParameters() {++ final ByteBuffer paramsBuffer;+ //We check if the model identifier value is within the range of a 16-bit value here. If it is then it is a sigmodel+ final byte[] elementAddress = MeshAddress.addressIntToBytes(this.elementAddress);+ final byte[] subscriptionAddress = MeshAddress.addressIntToBytes(this.mSubscriptionAddress);+ if (mModelIdentifier >= Short.MIN_VALUE && mModelIdentifier <= Short.MAX_VALUE) {+ paramsBuffer = ByteBuffer.allocate(SIG_MODEL_APP_KEY_BIND_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.put(elementAddress[1]);+ paramsBuffer.put(elementAddress[0]);+ paramsBuffer.put(subscriptionAddress[1]);+ paramsBuffer.put(subscriptionAddress[0]);+ paramsBuffer.putShort((short) mModelIdentifier);+ mParameters = paramsBuffer.array();+ } else {+ paramsBuffer = ByteBuffer.allocate(VENDOR_MODEL_APP_KEY_BIND_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.put(elementAddress[1]);+ paramsBuffer.put(elementAddress[0]);+ paramsBuffer.put(subscriptionAddress[1]);+ paramsBuffer.put(subscriptionAddress[0]);+ final byte[] modelIdentifier = new byte[]{(byte) ((mModelIdentifier >> 24) & 0xFF),+ (byte) ((mModelIdentifier >> 16) & 0xFF), (byte) ((mModelIdentifier >> 8) & 0xFF), (byte) (mModelIdentifier & 0xFF)};+ paramsBuffer.put(modelIdentifier[1]);+ paramsBuffer.put(modelIdentifier[0]);+ paramsBuffer.put(modelIdentifier[3]);+ paramsBuffer.put(modelIdentifier[2]);+ mParameters = paramsBuffer.array();+ }+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelSubscriptionStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelSubscriptionStatus.javanew file mode 100644index 000000000..9c46796a7--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelSubscriptionStatus.java@@ -0,0 +1,98 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.util.logging.Logger;++/**+ * Creates the ConfigModelSubscriptionStatus Message.+ */+@SuppressWarnings({"unused", "WeakerAccess"})+public class ConfigModelSubscriptionStatus extends ConfigStatusMessage {++ public static final Logger LOG = Logger.getLogger(ConfigModelSubscriptionStatus.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_MODEL_SUBSCRIPTION_STATUS;+ private static final int CONFIG_MODEL_PUBLICATION_STATUS_SIG_MODEL_PDU_LENGTH = 7;+ private static final int CONFIG_MODEL_APP_BIND_STATUS_VENDOR_MODEL_PDU_LENGTH = 9;+ private int mElementAddress;+ private int mModelIdentifier;+ private int mSubscriptionAddress;++ /**+ * Constructs the ConfigModelSubscriptionStatus mMessage.+ *+ * @param message Access Message+ */+ public ConfigModelSubscriptionStatus(final AccessMessage message) {+ super(message);+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ final void parseStatusParameters() {+ final AccessMessage message = (AccessMessage) mMessage;+ mStatusCode = mParameters[0];+ mStatusCodeName = getStatusCodeName(mStatusCode);+ mElementAddress = MeshParserUtils.unsignedBytesToInt(mParameters[1], mParameters[2]);++ mSubscriptionAddress = MeshParserUtils.unsignedBytesToInt(mParameters[3], mParameters[4]);++ final byte[] modelIdentifier;+ if (mParameters.length == CONFIG_MODEL_PUBLICATION_STATUS_SIG_MODEL_PDU_LENGTH) {+ mModelIdentifier = MeshParserUtils.unsignedBytesToInt(mParameters[5], mParameters[6]);+ } else {+ //modelIdentifier = new byte[]{mParameters[6], mParameters[5], mParameters[8], mParameters[7]};+ mModelIdentifier = MeshParserUtils.bytesToInt(new byte[]{mParameters[6], mParameters[5], mParameters[8], mParameters[7]});+ }++ LOG.info("Status code: " + mStatusCode);+ LOG.info("Status message: " + mStatusCodeName);+ LOG.info("Element Address: " + MeshAddress.formatAddress(mElementAddress, true));+ LOG.info("Subscription Address: " + MeshAddress.formatAddress(mSubscriptionAddress, true));+ LOG.info("Model Identifier: " + Integer.toHexString(mModelIdentifier));+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ /**+ * Returns the element address that the key was bound to+ *+ * @return element address+ */+ public int getElementAddress() {+ return mElementAddress;+ }++ /**+ * Returns the subscription address.+ *+ * @return subscription address+ */+ public int getSubscriptionAddress() {+ return mSubscriptionAddress;+ }++ /**+ * Returns the model identifier+ *+ * @return 16-bit sig model identifier or 32-bit vendor model identifier+ */+ public final int getModelIdentifier() {+ return mModelIdentifier;+ }++ /**+ * Returns if the message was successful+ *+ * @return true if the message was successful or false otherwise+ */+ public final boolean isSuccessful() {+ return mStatusCode == 0x00;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelSubscriptionVirtualAddressAdd.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelSubscriptionVirtualAddressAdd.javanew file mode 100644index 000000000..9e8787062--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelSubscriptionVirtualAddressAdd.java@@ -0,0 +1,90 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.UUID;+import java.util.logging.Logger;++/**+ * Creates the ConfigModelSubscriptionVirtualAddressAdd Message.+ */+@SuppressWarnings({"unused"})+public final class ConfigModelSubscriptionVirtualAddressAdd extends ConfigMessage {++ public static final Logger LOG = Logger.getLogger(ConfigModelSubscriptionVirtualAddressAdd.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_MODEL_SUBSCRIPTION_VIRTUAL_ADDRESS_ADD;++ //Length in bytes+ private static final int CONFIG_MODEL_SUBSCRIPTION_VIRTUAL_ADDRESS_ADD_PARAMS_LENGTH = 20;+ private static final int VENDOR_MODEL_SUBSCRIPTION_VIRTUAL_ADDRESS_ADD_PARAMS_LENGTH = CONFIG_MODEL_SUBSCRIPTION_VIRTUAL_ADDRESS_ADD_PARAMS_LENGTH + 2;++ private final int elementAddress;+ private final UUID labelUuid;+ private final int mModelIdentifier;++ /**+ * Constructs ConfigModelSubscriptionVirtualAddressAdd message.+ *+ * @param elementAddress Address of the element to which the model belongs to.+ * @param labelUuid Value of the Label UUID.+ * @param modelIdentifier Model identifier, 16-bit for Sig model and 32-bit model id for vendor models.+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public ConfigModelSubscriptionVirtualAddressAdd(final int elementAddress,+ /* @NonNull */ final UUID labelUuid,+ final int modelIdentifier) throws IllegalArgumentException {++ if (!MeshAddress.isValidUnicastAddress(elementAddress))+ throw new IllegalArgumentException("Invalid unicast address, unicast address must be a 16-bit value, and must range from 0x0001 to 0x7FFF");+ this.elementAddress = elementAddress;+ this.labelUuid = labelUuid;+ this.mModelIdentifier = modelIdentifier;+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ @Override+ void assembleMessageParameters() {++ final ByteBuffer paramsBuffer;+ //We check if the model identifier value is within the range of a 16-bit value here. If it is then it is a sigmodel+ final byte[] elementAddress = MeshAddress.addressIntToBytes(this.elementAddress);+ final byte[] subscriptionAddress = MeshParserUtils.uuidToBytes(labelUuid);+ if (mModelIdentifier >= Short.MIN_VALUE && mModelIdentifier <= Short.MAX_VALUE) {+ paramsBuffer = ByteBuffer.allocate(CONFIG_MODEL_SUBSCRIPTION_VIRTUAL_ADDRESS_ADD_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.put(elementAddress[1]);+ paramsBuffer.put(elementAddress[0]);+ paramsBuffer.put(subscriptionAddress);+ paramsBuffer.putShort((short) mModelIdentifier);+ mParameters = paramsBuffer.array();+ } else {+ paramsBuffer = ByteBuffer.allocate(VENDOR_MODEL_SUBSCRIPTION_VIRTUAL_ADDRESS_ADD_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.put(elementAddress[1]);+ paramsBuffer.put(elementAddress[0]);+ paramsBuffer.put(subscriptionAddress);+ final byte[] modelIdentifier = new byte[]{(byte) ((mModelIdentifier >> 24) & 0xFF),+ (byte) ((mModelIdentifier >> 16) & 0xFF), (byte) ((mModelIdentifier >> 8) & 0xFF), (byte) (mModelIdentifier & 0xFF)};+ paramsBuffer.put(modelIdentifier[1]);+ paramsBuffer.put(modelIdentifier[0]);+ paramsBuffer.put(modelIdentifier[3]);+ paramsBuffer.put(modelIdentifier[2]);+ mParameters = paramsBuffer.array();+ }+ }++ /**+ * Returns the value of the Label UUID publish address+ */+ public UUID getLabelUuid() {+ return labelUuid;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelSubscriptionVirtualAddressDelete.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelSubscriptionVirtualAddressDelete.javanew file mode 100644index 000000000..1c2a84fba--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelSubscriptionVirtualAddressDelete.java@@ -0,0 +1,90 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.UUID;+import java.util.logging.Logger;++/**+ * Creates the ConfigModelSubscriptionVirtualAddressDelete Message.+ */+@SuppressWarnings({"unused"})+public final class ConfigModelSubscriptionVirtualAddressDelete extends ConfigMessage {++ public static final Logger LOG = Logger.getLogger(ConfigModelSubscriptionVirtualAddressDelete.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_MODEL_SUBSCRIPTION_VIRTUAL_ADDRESS_DELETE;++ //Length in bytes+ private static final int CONFIG_MODEL_SUBSCRIPTION_VIRTUAL_ADDRESS_DELETE_LENGTH = 20;+ private static final int VENDOR_MODEL_SUBSCRIPTION_VIRTUAL_ADDRESS_DELETE_LENGTH = CONFIG_MODEL_SUBSCRIPTION_VIRTUAL_ADDRESS_DELETE_LENGTH + 2;++ private final int mElementAddress;+ private final UUID labelUuid;+ private final int mModelIdentifier;++ /**+ * Constructs ConfigModelSubscriptionDelete message.+ *+ * @param elementAddress Address of the element to which the model belongs to.+ * @param labelUuid Value of the Label UUID.+ * @param modelIdentifier Model identifier, 16-bit for Sig model and 32-bit model id for vendor models.+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public ConfigModelSubscriptionVirtualAddressDelete(final int elementAddress,+ /* @NonNull */ final UUID labelUuid,+ final int modelIdentifier) throws IllegalArgumentException {++ if (!MeshAddress.isValidUnicastAddress(elementAddress))+ throw new IllegalArgumentException("Invalid unicast address, unicast address must be a 16-bit value, and must range from 0x0001 to 0x7FFF");+ this.mElementAddress = elementAddress;+ this.labelUuid = labelUuid;+ this.mModelIdentifier = modelIdentifier;+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ @Override+ void assembleMessageParameters() {++ final ByteBuffer paramsBuffer;+ //We check if the model identifier value is within the range of a 16-bit value here. If it is then it is a sigmodel+ final byte[] elementAddress = MeshAddress.addressIntToBytes(mElementAddress);+ final byte[] subscriptionAddress = MeshParserUtils.uuidToBytes(labelUuid);+ if (mModelIdentifier >= Short.MIN_VALUE && mModelIdentifier <= Short.MAX_VALUE) {+ paramsBuffer = ByteBuffer.allocate(CONFIG_MODEL_SUBSCRIPTION_VIRTUAL_ADDRESS_DELETE_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.put(elementAddress[1]);+ paramsBuffer.put(elementAddress[0]);+ paramsBuffer.put(subscriptionAddress);+ paramsBuffer.putShort((short) mModelIdentifier);+ mParameters = paramsBuffer.array();+ } else {+ paramsBuffer = ByteBuffer.allocate(VENDOR_MODEL_SUBSCRIPTION_VIRTUAL_ADDRESS_DELETE_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.put(elementAddress[1]);+ paramsBuffer.put(elementAddress[0]);+ paramsBuffer.put(subscriptionAddress);+ final byte[] modelIdentifier = new byte[]{(byte) ((mModelIdentifier >> 24) & 0xFF),+ (byte) ((mModelIdentifier >> 16) & 0xFF), (byte) ((mModelIdentifier >> 8) & 0xFF), (byte) (mModelIdentifier & 0xFF)};+ paramsBuffer.put(modelIdentifier[1]);+ paramsBuffer.put(modelIdentifier[0]);+ paramsBuffer.put(modelIdentifier[3]);+ paramsBuffer.put(modelIdentifier[2]);+ mParameters = paramsBuffer.array();+ }+ }++ /**+ * Returns the value of the Label UUID of the subscription address+ */+ public UUID getLabelUuid() {+ return labelUuid;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelSubscriptionVirtualAddressOverwrite.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelSubscriptionVirtualAddressOverwrite.javanew file mode 100644index 000000000..6103b32a0--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigModelSubscriptionVirtualAddressOverwrite.java@@ -0,0 +1,91 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.UUID;+import java.util.logging.Logger;++/**+ * Creates the ConfigModelSubscriptionVirtualAddressOverwrite Message.+ * <p>his message will clear the existing subscription list in a model and add a new one</p>+ */+@SuppressWarnings({"unused"})+public final class ConfigModelSubscriptionVirtualAddressOverwrite extends ConfigMessage {++ public static final Logger LOG = Logger.getLogger(ConfigModelSubscriptionVirtualAddressOverwrite.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_MODEL_SUBSCRIPTION_VIRTUAL_ADDRESS_OVERWRITE;++ //Length in bytes+ private static final int CONFIG_MODEL_SUBSCRIPTION_VIRTUAL_ADDRESS_OVERWRITE_LENGTH = 20;+ private static final int VENDOR_MODEL_SUBSCRIPTION_VIRTUAL_ADDRESS_OVERWRITE_LENGTH = CONFIG_MODEL_SUBSCRIPTION_VIRTUAL_ADDRESS_OVERWRITE_LENGTH + 2;++ private final int mElementAddress;+ private final UUID labelUuid;+ private final int mModelIdentifier;++ /**+ * Constructs ConfigModelSubscriptionVirtualAddressOverwrite message.+ *+ * @param elementAddress Address of the element to which the model belongs to.+ * @param labelUuid Value of the Label UUID.+ * @param modelIdentifier Model identifier, 16-bit for Sig model and 32-bit model id for vendor models.+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public ConfigModelSubscriptionVirtualAddressOverwrite(final int elementAddress,+ /* @NonNull */ final UUID labelUuid,+ final int modelIdentifier) throws IllegalArgumentException {++ if (!MeshAddress.isValidUnicastAddress(elementAddress))+ throw new IllegalArgumentException("Invalid unicast address, unicast address must be a 16-bit value, and must range from 0x0001 to 0x7FFF");+ this.mElementAddress = elementAddress;+ this.labelUuid = labelUuid;+ this.mModelIdentifier = modelIdentifier;+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ @Override+ void assembleMessageParameters() {++ final ByteBuffer paramsBuffer;+ //We check if the model identifier value is within the range of a 16-bit value here. If it is then it is a sigmodel+ final byte[] elementAddress = MeshAddress.addressIntToBytes(mElementAddress);+ final byte[] subscriptionAddress = MeshParserUtils.uuidToBytes(labelUuid);+ if (mModelIdentifier >= Short.MIN_VALUE && mModelIdentifier <= Short.MAX_VALUE) {+ paramsBuffer = ByteBuffer.allocate(CONFIG_MODEL_SUBSCRIPTION_VIRTUAL_ADDRESS_OVERWRITE_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.put(elementAddress[1]);+ paramsBuffer.put(elementAddress[0]);+ paramsBuffer.put(subscriptionAddress);+ paramsBuffer.putShort((short) mModelIdentifier);+ mParameters = paramsBuffer.array();+ } else {+ paramsBuffer = ByteBuffer.allocate(VENDOR_MODEL_SUBSCRIPTION_VIRTUAL_ADDRESS_OVERWRITE_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.put(elementAddress[1]);+ paramsBuffer.put(elementAddress[0]);+ paramsBuffer.put(subscriptionAddress);+ final byte[] modelIdentifier = new byte[]{(byte) ((mModelIdentifier >> 24) & 0xFF),+ (byte) ((mModelIdentifier >> 16) & 0xFF), (byte) ((mModelIdentifier >> 8) & 0xFF), (byte) (mModelIdentifier & 0xFF)};+ paramsBuffer.put(modelIdentifier[1]);+ paramsBuffer.put(modelIdentifier[0]);+ paramsBuffer.put(modelIdentifier[3]);+ paramsBuffer.put(modelIdentifier[2]);+ mParameters = paramsBuffer.array();+ }+ }++ /**+ * Returns the value of the Label UUID of the subscription address+ */+ public UUID getLabelUuid() {+ return labelUuid;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNetKeyAdd.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNetKeyAdd.javanew file mode 100644index 000000000..f3e07b505--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNetKeyAdd.java@@ -0,0 +1,50 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.NetworkKey;+import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++public class ConfigNetKeyAdd extends ConfigMessage {++ public static final Logger LOG = Logger.getLogger(ConfigNetKeyAdd.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_NETKEY_ADD;++ private final NetworkKey mNetKey;++ /**+ * Constructs ConfigNetKeyAdd message.+ *+ * @param networkKey Network key for this message+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public ConfigNetKeyAdd(final NetworkKey networkKey) throws IllegalArgumentException {+ if (networkKey.getKey().length != 16)+ throw new IllegalArgumentException("Network key must be 16 bytes");++ this.mNetKey = networkKey;+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }+++ @Override+ void assembleMessageParameters() {+ LOG.info("NetKeyIndex: " + mNetKey.getKeyIndex());+ final byte[] netKeyIndex = MeshParserUtils.addKeyIndexPadding(mNetKey.getKeyIndex());++ final ByteBuffer paramsBuffer = ByteBuffer.allocate(18).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.put(netKeyIndex[1]);+ paramsBuffer.put((byte) ((netKeyIndex[0] & 0xFF) & 0x0F));+ paramsBuffer.put(mNetKey.getKey());+ mParameters = paramsBuffer.array();+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNetKeyDelete.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNetKeyDelete.javanew file mode 100644index 000000000..c7dab48b2--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNetKeyDelete.java@@ -0,0 +1,48 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.NetworkKey;+import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++public class ConfigNetKeyDelete extends ConfigMessage {++ public static final Logger LOG = Logger.getLogger(ConfigNetKeyDelete.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_NETKEY_DELETE;++ private final NetworkKey mNetKey;++ /**+ * Constructs ConfigNetKeyDelete message.+ *+ * @param networkKey Network key for this message+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public ConfigNetKeyDelete(final NetworkKey networkKey) throws IllegalArgumentException {+ if (networkKey.getKey().length != 16)+ throw new IllegalArgumentException("Network key must be 16 bytes");++ this.mNetKey = networkKey;+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }+++ @Override+ void assembleMessageParameters() {+ LOG.info("NetKeyIndex: " + mNetKey.getKeyIndex());+ final byte[] netKeyIndex = MeshParserUtils.addKeyIndexPadding(mNetKey.getKeyIndex());++ final ByteBuffer paramsBuffer = ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.put(netKeyIndex[1]);+ paramsBuffer.put((byte) ((netKeyIndex[0] & 0xFF) & 0x0F));+ mParameters = paramsBuffer.array();+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNetKeyGet.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNetKeyGet.javanew file mode 100644index 000000000..90bd7082e--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNetKeyGet.java@@ -0,0 +1,26 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;++public class ConfigNetKeyGet extends ConfigMessage {++ private static final String TAG = ConfigNetKeyGet.class.getSimpleName();+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_NETKEY_GET;++ /**+ * Constructs ConfigNetKeyGet message.+ */+ public ConfigNetKeyGet() {+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ @Override+ void assembleMessageParameters() {+ //Do nothing as ConfigNetKeyGet message does not have parameters+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNetKeyList.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNetKeyList.javanew file mode 100644index 000000000..0b9ba74a5--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNetKeyList.java@@ -0,0 +1,56 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;++import java.util.ArrayList;+import java.util.List;+import java.util.logging.Logger;++/**+ * Creates the ConfigNetKeyList Message.+ */+public class ConfigNetKeyList extends ConfigStatusMessage {++ public static final Logger LOG = Logger.getLogger(ConfigNetKeyList.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_NETKEY_LIST;+ private final List<Integer> mKeyIndexes;++ /**+ * Constructs the ConfigNetKeyList mMessage.+ *+ * @param message Access Message+ */+ public ConfigNetKeyList(final AccessMessage message) {+ super(message);+ mKeyIndexes = new ArrayList<>();+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ final void parseStatusParameters() {+ mKeyIndexes.addAll(decode(mParameters.length, 0));+ for (Integer keyIndex : mKeyIndexes) {+ LOG.info("Key Index: " + Integer.toHexString(keyIndex));+ }+ }++ @Override+ public final int getOpCode() {+ return OP_CODE;+ }++ /**+ * Returns if the message was successful+ *+ * @return true if the message was successful or false otherwise+ */+ public final boolean isSuccessful() {+ return mStatusCode == 0x00;+ }++ public List<Integer> getKeyIndexes() {+ return mKeyIndexes;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNetKeyStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNetKeyStatus.javanew file mode 100644index 000000000..25045a56d--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNetKeyStatus.java@@ -0,0 +1,65 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;++import java.util.ArrayList;+import java.util.logging.Logger;++/**+ * Creates the ConfigNetKeyStatus Message.+ */+public class ConfigNetKeyStatus extends ConfigStatusMessage {++ public static final Logger LOG = Logger.getLogger(ConfigNetKeyStatus.class.getName());++ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_NETKEY_STATUS;+ private int mNetKeyIndex;++ /**+ * Constructs the ConfigNetKeyStatus mMessage.+ *+ * @param message Access Message+ */+ public ConfigNetKeyStatus(final AccessMessage message) {+ super(message);+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ final void parseStatusParameters() {+ mStatusCode = mParameters[0];+ mStatusCodeName = getStatusCodeName(mStatusCode);+ final ArrayList<Integer> keyIndexes = decode(mParameters.length, 1);+ //NetKey status will only contain one index so we just take the first element+ mNetKeyIndex = keyIndexes.get(0);//ByteBuffer.wrap(netKeyIndex).order(ByteOrder.BIG_ENDIAN).getShort();++ LOG.info("Status code: " + mStatusCode);+ LOG.info("Status message: " + mStatusCodeName);+ LOG.info("Net key index: " + Integer.toHexString(mNetKeyIndex));+ }++ @Override+ public final int getOpCode() {+ return OP_CODE;+ }++ /**+ * Returns the global index of the net key.+ *+ * @return netkey index+ */+ public final int getNetKeyIndex() {+ return mNetKeyIndex;+ }++ /**+ * Returns if the message was successful+ *+ * @return true if the message was successful or false otherwise+ */+ public final boolean isSuccessful() {+ return mStatusCode == 0x00;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNetKeyUpdate.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNetKeyUpdate.javanew file mode 100644index 000000000..c7d3ab30d--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNetKeyUpdate.java@@ -0,0 +1,53 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.NetworkKey;+import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++/**+ * Creates the ConfigNetKeyUpdate message.+ */+public class ConfigNetKeyUpdate extends ConfigMessage {++ public static final Logger LOG = Logger.getLogger(ConfigNetKeyUpdate.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_NETKEY_UPDATE;++ private final NetworkKey mNetKey;++ /**+ * Constructs ConfigNetKeyUpdate message.+ *+ * @param networkKey Network key for this message+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public ConfigNetKeyUpdate(final NetworkKey networkKey) throws IllegalArgumentException {+ if (networkKey.getKey().length != 16)+ throw new IllegalArgumentException("Network key must be 16 bytes");++ this.mNetKey = networkKey;+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }+++ @Override+ void assembleMessageParameters() {+ LOG.info("NetKeyIndex: " + mNetKey.getKeyIndex());+ final byte[] netKeyIndex = MeshParserUtils.addKeyIndexPadding(mNetKey.getKeyIndex());++ final ByteBuffer paramsBuffer = ByteBuffer.allocate(18).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.put(netKeyIndex[0]);+ paramsBuffer.put(netKeyIndex[1]);+ paramsBuffer.put(mNetKey.getKey());+ mParameters = paramsBuffer.array();+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNetworkTransmitStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNetworkTransmitStatus.javanew file mode 100644index 000000000..7acb62654--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNetworkTransmitStatus.java@@ -0,0 +1,59 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;++import java.util.logging.Logger;++/**+ * To be used as a wrapper class for when creating the ConfigNetworkTransmitStatus message.+ */+public final class ConfigNetworkTransmitStatus extends ConfigStatusMessage {++ public static final Logger LOG = Logger.getLogger(ConfigNetworkTransmitStatus.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_NETWORK_TRANSMIT_STATUS;+ private int mNetworkTransmitCount;+ private int mNetworkTransmitIntervalSteps;++ /**+ * Constructs a ConfigNetworkTransmitStatus message.+ *+ * @param message Access message received+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public ConfigNetworkTransmitStatus(final AccessMessage message) {+ super(message);+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ @Override+ final void parseStatusParameters() {+ final byte[] payload = ((AccessMessage) mMessage).getAccessPdu();++ mNetworkTransmitCount = payload[2] & 0b111;+ mNetworkTransmitIntervalSteps = (payload[2] >> 3) & 0b11111;+ }++ /**+ * Returns the Network Transmit Count set in this message+ *+ * @return Network Transmit Count+ */+ public int getNetworkTransmitCount() {+ return mNetworkTransmitCount;+ }++ /**+ * Returns the Network Transmit Interval Steps set in this message+ *+ * @return Network Transmit Interval Steps+ */+ public int getNetworkTransmitIntervalSteps() {+ return mNetworkTransmitIntervalSteps;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNodeIdentityStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNodeIdentityStatus.javanew file mode 100644index 000000000..44cc6736a--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNodeIdentityStatus.java@@ -0,0 +1,72 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++/**+ * Creates the ConfigNodeIdentityStatus message.+ */+public class ConfigNodeIdentityStatus extends ConfigStatusMessage {++ public static final Logger LOG = Logger.getLogger(ConfigNodeIdentityStatus.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_BEACON_STATUS;+ private int netKeyIndex;+ /* @NodeIdentityState */+ private int nodeIdentityState;++ /**+ * Constructs ConfigNodeIdentityStatus message.+ *+ * @param message {@link AccessMessage}+ */+ public ConfigNodeIdentityStatus(final AccessMessage message) {+ super(message);+ mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ void parseStatusParameters() {+ mStatusCode = mParameters[0];+ final byte[] netKeyIndex = new byte[]{(byte) (mParameters[2] & 0x0F), mParameters[1]};+ this.netKeyIndex = ByteBuffer.wrap(netKeyIndex).order(ByteOrder.BIG_ENDIAN).getShort();+ nodeIdentityState = MeshParserUtils.unsignedByteToInt(mParameters[3]);+ LOG.info("Status: " + mStatusCode);+ LOG.info("Node Identity State: " + nodeIdentityState);+ }+++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ /**+ * Returns if the message was successful.+ *+ * @return true if the message was successful or false otherwise.+ */+ public final boolean isSuccessful() {+ return mStatusCode == 0x00;+ }++ /**+ * Returns the NodeIdentityState+ */+ /* @NodeIdentityState */+ public int getNodeIdentityState() {+ return nodeIdentityState;+ }++ /**+ * Returns the net key index.+ */+ public int getNetKeyIndex() {+ return netKeyIndex;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNodeResetStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNodeResetStatus.javanew file mode 100644index 000000000..7208152fd--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigNodeResetStatus.java@@ -0,0 +1,37 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;++import java.util.logging.Logger;++/**+ * To be used as a wrapper class for when creating the ConfigAppKeyStatus Message.+ */+@SuppressWarnings({"unused", "WeakerAccess"})+public class ConfigNodeResetStatus extends ConfigStatusMessage {++ public static final Logger LOG = Logger.getLogger(ConfigNodeResetStatus.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_NODE_RESET_STATUS;++ /**+ * Constructs the ConfigAppKeyStatus mMessage.+ *+ * @param message Access Message+ */+ public ConfigNodeResetStatus(final AccessMessage message) {+ super(message);+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ final void parseStatusParameters() {+ //This message has empty parameters+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigProxySet.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigProxySet.javanew file mode 100644index 000000000..474f65131--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigProxySet.java@@ -0,0 +1,46 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;++import java.lang.annotation.Retention;+import java.lang.annotation.RetentionPolicy;++/**+ * To be used as a wrapper class to create a ConfigProxySet message.+ */+public class ConfigProxySet extends ConfigMessage {++ public static final int PROXY_FEATURE_DISABLED = 0x00;+ public static final int PROXY_FEATURE_ENABLED = 0x01;+ private static final String TAG = ConfigProxySet.class.getSimpleName();+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_GATT_PROXY_SET;+ private final int proxyState;++ /**+ * Constructs ConfigNodeReset message.+ *+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public ConfigProxySet(/* @ProxyState */ final int proxyState) throws IllegalArgumentException {+ if (proxyState != PROXY_FEATURE_DISABLED && proxyState != PROXY_FEATURE_ENABLED)+ throw new IllegalArgumentException("Invalid proxy state value.");+ this.proxyState = proxyState;+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ @Override+ void assembleMessageParameters() {+ mParameters = new byte[]{(byte) proxyState};+ }++ // @Retention(RetentionPolicy.SOURCE)+ // @IntDef({PROXY_FEATURE_DISABLED, PROXY_FEATURE_ENABLED})+ // public @interface ProxyState {+ // }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigProxyStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigProxyStatus.javanew file mode 100644index 000000000..6ba48adf4--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigProxyStatus.java@@ -0,0 +1,53 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;++/**+ * To be used as a wrapper class for when creating the ConfigRelayStatus message.+ */+public final class ConfigProxyStatus extends ConfigStatusMessage {++ private static final String TAG = ConfigProxyStatus.class.getSimpleName();+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_GATT_PROXY_STATUS;+ private int mProxyState;++ /**+ * Constructs a ConfigRelayStatus message.+ *+ * @param message Access message received+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public ConfigProxyStatus(final AccessMessage message) {+ super(message);+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ @Override+ final void parseStatusParameters() {+ final byte[] payload = ((AccessMessage) mMessage).getAccessPdu();+ mProxyState = payload[2];+ }+++ /**+ * Returns the current ConfigProxySet.ProxyState of the node+ */+ /* @ConfigProxySet.ProxyState */+ public int getProxyState() {+ return mProxyState;+ }++ /**+ * Returns true if the proxy feature is currently enabled on the node and false otherwise+ */+ public boolean isProxyFeatureEnabled() {+ return mProxyState == ConfigProxySet.PROXY_FEATURE_ENABLED;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigRelayStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigRelayStatus.javanew file mode 100644index 000000000..991d25cff--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigRelayStatus.java@@ -0,0 +1,73 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;++import java.util.logging.Logger;++/**+ * To be used as a wrapper class for when creating the ConfigRelayStatus message.+ */+@SuppressWarnings({"WeakerAccess"})+public final class ConfigRelayStatus extends ConfigStatusMessage {++ public static final Logger LOG = Logger.getLogger(ConfigRelayStatus.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_RELAY_STATUS;+ private int mRelay;+ private int mRelayRetransmitCount;+ private int mRelayRetransmitIntervalSteps;++ /**+ * Constructs a ConfigRelayStatus message.+ *+ * @param message Access message received+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public ConfigRelayStatus(final AccessMessage message) {+ super(message);+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ @Override+ final void parseStatusParameters() {+ final byte[] payload = ((AccessMessage) mMessage).getAccessPdu();+ mRelay = payload[2];+ mRelayRetransmitCount = payload[3] & 0b111;+ mRelayRetransmitIntervalSteps = (payload[3] >> 3) & 0b11111;+ LOG.info("Relay: " + mRelay);+ LOG.info("Retransmit count: " + mRelayRetransmitCount);+ LOG.info("Retransmit Interval steps: " + mRelayRetransmitIntervalSteps);+ }+++ /**+ * Returns the RelaySettings.RelayState of the node+ */+ /* @RelaySettings.RelayState */+ public int getRelay() {+ return mRelay;+ }++ /**+ * Returns the Relay retransmit count set in this message+ *+ * @return Relay retransmit count+ */+ public int getRelayRetransmitCount() {+ return mRelayRetransmitCount;+ }++ /**+ * Returns the Relay retransmit interval steps set in this message+ *+ * @return Relay retransmit interval steps+ */+ public int getRelayRetransmitIntervalSteps() {+ return mRelayRetransmitIntervalSteps;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigSigModelAppList.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigSigModelAppList.javanew file mode 100644index 000000000..09e934ed6--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigSigModelAppList.java@@ -0,0 +1,89 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.CompositionDataParser;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.util.ArrayList;+import java.util.List;+import java.util.logging.Logger;++/**+ * Creates the ConfigAppKeyList Message.+ */+@SuppressWarnings({"unused", "WeakerAccess"})+public class ConfigSigModelAppList extends ConfigStatusMessage {++ public static final Logger LOG = Logger.getLogger(ConfigSigModelAppList.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_SIG_MODEL_APP_LIST;+ private int mElementAddress;+ private int mModelIdentifier;+ private final List<Integer> mKeyIndexes;++ /**+ * Constructs the ConfigNetKeyList mMessage.+ *+ * @param message Access Message+ */+ public ConfigSigModelAppList(final AccessMessage message) {+ super(message);+ mKeyIndexes = new ArrayList<>();+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ final void parseStatusParameters() {+ mStatusCode = mParameters[0];+ mStatusCodeName = getStatusCodeName(mStatusCode);+ mElementAddress = MeshParserUtils.unsignedBytesToInt(mParameters[1], mParameters[2]);+ mModelIdentifier = MeshParserUtils.unsignedBytesToInt(mParameters[3], mParameters[4]);++ LOG.info("Status code: " + mStatusCode);+ LOG.info("Status message: " + mStatusCodeName);+ LOG.info("Element address: " + MeshAddress.formatAddress(mElementAddress, false));+ LOG.info("Model identifier: " + CompositionDataParser.formatModelIdentifier(mModelIdentifier, false));++ mKeyIndexes.addAll(decode(mParameters.length, 5));+ for (Integer keyIndex : mKeyIndexes) {+ LOG.info("AppKey Index: " + Integer.toHexString(keyIndex));+ }+ }++ @Override+ public final int getOpCode() {+ return OP_CODE;+ }++ /**+ * Returns if the message was successful+ *+ * @return true if the message was successful or false otherwise+ */+ public final boolean isSuccessful() {+ return mStatusCode == 0x00;+ }++ /**+ * Returns the element address+ */+ public int getElementAddress() {+ return mElementAddress;+ }++ /**+ * Returns the model identifier+ */+ public int getModelIdentifier() {+ return mModelIdentifier;+ }++ /**+ * Returns the bound app key indexes+ */+ public List<Integer> getKeyIndexes() {+ return mKeyIndexes;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigSigModelSubscriptionList.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigSigModelSubscriptionList.javanew file mode 100644index 000000000..53b2db97c--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigSigModelSubscriptionList.java@@ -0,0 +1,95 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.util.ArrayList;+import java.util.List;+import java.util.logging.Logger;++/**+ * Creates the ConfigModelSubscriptionStatus Message.+ * <p> This message lists all subscription addresses for a SIG Models </p>+ */+public class ConfigSigModelSubscriptionList extends ConfigStatusMessage {++ public static final Logger LOG = Logger.getLogger(ConfigSigModelSubscriptionList.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_SIG_MODEL_SUBSCRIPTION_LIST;+ private int mElementAddress;+ private int mModelIdentifier;+ private final List<Integer> mSubscriptionAddresses;++ /**+ * Constructs the ConfigModelSubscriptionStatus mMessage.+ *+ * @param message Access Message+ */+ public ConfigSigModelSubscriptionList(final AccessMessage message) {+ super(message);+ mSubscriptionAddresses = new ArrayList<>();+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ final void parseStatusParameters() {+ final AccessMessage message = (AccessMessage) mMessage;+ mStatusCode = mParameters[0];+ mStatusCodeName = getStatusCodeName(mStatusCode);+ mElementAddress = MeshParserUtils.unsignedBytesToInt(mParameters[1], mParameters[2]);+ mModelIdentifier = MeshParserUtils.unsignedBytesToInt(mParameters[3], mParameters[4]);++ LOG.info("Status code: " + mStatusCode);+ LOG.info("Status message: " + mStatusCodeName);+ LOG.info("Element Address: " + MeshAddress.formatAddress(mElementAddress, true));+ LOG.info("Model Identifier: " + Integer.toHexString(mModelIdentifier));++ for (int i = 5; i < mParameters.length; i += 2) {+ final int address = MeshParserUtils.unsignedBytesToInt(mParameters[i], mParameters[i + 1]);+ mSubscriptionAddresses.add(address);+ LOG.info("Subscription Address: " + MeshAddress.formatAddress(address, false));+ }+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ /**+ * Returns the element address that the key was bound to+ *+ * @return element address+ */+ public int getElementAddress() {+ return mElementAddress;+ }++ /**+ * Returns the list of subscription addresses.+ *+ * @return subscription address+ */+ public List<Integer> getSubscriptionAddresses() {+ return mSubscriptionAddresses;+ }++ /**+ * Returns the model identifier+ *+ * @return 16-bit sig model identifier or 32-bit vendor model identifier+ */+ public final int getModelIdentifier() {+ return mModelIdentifier;+ }++ /**+ * Returns if the message was successful+ *+ * @return true if the message was successful or false otherwise+ */+ public final boolean isSuccessful() {+ return mStatusCode == 0x00;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigStatusMessage.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigStatusMessage.javanew file mode 100644index 000000000..993bf4cd3--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigStatusMessage.java@@ -0,0 +1,172 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.ArrayList;++import static org.openremote.agent.protocol.bluetooth.mesh.transport.ConfigStatusMessage.StatusCodeNames.fromStatusCode;++public abstract class ConfigStatusMessage extends MeshMessage {++ protected int mStatusCode;+ protected String mStatusCodeName;++ public ConfigStatusMessage(final AccessMessage message) {+ mMessage = message;+ }++ /**+ * Parses the status parameters returned by a status message+ */+ abstract void parseStatusParameters();++ @Override+ public final int getAkf() {+ return mMessage.getAkf();+ }++ @Override+ public final int getAid() {+ return mMessage.getAid();+ }++ @Override+ public final byte[] getParameters() {+ return mParameters;+ }++ protected ArrayList<Integer> decode(final int dataSize, final int offset) {+ final ArrayList<Integer> arrayList = new ArrayList<>();+ final int size = dataSize - offset;+ if (size == 0) {+ return arrayList;+ }+ if (size == 2) {+ final byte[] netKeyIndex = new byte[]{(byte) (mParameters[offset + 1] & 0x0F), mParameters[offset]};+ final int keyIndex = encode(netKeyIndex);+ arrayList.add(keyIndex);+ } else {+ final int firstKeyIndex = encode(new byte[]{(byte) (mParameters[offset + 1] & 0x0F), mParameters[offset]});+ final int secondNetKeyIndex = encode(new byte[]{+ (byte) ((mParameters[offset + 2] & 0xF0) >> 4),+ (byte) (mParameters[offset + 2] << 4 | ((mParameters[offset + 1] & 0xF0) >> 4))});+ arrayList.add(firstKeyIndex);+ arrayList.add(secondNetKeyIndex);+ arrayList.addAll(decode(dataSize, offset + 3));+ }+ return arrayList;+ }++ private static int encode(final byte[] netKeyIndex) {+ return ByteBuffer.wrap(netKeyIndex).order(ByteOrder.BIG_ENDIAN).getShort();+ }++ /**+ * Returns the status code received by the status message+ *+ * @return Status code+ */+ public final int getStatusCode() {+ return mStatusCode;+ }++ /**+ * Returns the status code name for a status code received by the status message.+ *+ * @return status code name+ */+ public final String getStatusCodeName() {+ return mStatusCodeName;+ }++ /**+ * Returns the status code name for a status code returned by a status message.+ *+ * @param statusCode StatusCode received by the status message+ * @return The specific status code name+ */+ final String getStatusCodeName(final int statusCode) {+ switch (fromStatusCode(statusCode)) {+ case SUCCESS:+ return "Success";+ case INVALID_ADDRESS:+ return "Invalid Address";+ case INVALID_MODEL:+ return "Invalid Model";+ case INVALID_APPKEY_INDEX:+ return "Invalid ApplicationKey Index";+ case INVALID_NETKEY_INDEX:+ return "Invalid NetKey Index";+ case INSUFFICIENT_RESOURCES:+ return "Insufficient Resources";+ case KEY_INDEX_ALREADY_STORED:+ return "Key Index Already Stored";+ case INVALID_PUBLISH_PARAMETERS:+ return "Invalid Publish Parameters";+ case NOT_A_SUBSCRIBE_MODEL:+ return "Not a Subscribe Model";+ case STORAGE_FAILURE:+ return "Storage Failure";+ case FEATURE_NOT_SUPPORTED:+ return "Feature Not Supported";+ case CANNOT_UPDATE:+ return "Cannot Update";+ case CANNOT_REMOVE:+ return "Cannot Remove";+ case CANNOT_BIND:+ return "Cannot Bind";+ case TEMPORARILY_UNABLE_TO_CHANGE_STATE:+ return "Temporarily Unable to Change State";+ case CANNOT_SET:+ return "Cannot Set";+ case UNSPECIFIED_ERROR:+ return "Unspecified Error";+ case INVALID_BINDING:+ return "Invalid Binding";+ case RFU:+ default:+ return "RFU";+ }+ }++ public enum StatusCodeNames {+ SUCCESS(0x00),+ INVALID_ADDRESS(0x01),+ INVALID_MODEL(0x02),+ INVALID_APPKEY_INDEX(0x03),+ INVALID_NETKEY_INDEX(0x04),+ INSUFFICIENT_RESOURCES(0x05),+ KEY_INDEX_ALREADY_STORED(0x06),+ INVALID_PUBLISH_PARAMETERS(0x07),+ NOT_A_SUBSCRIBE_MODEL(0x08),+ STORAGE_FAILURE(0x09),+ FEATURE_NOT_SUPPORTED(0x0A),+ CANNOT_UPDATE(0x0B),+ CANNOT_REMOVE(0x0C),+ CANNOT_BIND(0x0D),+ TEMPORARILY_UNABLE_TO_CHANGE_STATE(0x0E),+ CANNOT_SET(0x0F),+ UNSPECIFIED_ERROR(0x10),+ INVALID_BINDING(0x11),+ RFU(0x12);++ private final int statusCode;++ StatusCodeNames(final int statusCode) {+ this.statusCode = statusCode;+ }++ public static StatusCodeNames fromStatusCode(final int statusCode) {+ for (StatusCodeNames code : values()) {+ if (code.getStatusCode() == statusCode) {+ return code;+ }+ }+ throw new IllegalArgumentException("Enum not found in StatusCodeNames");+ }++ public final int getStatusCode() {+ return statusCode;+ }+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigVendorModelAppList.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigVendorModelAppList.javanew file mode 100644index 000000000..c178545c5--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigVendorModelAppList.java@@ -0,0 +1,92 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.CompositionDataParser;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.ArrayList;+import java.util.List;+import java.util.logging.Logger;++/**+ * Creates the ConfigAppKeyList Message.+ */+@SuppressWarnings({"unused", "WeakerAccess"})+public class ConfigVendorModelAppList extends ConfigStatusMessage {++ public static final Logger LOG = Logger.getLogger(ConfigVendorModelAppList.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_VENDOR_MODEL_APP_LIST;+ private int mElementAddress;+ private int mModelIdentifier;+ private final List<Integer> mKeyIndexes;++ /**+ * Constructs the ConfigNetKeyList mMessage.+ *+ * @param message Access Message+ */+ public ConfigVendorModelAppList(final AccessMessage message) {+ super(message);+ mKeyIndexes = new ArrayList<>();+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ final void parseStatusParameters() {+ mStatusCode = mParameters[0];+ mStatusCodeName = getStatusCodeName(mStatusCode);+ mElementAddress = MeshParserUtils.unsignedBytesToInt(mParameters[1], mParameters[2]);+ final byte[] modelIdentifier = new byte[]{mParameters[4], mParameters[3], mParameters[6], mParameters[5]};+ mModelIdentifier = ByteBuffer.wrap(modelIdentifier).order(ByteOrder.BIG_ENDIAN).getInt();++ LOG.info("Status code: " + mStatusCode);+ LOG.info("Status message: " + mStatusCodeName);+ LOG.info("Element address: " + MeshAddress.formatAddress(mElementAddress, false));+ LOG.info("Model identifier: " + CompositionDataParser.formatModelIdentifier(mModelIdentifier, false));++ mKeyIndexes.addAll(decode(mParameters.length, 7));+ for (Integer keyIndex : mKeyIndexes) {+ LOG.info("AppKey Index: " + Integer.toHexString(keyIndex));+ }+ }++ @Override+ public final int getOpCode() {+ return OP_CODE;+ }++ /**+ * Returns if the message was successful+ *+ * @return true if the message was successful or false otherwise+ */+ public final boolean isSuccessful() {+ return mStatusCode == 0x00;+ }++ /**+ * Returns the element address+ */+ public int getElementAddress() {+ return mElementAddress;+ }++ /**+ * Returns the model identifier+ */+ public int getModelIdentifier() {+ return mModelIdentifier;+ }++ /**+ * Returns the bound app key indexes+ */+ public List<Integer> getKeyIndexes() {+ return mKeyIndexes;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigVendorModelSubscriptionList.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigVendorModelSubscriptionList.javanew file mode 100644index 000000000..fc122eb12--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigVendorModelSubscriptionList.java@@ -0,0 +1,97 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.util.ArrayList;+import java.util.List;+import java.util.logging.Logger;++/**+ * Creates the ConfigModelSubscriptionStatus Message.+ * <p> This message lists all subscription addresses for a SIG Models </p>+ */+@SuppressWarnings({"unused", "WeakerAccess"})+public class ConfigVendorModelSubscriptionList extends ConfigStatusMessage {++ public static final Logger LOG = Logger.getLogger(ConfigVendorModelSubscriptionList.class.getName());+ private static final int OP_CODE = ConfigMessageOpCodes.CONFIG_VENDOR_MODEL_SUBSCRIPTION_LIST;+ private int mElementAddress;+ private int mModelIdentifier;+ private final List<Integer> mSubscriptionAddresses;++ /**+ * Constructs the ConfigModelSubscriptionStatus mMessage.+ *+ * @param message Access Message+ */+ public ConfigVendorModelSubscriptionList(final AccessMessage message) {+ super(message);+ mSubscriptionAddresses = new ArrayList<>();+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ final void parseStatusParameters() {+ final AccessMessage message = (AccessMessage) mMessage;+ mStatusCode = mParameters[0];+ mStatusCodeName = getStatusCodeName(mStatusCode);+ mElementAddress = MeshParserUtils.unsignedBytesToInt(mParameters[1], mParameters[2]);+ mModelIdentifier = MeshParserUtils.bytesToInt(new byte[]{mParameters[4], mParameters[3], mParameters[6], mParameters[5]});++ LOG.info("Status code: " + mStatusCode);+ LOG.info("Status message: " + mStatusCodeName);+ LOG.info("Element Address: " + MeshAddress.formatAddress(mElementAddress, true));+ LOG.info("Model Identifier: " + Integer.toHexString(mModelIdentifier));++ for (int i = 7; i < mParameters.length; i += 2) {+ final int address = MeshParserUtils.unsignedBytesToInt(mParameters[i], mParameters[i + 1]);+ mSubscriptionAddresses.add(address);+ LOG.info("Subscription Address: " + MeshAddress.formatAddress(address, false));+ }+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ /**+ * Returns the element address that the key was bound to+ *+ * @return element address+ */+ public int getElementAddress() {+ return mElementAddress;+ }++ /**+ * Returns the list of subscription addresses.+ *+ * @return subscription address+ */+ public List<Integer> getSubscriptionAddresses() {+ return mSubscriptionAddresses;+ }++ /**+ * Returns the model identifier+ *+ * @return 16-bit sig model identifier or 32-bit vendor model identifier+ */+ public final int getModelIdentifier() {+ return mModelIdentifier;+ }++ /**+ * Returns if the message was successful+ *+ * @return true if the message was successful or false otherwise+ */+ public final boolean isSuccessful() {+ return mStatusCode == 0x00;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ControlMessage.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ControlMessage.javanew file mode 100644index 000000000..54255c294--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ControlMessage.java@@ -0,0 +1,47 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.control.TransportControlMessage;++import java.util.HashMap;+import java.util.Map;++public final class ControlMessage extends Message {++ protected Map<Integer, byte[]> lowerTransportControlPdu = new HashMap<>();+ private byte[] transportControlPdu;+ private TransportControlMessage transportControlMessage;++ public ControlMessage() {+ this.ctl = 1;+ }++ @Override+ public int getCtl() {+ return ctl;+ }++ public byte[] getTransportControlPdu() {+ return transportControlPdu;+ }++ public void setTransportControlPdu(final byte[] transportControlPdu) {+ this.transportControlPdu = transportControlPdu;+ }++ public Map<Integer, byte[]> getLowerTransportControlPdu() {+ return lowerTransportControlPdu;+ }++ public void setLowerTransportControlPdu(final Map<Integer, byte[]> segmentedAccessMessages) {+ this.lowerTransportControlPdu = segmentedAccessMessages;+ }++ public TransportControlMessage getTransportControlMessage() {+ return transportControlMessage;+ }++ public void setTransportControlMessage(final TransportControlMessage transportControlMessage) {+ this.transportControlMessage = transportControlMessage;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/DefaultNoOperationMessageState.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/DefaultNoOperationMessageState.javanew file mode 100644index 000000000..2acd1ed2e--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/DefaultNoOperationMessageState.java@@ -0,0 +1,572 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.Features;+import org.openremote.agent.protocol.bluetooth.mesh.Group;+import org.openremote.agent.protocol.bluetooth.mesh.MeshManagerApi;+import org.openremote.agent.protocol.bluetooth.mesh.MeshNetwork;+import org.openremote.agent.protocol.bluetooth.mesh.NetworkKey;+import org.openremote.agent.protocol.bluetooth.mesh.control.BlockAcknowledgementMessage;+import org.openremote.agent.protocol.bluetooth.mesh.control.TransportControlMessage;+import org.openremote.agent.protocol.bluetooth.mesh.models.ConfigurationServerModel;+import org.openremote.agent.protocol.bluetooth.mesh.models.SceneServer;+import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ApplicationMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ProxyConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.AddressArray;+import org.openremote.agent.protocol.bluetooth.mesh.utils.ExtendedInvalidCipherTextException;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;+import org.openremote.agent.protocol.bluetooth.mesh.utils.NetworkTransmitSettings;+import org.openremote.agent.protocol.bluetooth.mesh.utils.ProxyFilter;+import org.openremote.agent.protocol.bluetooth.mesh.utils.ProxyFilterType;+import org.openremote.agent.protocol.bluetooth.mesh.utils.RelaySettings;++import java.util.ArrayList;+import java.util.List;+import java.util.UUID;+import java.util.logging.Logger;++import static org.openremote.agent.protocol.bluetooth.mesh.models.SigModelParser.CONFIGURATION_SERVER;+import static org.openremote.agent.protocol.bluetooth.mesh.models.SigModelParser.SCENE_SERVER;+import static org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress.isValidUnassignedAddress;++class DefaultNoOperationMessageState extends MeshMessageState {++ public static final Logger LOG = Logger.getLogger(DefaultNoOperationMessageState.class.getName());++ /**+ * Constructs the DefaultNoOperationMessageState+ *+ * @param meshMessage {@link MeshMessage} Mesh message to be sent+ * @param meshTransport {@link MeshTransport} Mesh transport+ * @param callbacks {@link InternalMeshMsgHandlerCallbacks} callbacks+ */+ DefaultNoOperationMessageState(/* @Nullable */ final MeshMessage meshMessage,+ final MeshTransport meshTransport,+ final InternalMeshMsgHandlerCallbacks callbacks) {+ super(meshMessage, meshTransport, callbacks);+ }++ @Override+ public synchronized MessageState getState() {+ return null;+ }++ synchronized void parseMeshPdu(final NetworkKey key,+ final ProvisionedMeshNode node,+ final byte[] pdu,+ final byte[] networkHeader,+ final byte[] decryptedNetworkPayload,+ final int ivIndex,+ final byte[] sequenceNumber) {+ final Message message;+ try {+ message = mMeshTransport.parseMeshMessage(key, node, pdu, networkHeader, decryptedNetworkPayload, ivIndex, sequenceNumber);+ if (message != null) {+ if (message instanceof AccessMessage) {+ parseAccessMessage((AccessMessage) message);+ } else {+ parseControlMessage((ControlMessage) message);+ }+ } else {+ LOG.info("Message reassembly may not be completed yet!");+ }+ } catch (ExtendedInvalidCipherTextException e) {+ LOG.severe("Decryption failed in " + e.getTag() + " : " + e.getMessage());+ mMeshStatusCallbacks.onMessageDecryptionFailed(e.getTag(), e.getMessage());+ }+ }++ /**+ * Parses Access message received+ *+ * @param message access message received by the acccess layer+ */+ private void parseAccessMessage(final AccessMessage message) {+ final ProvisionedMeshNode node = mInternalTransportCallbacks.getNode(message.getSrc());+ final int opCodeLength = MeshParserUtils.getOpCodeLength(message.getAccessPdu()[0] & 0xFF);+ //OpCode length+ switch (opCodeLength) {+ case 1:+ if (message.getOpCode() == ConfigMessageOpCodes.CONFIG_COMPOSITION_DATA_STATUS) {+ final ConfigCompositionDataStatus status = new ConfigCompositionDataStatus(message);+ if (!isReceivedViaProxyFilter(message)) {+ node.setCompositionData(status);+ }+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ } else if (message.getOpCode() == ApplicationMessageOpCodes.SCENE_STATUS) {+ final SceneStatus sceneStatus = new SceneStatus(message);+ if (sceneStatus.isSuccessful()) {+ final MeshModel model = getMeshModel(node, sceneStatus.getSrc(), SCENE_SERVER);+ if (model != null) {+ final SceneServer sceneServer = ((SceneServer) model);+ sceneServer.currentScene = sceneStatus.getCurrentScene();+ sceneServer.targetScene = sceneStatus.getTargetScene();+ }+ }+ mInternalTransportCallbacks.updateMeshNetwork(sceneStatus);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), sceneStatus);+ } else if (message.getOpCode() == ConfigMessageOpCodes.CONFIG_HEARTBEAT_PUBLICATION_STATUS) {+ final ConfigHeartbeatPublicationStatus status = new ConfigHeartbeatPublicationStatus(message);+ if (!isReceivedViaProxyFilter(message)) {+ if (status.isSuccessful()) {+ final MeshModel model = getMeshModel(node, status.getSrc(), CONFIGURATION_SERVER);+ if (model != null) {+ ((ConfigurationServerModel) model).+ setHeartbeatPublication(!isValidUnassignedAddress(status.getHeartbeatPublication().getDst()) ? status.getHeartbeatPublication() : null);+ }+ }+ }+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ } else {+ handleUnknownPdu(message);+ }+ break;+ case 2:+ if (message.getOpCode() == ConfigMessageOpCodes.CONFIG_DEFAULT_TTL_STATUS) {+ final ConfigDefaultTtlStatus status = new ConfigDefaultTtlStatus(message);+ if (!isReceivedViaProxyFilter(message)) {+ node.setTtl(status.getTtl());+ }+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ } else if (message.getOpCode() == ConfigMessageOpCodes.CONFIG_NETKEY_STATUS) {+ final ConfigNetKeyStatus status = new ConfigNetKeyStatus(message);+ if (!isReceivedViaProxyFilter(message)) {+ if (status.isSuccessful()) {+ if (mMeshMessage instanceof ConfigNetKeyAdd) {+ node.setAddedNetKeyIndex(status.getNetKeyIndex());+ } else if (mMeshMessage instanceof ConfigNetKeyUpdate) {+ node.updateAddedNetKey(status.getNetKeyIndex());+ } else if (mMeshMessage instanceof ConfigNetKeyDelete) {+ node.removeAddedNetKeyIndex(status.getNetKeyIndex());+ }+ }+ }+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ } else if (message.getOpCode() == ConfigMessageOpCodes.CONFIG_NETKEY_LIST) {+ final ConfigNetKeyList netKeyList = new ConfigNetKeyList(message);+ if (!isReceivedViaProxyFilter(message)) {+ if (netKeyList.isSuccessful()) {+ node.updateNetKeyList(netKeyList.getKeyIndexes());+ }+ }+ mInternalTransportCallbacks.updateMeshNetwork(netKeyList);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), netKeyList);+ } else if (message.getOpCode() == ConfigMessageOpCodes.CONFIG_APPKEY_STATUS) {+ final ConfigAppKeyStatus status = new ConfigAppKeyStatus(message);+ if (!isReceivedViaProxyFilter(message)) {+ if (status.isSuccessful()) {+ if (mMeshMessage instanceof ConfigAppKeyAdd) {+ node.setAddedAppKeyIndex(status.getAppKeyIndex());+ } else if (mMeshMessage instanceof ConfigAppKeyUpdate) {+ node.updateAddedAppKey(status.getAppKeyIndex());+ } else if (mMeshMessage instanceof ConfigAppKeyDelete) {+ node.removeAddedAppKeyIndex(status.getAppKeyIndex());+ }+ }+ }+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ } else if (message.getOpCode() == ConfigMessageOpCodes.CONFIG_APPKEY_LIST) {+ final ConfigAppKeyList appKeyList = new ConfigAppKeyList(message);+ if (!isReceivedViaProxyFilter(message)) {+ if (appKeyList.isSuccessful()) {+ node.updateAppKeyList(appKeyList.getNetKeyIndex(), appKeyList.getKeyIndexes(),+ mInternalTransportCallbacks.getApplicationKeys(appKeyList.getNetKeyIndex()));+ }+ }+ mInternalTransportCallbacks.updateMeshNetwork(appKeyList);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), appKeyList);+ } else if (message.getOpCode() == ConfigMessageOpCodes.CONFIG_MODEL_APP_STATUS) {+ final ConfigModelAppStatus status = new ConfigModelAppStatus(message);+ if (!isReceivedViaProxyFilter(message)) {+ if (status.isSuccessful()) {+ if (mMeshMessage instanceof ConfigModelAppBind) {+ node.setAppKeyBindStatus(status);+ } else {+ node.setAppKeyUnbindStatus(status);+ }+ }+ }+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ } else if (message.getOpCode() == ConfigMessageOpCodes.CONFIG_SIG_MODEL_APP_LIST) {+ final ConfigSigModelAppList appKeyList = new ConfigSigModelAppList(message);+ if (!isReceivedViaProxyFilter(message)) {+ if (appKeyList.isSuccessful()) {+ final MeshModel model = getMeshModel(node, appKeyList.getElementAddress(), appKeyList.getModelIdentifier());+ if (model != null) {+ model.setBoundAppKeyIndexes(appKeyList.getKeyIndexes());+ }+ }+ }+ mInternalTransportCallbacks.updateMeshNetwork(appKeyList);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), appKeyList);+ } else if (message.getOpCode() == ConfigMessageOpCodes.CONFIG_VENDOR_MODEL_APP_LIST) {+ final ConfigVendorModelAppList appKeyList = new ConfigVendorModelAppList(message);+ if (!isReceivedViaProxyFilter(message)) {+ if (appKeyList.isSuccessful()) {+ final MeshModel model = getMeshModel(node, appKeyList.getElementAddress(), appKeyList.getModelIdentifier());+ if (model != null) {+ model.setBoundAppKeyIndexes(appKeyList.getKeyIndexes());+ }+ }+ }+ mInternalTransportCallbacks.updateMeshNetwork(appKeyList);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), appKeyList);+ } else if (message.getOpCode() == ConfigMessageOpCodes.CONFIG_MODEL_PUBLICATION_STATUS) {+ final ConfigModelPublicationStatus status = new ConfigModelPublicationStatus(message);+ if (!isReceivedViaProxyFilter(message)) {+ if (status.isSuccessful()) {+ final MeshModel model = getMeshModel(node, status.getElementAddress(), status.getModelIdentifier());+ if (model != null) {+ if (mMeshMessage instanceof ConfigModelPublicationGet) {+ model.updatePublicationStatus(status);+ } else if (mMeshMessage instanceof ConfigModelPublicationSet) {+ model.setPublicationStatus(status, null);+ } else if (mMeshMessage instanceof ConfigModelPublicationVirtualAddressSet) {+ final UUID labelUUID = ((ConfigModelPublicationVirtualAddressSet) mMeshMessage).+ getLabelUuid();+ model.setPublicationStatus(status, labelUUID);+ }+ }+ }+ }+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ } else if (message.getOpCode() == ConfigMessageOpCodes.CONFIG_MODEL_SUBSCRIPTION_STATUS) {+ final ConfigModelSubscriptionStatus status = new ConfigModelSubscriptionStatus(message);+ if (!isReceivedViaProxyFilter(message)) {+ if (status.isSuccessful()) {+ final MeshModel model = getMeshModel(node, status.getElementAddress(), status.getModelIdentifier());+ if (model != null) {+ if (mMeshMessage instanceof ConfigModelSubscriptionAdd) {+ model.addSubscriptionAddress(status.getSubscriptionAddress());+ } else if (mMeshMessage instanceof ConfigModelSubscriptionVirtualAddressAdd) {+ model.addSubscriptionAddress(((ConfigModelSubscriptionVirtualAddressAdd) mMeshMessage).+ getLabelUuid(), status.getSubscriptionAddress());+ } else if (mMeshMessage instanceof ConfigModelSubscriptionOverwrite) {+ model.overwriteSubscriptionAddress(status.getSubscriptionAddress());+ } else if (mMeshMessage instanceof ConfigModelSubscriptionVirtualAddressOverwrite) {+ model.overwriteSubscriptionAddress(((ConfigModelSubscriptionVirtualAddressOverwrite) mMeshMessage).+ getLabelUuid(), status.getSubscriptionAddress());+ } else if (mMeshMessage instanceof ConfigModelSubscriptionDelete) {+ model.removeSubscriptionAddress(status.getSubscriptionAddress());+ } else if (mMeshMessage instanceof ConfigModelSubscriptionVirtualAddressDelete) {+ model.removeSubscriptionAddress(((ConfigModelSubscriptionVirtualAddressDelete) mMeshMessage).+ getLabelUuid(), status.getSubscriptionAddress());+ } else if (mMeshMessage instanceof ConfigModelSubscriptionDeleteAll) {+ model.removeAllSubscriptionAddresses();+ }+ }+ }+ }+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ } else if (message.getOpCode() == ConfigMessageOpCodes.CONFIG_SIG_MODEL_SUBSCRIPTION_LIST) {+ final ConfigSigModelSubscriptionList status = new ConfigSigModelSubscriptionList(message);+ if (!isReceivedViaProxyFilter(message)) {+ if (status.isSuccessful()) {+ final MeshModel model = getMeshModel(node, status.getElementAddress(), status.getModelIdentifier());+ if (model != null) {+ model.updateSubscriptionAddressesList(status.getSubscriptionAddresses());+ }+ createGroups(status.getSubscriptionAddresses());+ }+ }+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ } else if (message.getOpCode() == ConfigMessageOpCodes.CONFIG_VENDOR_MODEL_SUBSCRIPTION_LIST) {+ final ConfigVendorModelSubscriptionList status = new ConfigVendorModelSubscriptionList(message);+ if (!isReceivedViaProxyFilter(message)) {+ if (status.isSuccessful()) {+ final MeshModel model = getMeshModel(node, status.getElementAddress(), status.getModelIdentifier());+ if (model != null) {+ model.updateSubscriptionAddressesList(status.getSubscriptionAddresses());+ }+ createGroups(status.getSubscriptionAddresses());+ }+ }+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ } else if (message.getOpCode() == ConfigMessageOpCodes.CONFIG_HEARTBEAT_SUBSCRIPTION_STATUS) {+ final ConfigHeartbeatSubscriptionStatus status = new ConfigHeartbeatSubscriptionStatus(message);+ if (!isReceivedViaProxyFilter(message)) {+ if (status.isSuccessful()) {+ final MeshModel model = getMeshModel(node, message.getSrc(), CONFIGURATION_SERVER);+ if (model != null) {+ ((ConfigurationServerModel) model).+ setHeartbeatSubscription((!isValidUnassignedAddress(status.getHeartbeatSubscription().getSrc()) ||+ !isValidUnassignedAddress(status.getHeartbeatSubscription().getDst()))+ ? status.getHeartbeatSubscription() : null);+ }+ }+ }+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ } else if (message.getOpCode() == ConfigMessageOpCodes.CONFIG_NODE_IDENTITY_STATUS) {+ final ConfigNodeIdentityStatus status = new ConfigNodeIdentityStatus(message);+ if (!isReceivedViaProxyFilter(message)) {+ node.nodeIdentityState = status.getNodeIdentityState();+ }+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ } else if (message.getOpCode() == ConfigMessageOpCodes.CONFIG_NODE_RESET_STATUS) {+ final ConfigNodeResetStatus status = new ConfigNodeResetStatus(message);+ if (!isReceivedViaProxyFilter(message)) {+ mInternalTransportCallbacks.onMeshNodeReset(node);+ }+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ } else if (message.getOpCode() == ConfigMessageOpCodes.CONFIG_NETWORK_TRANSMIT_STATUS) {+ final ConfigNetworkTransmitStatus status = new ConfigNetworkTransmitStatus(message);+ final NetworkTransmitSettings networkTransmitSettings =+ new NetworkTransmitSettings(status.getNetworkTransmitCount(), status.getNetworkTransmitIntervalSteps());+ node.setNetworkTransmitSettings(networkTransmitSettings);+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ } else if (message.getOpCode() == ConfigMessageOpCodes.CONFIG_RELAY_STATUS) {+ final ConfigRelayStatus status = new ConfigRelayStatus(message);+ if (!isReceivedViaProxyFilter(message)) {+ final RelaySettings relaySettings =+ new RelaySettings(status.getRelayRetransmitCount(), status.getRelayRetransmitIntervalSteps());+ node.setRelaySettings(relaySettings);+ }+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ } else if (message.getOpCode() == ConfigMessageOpCodes.CONFIG_BEACON_STATUS) {+ final ConfigBeaconStatus status = new ConfigBeaconStatus(message);+ if (!isReceivedViaProxyFilter(message)) {+ node.setSecureNetworkBeaconSupported(status.isEnable());+ }+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ } else if (message.getOpCode() == ConfigMessageOpCodes.CONFIG_FRIEND_STATUS) {+ final ConfigFriendStatus status = new ConfigFriendStatus(message);+ if (!isReceivedViaProxyFilter(message)) {+ node.getNodeFeatures().setFriend(status.isEnable() ? Features.ENABLED : Features.DISABLED);+ }+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ } else if (message.getOpCode() == ConfigMessageOpCodes.CONFIG_KEY_REFRESH_PHASE_STATUS) {+ final ConfigKeyRefreshPhaseStatus status = new ConfigKeyRefreshPhaseStatus(message);+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ } else if (message.getOpCode() == ConfigMessageOpCodes.CONFIG_GATT_PROXY_STATUS) {+ final ConfigProxyStatus status = new ConfigProxyStatus(message);+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ } else if (message.getOpCode() == ConfigMessageOpCodes.CONFIG_LOW_POWER_NODE_POLLTIMEOUT_STATUS) {+ final ConfigLowPowerNodePollTimeoutStatus status = new ConfigLowPowerNodePollTimeoutStatus(message);+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ } else if (message.getOpCode() == ApplicationMessageOpCodes.GENERIC_ON_OFF_STATUS) {+ final GenericOnOffStatus status = new GenericOnOffStatus(message);+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ } else if (message.getOpCode() == ApplicationMessageOpCodes.GENERIC_LEVEL_STATUS) {+ final GenericLevelStatus genericLevelStatus = new GenericLevelStatus(message);+ mInternalTransportCallbacks.updateMeshNetwork(genericLevelStatus);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), genericLevelStatus);+ } else if (message.getOpCode() == ApplicationMessageOpCodes.LIGHT_LIGHTNESS_STATUS) {+ final LightLightnessStatus lightLightnessStatus = new LightLightnessStatus(message);+ mInternalTransportCallbacks.updateMeshNetwork(lightLightnessStatus);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), lightLightnessStatus);+ } else if (message.getOpCode() == ApplicationMessageOpCodes.LIGHT_CTL_STATUS) {+ final LightCtlStatus lightCtlStatus = new LightCtlStatus(message);+ mInternalTransportCallbacks.updateMeshNetwork(lightCtlStatus);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), lightCtlStatus);+ } else if (message.getOpCode() == ApplicationMessageOpCodes.LIGHT_HSL_STATUS) {+ final LightHslStatus lightHslStatus = new LightHslStatus(message);+ mInternalTransportCallbacks.updateMeshNetwork(lightHslStatus);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), lightHslStatus);+ } else if (message.getOpCode() == ApplicationMessageOpCodes.SCENE_REGISTER_STATUS) {+ if (mMeshMessage instanceof SceneStore) {+ final SceneRegisterStatus status = new SceneRegisterStatus(message);+ storeScene(node, status);+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ } else if (mMeshMessage instanceof SceneRecall) {+ final SceneStatus status = new SceneStatus(message);+ storeScene(node, status);+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ } else if (mMeshMessage instanceof SceneDelete) {+ final SceneRegisterStatus status = new SceneRegisterStatus(message);+ deleteScene(node, status);+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ }++ } else {+ handleUnknownPdu(message);+ }+ break;+ case 3:+ if (mMeshMessage instanceof VendorModelMessageAcked) {+ final VendorModelMessageAcked vendorModelMessageAcked = (VendorModelMessageAcked) mMeshMessage;+ final VendorModelMessageStatus status = new VendorModelMessageStatus(message, vendorModelMessageAcked.getModelIdentifier());+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ LOG.info("Vendor model Access PDU Received: " + MeshParserUtils.bytesToHex(message.getAccessPdu(), false));+ } else if (mMeshMessage instanceof VendorModelMessageUnacked) {+ final VendorModelMessageUnacked vendorModelMessageUnacked = (VendorModelMessageUnacked) mMeshMessage;+ final VendorModelMessageStatus status = new VendorModelMessageStatus(message, vendorModelMessageUnacked.getModelIdentifier());+ mMeshStatusCallbacks.onMeshMessageReceived(message.getSrc(), status);+ } else {+ handleUnknownPdu(message);+ }+ break;+ }+ }++ private void handleUnknownPdu(final AccessMessage message) {+ LOG.info("Unknown Access PDU Received: " + MeshParserUtils.bytesToHex(message.getAccessPdu(), false));+ mMeshStatusCallbacks.onUnknownPduReceived(message.getSrc(), message.getAccessPdu());+ }++ /**+ * Parses control message received+ *+ * @param controlMessage control message received by the transport layer+ */+ private void parseControlMessage(final ControlMessage controlMessage) {+ //Get the segment count count of the access message+ final int segmentCount = message.getNetworkLayerPdu().size();+ if (controlMessage.getPduType() == MeshManagerApi.PDU_TYPE_NETWORK) {+ final TransportControlMessage transportControlMessage = controlMessage.getTransportControlMessage();+ if (transportControlMessage.getState() == TransportControlMessage.TransportControlMessageState.LOWER_TRANSPORT_BLOCK_ACKNOWLEDGEMENT) {+ LOG.info("Acknowledgement payload: " + MeshParserUtils.bytesToHex(controlMessage.getTransportControlPdu(), false));+ final ArrayList<Integer> retransmitPduIndexes = BlockAcknowledgementMessage.getSegmentsToBeRetransmitted(controlMessage.getTransportControlPdu(), segmentCount);+ mMeshStatusCallbacks.onBlockAcknowledgementReceived(controlMessage.getSrc(), controlMessage);+ executeResend(retransmitPduIndexes);+ } else {+ LOG.info("Unexpected control message received, ignoring message");+ mMeshStatusCallbacks.onUnknownPduReceived(controlMessage.getSrc(), controlMessage.getTransportControlPdu());+ }+ } else if (controlMessage.getPduType() == MeshManagerApi.PDU_TYPE_PROXY_CONFIGURATION) {+ if (controlMessage.getOpCode() == ProxyConfigMessageOpCodes.FILTER_STATUS) {+ final ProxyConfigFilterStatus status = new ProxyConfigFilterStatus(controlMessage);+ final ProxyFilter filter;+ if (mMeshMessage instanceof ProxyConfigSetFilterType) {+ filter = new ProxyFilter(status.getFilterType());+ mInternalTransportCallbacks.setProxyFilter(filter);+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(controlMessage.getSrc(), status);+ } else if (mMeshMessage instanceof ProxyConfigAddAddressToFilter) {+ filter = updateProxyFilter(mInternalTransportCallbacks.getProxyFilter(), status.getFilterType());+ final ProxyConfigAddAddressToFilter addAddressToFilter = (ProxyConfigAddAddressToFilter) mMeshMessage;+ for (AddressArray addressArray : addAddressToFilter.getAddresses()) {+ filter.addAddress(addressArray);+ }+ mInternalTransportCallbacks.setProxyFilter(filter);+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(controlMessage.getSrc(), status);++ } else if (mMeshMessage instanceof ProxyConfigRemoveAddressFromFilter) {+ filter = updateProxyFilter(mInternalTransportCallbacks.getProxyFilter(), status.getFilterType());+ final ProxyConfigRemoveAddressFromFilter removeAddressFromFilter = (ProxyConfigRemoveAddressFromFilter) mMeshMessage;+ for (AddressArray addressArray : removeAddressFromFilter.getAddresses()) {+ filter.removeAddress(addressArray);+ }+ mInternalTransportCallbacks.setProxyFilter(filter);+ mInternalTransportCallbacks.updateMeshNetwork(status);+ mMeshStatusCallbacks.onMeshMessageReceived(controlMessage.getSrc(), status);+ }+ }+ }+ }++ /**+ * Checks and returns a new filter or the existing filter+ *+ * @param currentFilter Proxy filter that is currently set on this node+ * @param filterType Type of {@link ProxyFilterType} that was received by the status message+ */+ private ProxyFilter updateProxyFilter(final ProxyFilter currentFilter,+ final ProxyFilterType filterType) {+ if (currentFilter != null && currentFilter.getFilterType().getType() == filterType.getType()) {+ return currentFilter;+ } else {+ return new ProxyFilter(filterType);+ }+ }++ @SuppressWarnings("BooleanMethodIsAlwaysInverted")+ private boolean isReceivedViaProxyFilter(final Message message) {+ final ProxyFilter filter = mInternalTransportCallbacks.getProxyFilter();+ if (filter != null) {+ if (filter.getFilterType().getType() == ProxyFilterType.INCLUSION_LIST_FILTER) {+ return filterAddressMatches(filter, message.getDst());+ } else {+ return !filterAddressMatches(filter, message.getDst());+ }+ }+ return false;+ }++ private boolean filterAddressMatches(final ProxyFilter filter, final int dst) {+ for (AddressArray addressArray : filter.getAddresses()) {+ final int address = MeshParserUtils.unsignedBytesToInt(addressArray.getAddress()[1], addressArray.getAddress()[0]);+ if (address == dst) {+ return true;+ }+ }+ return false;+ }++ private void createGroups(final List<Integer> subscriptionAddresses) {+ final MeshNetwork network = mInternalTransportCallbacks.getMeshNetwork();+ for (Integer groupAddress : subscriptionAddresses) {+ Group group = network.getGroup(groupAddress);+ if (group == null) {+ group = new Group(groupAddress, network.getMeshUUID());+ group.setName("Unknown Group");+ network.getGroups().add(group);+ }+ }+ }++ private MeshModel getMeshModel(final ProvisionedMeshNode node, final int src, final int modelId) {+ final Element element = node.getElements().get(src);+ if (element != null) {+ return element.getMeshModels().get(modelId);+ }+ return null;+ }++ private void storeScene(final ProvisionedMeshNode node, final SceneRegisterStatus status) {+ if (status.isSuccessful()) {+ final SceneServer sceneServer = (SceneServer) getMeshModel(node, status.getSrc(), SCENE_SERVER);+ if (sceneServer != null) {+ mInternalTransportCallbacks.storeScene(status.getSrc(), status.getCurrentScene(), status.getSceneList());+ if (!sceneServer.sceneNumbers.contains(status.getCurrentScene())) {+ sceneServer.sceneNumbers.add(status.getCurrentScene());+ }+ sceneServer.currentScene = status.getCurrentScene();+ }+ }+ }++ private void storeScene(final ProvisionedMeshNode node, final SceneStatus status) {+ if (status.isSuccessful()) {+ final SceneServer sceneServer = (SceneServer) getMeshModel(node, status.getSrc(), SCENE_SERVER);+ if (sceneServer != null) {+ sceneServer.currentScene = status.getCurrentScene();+ }+ }+ }++ private void deleteScene(final ProvisionedMeshNode node, final SceneRegisterStatus status) {+ if (status.isSuccessful()) {+ final SceneServer sceneServer = (SceneServer) getMeshModel(node, status.getSrc(), SCENE_SERVER);+ if (sceneServer != null) {+ final int deletedScene = ((SceneDelete) mMeshMessage).getSceneNumber();+ mInternalTransportCallbacks.deleteScene(status.getSrc(), deletedScene, status.getSceneList());+ if (sceneServer.sceneNumbers.contains(deletedScene))+ sceneServer.sceneNumbers.remove((Integer) deletedScene);+ }+ }+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/Element.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/Element.javanew file mode 100644index 000000000..235b23c47--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/Element.java@@ -0,0 +1,125 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.models.SigModel;+import org.openremote.agent.protocol.bluetooth.mesh.models.VendorModel;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;++import java.util.ArrayList;+import java.util.Collections;+import java.util.HashMap;+import java.util.LinkedHashMap;+import java.util.Map;+import java.util.Set;++public final class Element {++ int locationDescriptor;++ final Map<Integer, MeshModel> meshModels;++ int elementAddress;++ String name;++ /**+ * Constructs an element within a node+ *+ * @param elementAddress element address+ * @param locationDescriptor location descriptor+ * @param models models belonging to this element+ */+ public Element(final int elementAddress, final int locationDescriptor, final Map<Integer, MeshModel> models) {+ this(elementAddress, locationDescriptor, models, "Element: " + MeshAddress.formatAddress(elementAddress, true));+ }++ /**+ * Constructs an element within a node+ *+ * @param elementAddress element address+ * @param locationDescriptor location descriptor+ * @param models models belonging to this element+ */+ Element(final int elementAddress, final int locationDescriptor, final Map<Integer, MeshModel> models, final String name) {+ this.elementAddress = elementAddress;+ this.locationDescriptor = locationDescriptor;+ this.meshModels = models;+ this.name = name;+ }++ Element(final int locationDescriptor, final Map<Integer, MeshModel> models) {+ this.locationDescriptor = locationDescriptor;+ this.meshModels = models;+ }++ private void sortModels(final HashMap<Integer, MeshModel> unorderedElements) {+ final Set<Integer> unorderedKeys = unorderedElements.keySet();++ final ArrayList<Integer> orderedKeys = new ArrayList<>(unorderedKeys);+ Collections.sort(orderedKeys);+ for (int key : orderedKeys) {+ meshModels.put(key, unorderedElements.get(key));+ }+ }++ /**+ * Returns the address of the element+ */+ public int getElementAddress() {+ return elementAddress;+ }++ void setElementAddress(final int elementAddress) {+ this.elementAddress = elementAddress;+ }++ /**+ * Returns the location descriptor+ */+ public int getLocationDescriptor() {+ return locationDescriptor;+ }++ void setLocationDescriptor(final int locationDescriptor) {+ this.locationDescriptor = locationDescriptor;+ }++ /**+ * Returns the name of the element+ */+ public String getName() {+ return name;+ }++ public void setName(final String name) {+ this.name = name;+ }++ public int getSigModelCount() {+ int count = 0;+ for (Map.Entry<Integer, MeshModel> modelEntry : meshModels.entrySet()) {+ if (modelEntry.getValue() instanceof SigModel) {+ count++;+ }+ }+ return count;+ }++ public int getVendorModelCount() {+ int count = 0;+ for (Map.Entry<Integer, MeshModel> modelEntry : meshModels.entrySet()) {+ if (modelEntry.getValue() instanceof VendorModel) {+ count++;+ }+ }+ return count;+ }++ /**+ * Returns a list of sig models avaialable in this element+ *+ * @return List containing sig models+ */+ public Map<Integer, MeshModel> getMeshModels() {+ return Collections.unmodifiableMap(meshModels);+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericLevelGet.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericLevelGet.javanew file mode 100644index 000000000..5c0bf7b64--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericLevelGet.java@@ -0,0 +1,38 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.ApplicationKey;+import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ApplicationMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.SecureUtils;++import java.util.logging.Logger;++/**+ * To be used as a wrapper class to create generic level get message.+ */+public class GenericLevelGet extends GenericMessage {++ public static final Logger LOG = Logger.getLogger(GenericLevelGet.class.getName());+ private static final int OP_CODE = ApplicationMessageOpCodes.GENERIC_LEVEL_GET;+++ /**+ * Constructs GenericLevelGet message.+ *+ * @param appKey {@link ApplicationKey} key for this message+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public GenericLevelGet(final ApplicationKey appKey) throws IllegalArgumentException {+ super(appKey);+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ @Override+ void assembleMessageParameters() {+ mAid = SecureUtils.calculateK4(mAppKey.getKey());+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericLevelSet.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericLevelSet.javanew file mode 100644index 000000000..cc49400f8--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericLevelSet.java@@ -0,0 +1,97 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.ApplicationKey;+import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ApplicationMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.SecureUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++/**+ * To be used as a wrapper class when creating a GenericLevelSet message.+ */+@SuppressWarnings("unused")+public class GenericLevelSet extends GenericMessage {++ public static final Logger LOG = Logger.getLogger(GenericLevelSet.class.getName());+ private static final int OP_CODE = ApplicationMessageOpCodes.GENERIC_LEVEL_SET;+ private static final int GENERIC_LEVEL_SET_TRANSITION_PARAMS_LENGTH = 5;+ private static final int GENERIC_LEVEL_SET_PARAMS_LENGTH = 3;++ private final Integer mTransitionSteps;+ private final Integer mTransitionResolution;+ private final Integer mDelay;+ private final int mLevel;+ private final int tId;++ /**+ * Constructs GenericLevelSet message.+ *+ * @param appKey {@link ApplicationKey} key for this message+ * @param level Level value+ * @param tId Transaction id which must be incremented for every message+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public GenericLevelSet(final ApplicationKey appKey,+ final int level,+ final int tId) throws IllegalArgumentException {+ this(appKey, null, null, null, level, tId);+ }++ /**+ * Constructs GenericLevelSet message.+ *+ * @param appKey {@link ApplicationKey} key for this message+ * @param transitionSteps Transition steps for the level+ * @param transitionResolution Transition resolution for the level+ * @param delay Delay for this message to be executed 0 - 1275 milliseconds+ * @param level Level of the GenericLevelModel+ * @param tId Transaction id+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public GenericLevelSet(final ApplicationKey appKey,+ /* @Nullable */ final Integer transitionSteps,+ /* @Nullable */ final Integer transitionResolution,+ /* @Nullable */ final Integer delay,+ final int level,+ final int tId) throws IllegalArgumentException {+ super(appKey);+ this.mTransitionSteps = transitionSteps;+ this.mTransitionResolution = transitionResolution;+ this.mDelay = delay;+ this.tId = tId;+ if (level < Short.MIN_VALUE || level > Short.MAX_VALUE)+ throw new IllegalArgumentException("Generic level value must be between -32768 to 32767");+ this.mLevel = level;+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ @Override+ void assembleMessageParameters() {+ mAid = SecureUtils.calculateK4(mAppKey.getKey());+ final ByteBuffer paramsBuffer;+ LOG.info("Level: " + mLevel);+ if (mTransitionSteps == null || mTransitionResolution == null || mDelay == null) {+ paramsBuffer = ByteBuffer.allocate(GENERIC_LEVEL_SET_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.putShort((short) mLevel);+ paramsBuffer.put((byte) tId);+ } else {+ LOG.info("Transition steps: " + mTransitionSteps);+ LOG.info("Transition step resolution: " + mTransitionResolution);+ paramsBuffer = ByteBuffer.allocate(GENERIC_LEVEL_SET_TRANSITION_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.putShort((short) (mLevel));+ paramsBuffer.put((byte) tId);+ paramsBuffer.put((byte) (mTransitionResolution << 6 | mTransitionSteps));+ final int delay = mDelay;+ paramsBuffer.put((byte) delay);+ }+ mParameters = paramsBuffer.array();+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericLevelSetUnacknowledged.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericLevelSetUnacknowledged.javanew file mode 100644index 000000000..f1806407b--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericLevelSetUnacknowledged.java@@ -0,0 +1,96 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.ApplicationKey;+import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ApplicationMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.SecureUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++/**+ * To be used as a wrapper class when creating a GenericLevelSetUnacknowledged message.+ */+public class GenericLevelSetUnacknowledged extends GenericMessage {++ public static final Logger LOG = Logger.getLogger(GenericLevelSetUnacknowledged.class.getName());+ private static final int OP_CODE = ApplicationMessageOpCodes.GENERIC_LEVEL_SET_UNACKNOWLEDGED;+ private static final int GENERIC_LEVEL_SET_TRANSITION_PARAMS_LENGTH = 5;+ private static final int GENERIC_LEVEL_SET_PARAMS_LENGTH = 3;++ private final Integer mTransitionSteps;+ private final Integer mTransitionResolution;+ private final Integer mDelay;+ private final int mLevel;+ private final int tId;++ /**+ * Constructs GenericLevelSetUnacknowledged message.+ *+ * @param appKey {@link ApplicationKey} key for this message+ * @param level Level of the GenericLevelModel+ * @param tId Transaction id+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public GenericLevelSetUnacknowledged(final ApplicationKey appKey,+ final int level,+ final int tId) throws IllegalArgumentException {+ this(appKey, null, null, null, level, tId);+ }++ /**+ * Constructs GenericLevelSetUnacknowledged message.+ *+ * @param appKey {@link ApplicationKey} key for this message+ * @param transitionSteps Transition steps for the level+ * @param transitionResolution Transition resolution for the level+ * @param delay Delay for this message to be executed 0 - 1275 milliseconds+ * @param level Level of the GenericLevelModel+ * @param tId Transaction id+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public GenericLevelSetUnacknowledged(final ApplicationKey appKey,+ /* @Nullable */ final Integer transitionSteps,+ /* @Nullable */ final Integer transitionResolution,+ /* @Nullable */ final Integer delay,+ final int level,+ final int tId) throws IllegalArgumentException {+ super(appKey);+ this.mTransitionSteps = transitionSteps;+ this.mTransitionResolution = transitionResolution;+ this.mDelay = delay;+ this.tId = tId;+ if (level < Short.MIN_VALUE || level > Short.MAX_VALUE)+ throw new IllegalArgumentException("Generic level value must be between -32768 to 32767");+ this.mLevel = level;+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ @Override+ void assembleMessageParameters() {+ mAid = SecureUtils.calculateK4(mAppKey.getKey());+ final ByteBuffer paramsBuffer;+ LOG.info("Level: " + mLevel);+ if (mTransitionSteps == null || mTransitionResolution == null || mDelay == null) {+ paramsBuffer = ByteBuffer.allocate(GENERIC_LEVEL_SET_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.putShort((short) mLevel);+ paramsBuffer.put((byte) tId);+ } else {+ LOG.info("Transition steps: " + mTransitionSteps);+ LOG.info("Transition step resolution: " + mTransitionResolution);+ paramsBuffer = ByteBuffer.allocate(GENERIC_LEVEL_SET_TRANSITION_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.putShort((short) (mLevel));+ paramsBuffer.put((byte) tId);+ paramsBuffer.put((byte) (mTransitionResolution << 6 | mTransitionSteps));+ final int delay = mDelay;+ paramsBuffer.put((byte) delay);+ }+ mParameters = paramsBuffer.array();+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericLevelStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericLevelStatus.javanew file mode 100644index 000000000..4bd3ed00d--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericLevelStatus.java@@ -0,0 +1,94 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ApplicationMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++/**+ * To be used as a wrapper class to create generic level status message.+ */+public final class GenericLevelStatus extends GenericStatusMessage {++ public static final Logger LOG = Logger.getLogger(GenericLevelStatus.class.getName());+ private static final int GENERIC_LEVEL_STATUS_MANDATORY_LENGTH = 2;+ private static final int OP_CODE = ApplicationMessageOpCodes.GENERIC_LEVEL_STATUS;+ private int mPresentLevel;+ private Integer mTargetLevel;+ private int mTransitionSteps;+ private int mTransitionResolution;++ /**+ * Constructs GenericLevelStatus message+ * @param message access message+ */+ public GenericLevelStatus(final AccessMessage message) {+ super(message);+ this.mMessage = message;+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ void parseStatusParameters() {+ LOG.info("Received generic level status from: " + MeshAddress.formatAddress(mMessage.getSrc(), true));+ final ByteBuffer buffer = ByteBuffer.wrap(mParameters).order(ByteOrder.LITTLE_ENDIAN);+ mPresentLevel = (int) (buffer.getShort());+ LOG.info("Present level: " + mPresentLevel);+ if (buffer.limit() > GENERIC_LEVEL_STATUS_MANDATORY_LENGTH) {+ mTargetLevel = (int) (buffer.getShort());+ final int remainingTime = buffer.get() & 0xFF;+ mTransitionSteps = (remainingTime & 0x3F);+ mTransitionResolution = (remainingTime >> 6);+ LOG.info("Target level: " + mTargetLevel);+ LOG.info("Remaining time, transition number of steps: " + mTransitionSteps);+ LOG.info("Remaining time, transition number of step resolution: " + mTransitionResolution);+ LOG.info("Remaining time: " + MeshParserUtils.getRemainingTime(remainingTime));+ }+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ /**+ * Returns the present level of the GenericOnOffModel+ *+ * @return present level+ */+ public final int getPresentLevel() {+ return mPresentLevel;+ }++ /**+ * Returns the target level of the GenericOnOffModel+ *+ * @return target level+ */+ public final Integer getTargetLevel() {+ return mTargetLevel;+ }++ /**+ * Returns the transition steps.+ *+ * @return transition steps+ */+ public int getTransitionSteps() {+ return mTransitionSteps;+ }++ /**+ * Returns the transition resolution.+ *+ * @return transition resolution+ */+ public int getTransitionResolution() {+ return mTransitionResolution;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericMessage.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericMessage.javanew file mode 100644index 000000000..1d88e5936--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericMessage.java@@ -0,0 +1,55 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.ApplicationKey;++abstract class GenericMessage extends MeshMessage {++ public static final int GENERIC_TRANSITION_STEP_0 = 0;+ public static final int GENERIC_TRANSITION_STEP_1 = 1;+ public static final int GENERIC_TRANSITION_STEP_2 = 2;+ public static final int GENERIC_TRANSITION_STEP_3 = 3;++ final ApplicationKey mAppKey;+ byte mAid;++ /**+ * Constructs a generic message+ *+ * @param appKey application key+ */+ GenericMessage(final ApplicationKey appKey) {+ if (appKey.getKey().length != 16)+ throw new IllegalArgumentException("Application key must be 16 bytes");+ this.mAppKey = appKey;+ }++ @Override+ public final int getAkf() {+ return 1;+ }++ @Override+ public final int getAid() {+ return mAid;+ }++ /**+ * Returns the app key used in this message.+ *+ * @return app key+ */+ public final ApplicationKey getAppKey() {+ return mAppKey;+ }++ @Override+ public final byte[] getParameters() {+ return mParameters;+ }++ /**+ * Creates the parameters for a given mesh message.+ */+ abstract void assembleMessageParameters();+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericMessageState.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericMessageState.javanew file mode 100644index 000000000..51d1d994e--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericMessageState.java@@ -0,0 +1,84 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.ApplicationKey;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;++import java.util.UUID;++/**+ * Abstract state class that handles Generic Message States+ */+class GenericMessageState extends MeshMessageState {++ UUID mLabel;++ /**+ * Constructs the generic message state+ *+ * @param src Source address+ * @param dst Destination address+ * @param meshMessage {@link MeshMessage} to be sent+ * @param meshTransport {@link MeshTransport} transport+ * @param callbacks {@link InternalMeshMsgHandlerCallbacks} callbacks+ * @throws IllegalArgumentException if src or dst address is invalid+ */+ GenericMessageState(final int src,+ final int dst,+ final MeshMessage meshMessage,+ final MeshTransport meshTransport,+ final InternalMeshMsgHandlerCallbacks callbacks) throws IllegalArgumentException {+ this(src, dst, null, meshMessage, meshTransport, callbacks);+ }++ /**+ * Constructs the generic message state+ *+ * @param src Source address+ * @param dst Destination address+ * @param label Label UUID of destination address+ * @param meshMessage {@link MeshMessage} to be sent+ * @param meshTransport {@link MeshTransport} transport+ * @param callbacks {@link InternalMeshMsgHandlerCallbacks} callbacks+ * @throws IllegalArgumentException if src or dst address is invalid+ */+ GenericMessageState(final int src,+ final int dst,+ /* @Nullable */ final UUID label,+ final MeshMessage meshMessage,+ final MeshTransport meshTransport,+ final InternalMeshMsgHandlerCallbacks callbacks) throws IllegalArgumentException {+ super(meshMessage, meshTransport, callbacks);+ this.mSrc = src;+ if (!MeshAddress.isAddressInRange(src)) {+ throw new IllegalArgumentException("Invalid address, a source address must be a valid 16-bit value!");+ }+ this.mDst = dst;+ if (!MeshAddress.isAddressInRange(dst)) {+ throw new IllegalArgumentException("Invalid address, a destination address must be a valid 16-bit value");+ }+ mLabel = label;+ createAccessMessage();+ }++ /**+ * Creates the access message to be sent+ */+ protected synchronized void createAccessMessage() {+ final GenericMessage genericMessage = (GenericMessage) mMeshMessage;+ final ApplicationKey key = genericMessage.getAppKey();+ final int akf = genericMessage.getAkf();+ final int aid = genericMessage.getAid();+ final int aszmic = genericMessage.getAszmic();+ final int opCode = genericMessage.getOpCode();+ final byte[] parameters = genericMessage.getParameters();+ message = mMeshTransport.createMeshMessage(mSrc, mDst, mLabel, genericMessage.messageTtl,+ key, akf, aid, aszmic, opCode, parameters);+ genericMessage.setMessage(message);+ }++ @Override+ public synchronized MessageState getState() {+ return MessageState.GENERIC_MESSAGE_STATE;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericOnOffGet.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericOnOffGet.javanew file mode 100644index 000000000..fbed2495b--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericOnOffGet.java@@ -0,0 +1,37 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.ApplicationKey;+import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ApplicationMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.SecureUtils;++import java.util.logging.Logger;++/**+ * To be used as a wrapper class when creating a GenericOnOffGet message.+ */+public class GenericOnOffGet extends GenericMessage {++ public static final Logger LOG = Logger.getLogger(GenericOnOffGet.class.getName());+ private static final int OP_CODE = ApplicationMessageOpCodes.GENERIC_ON_OFF_GET;++ /**+ * Constructs GenericOnOffGet message.+ *+ * @param appKey application key for this message+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public GenericOnOffGet(final ApplicationKey appKey) throws IllegalArgumentException {+ super(appKey);+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ @Override+ void assembleMessageParameters() {+ mAid = SecureUtils.calculateK4(mAppKey.getKey());+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericOnOffSet.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericOnOffSet.javanew file mode 100644index 000000000..810140e86--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericOnOffSet.java@@ -0,0 +1,96 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.ApplicationKey;+import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ApplicationMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.SecureUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++/**+ * To be used as a wrapper class when creating a GenericOnOffSet message.+ */+@SuppressWarnings("unused")+public class GenericOnOffSet extends GenericMessage {++ public static final Logger LOG = Logger.getLogger(GenericOnOffSet.class.getName());+ private static final int OP_CODE = ApplicationMessageOpCodes.GENERIC_ON_OFF_SET;+ private static final int GENERIC_ON_OFF_SET_TRANSITION_PARAMS_LENGTH = 4;+ private static final int GENERIC_ON_OFF_SET_PARAMS_LENGTH = 2;++ private final Integer mTransitionSteps;+ private final Integer mTransitionResolution;+ private final Integer mDelay;+ private final boolean mState;+ private final int tId;++ /**+ * Constructs GenericOnOffSet message.+ *+ * @param appKey {@link ApplicationKey} key for this message+ * @param state Boolean state of the GenericOnOffModel+ * @param tId Transaction id+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public GenericOnOffSet(final ApplicationKey appKey,+ final boolean state,+ final int tId) throws IllegalArgumentException {+ this(appKey, state, tId, null, null, null);+ }++ /**+ * Constructs GenericOnOffSet message.+ *+ * @param appKey {@link ApplicationKey} key for this message+ * @param state Boolean state of the GenericOnOffModel+ * @param tId Transaction id+ * @param transitionSteps Transition steps for the level+ * @param transitionResolution Transition resolution for the level+ * @param delay Delay for this message to be executed 0 - 1275 milliseconds+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public GenericOnOffSet(final ApplicationKey appKey,+ final boolean state,+ final int tId,+ /* @Nullable */ final Integer transitionSteps,+ /* @Nullable */ final Integer transitionResolution,+ /* @Nullable */ final Integer delay) {+ super(appKey);+ this.mTransitionSteps = transitionSteps;+ this.mTransitionResolution = transitionResolution;+ this.mDelay = delay;+ this.mState = state;+ this.tId = tId;+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ @Override+ void assembleMessageParameters() {+ mAid = SecureUtils.calculateK4(mAppKey.getKey());+ final ByteBuffer paramsBuffer;+ LOG.info("State: " + (mState ? "ON" : "OFF"));+ if (mTransitionSteps == null || mTransitionResolution == null || mDelay == null) {+ paramsBuffer = ByteBuffer.allocate(GENERIC_ON_OFF_SET_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.put((byte) (mState ? 0x01 : 0x00));+ paramsBuffer.put((byte) tId);+ } else {+ LOG.info("Transition steps: " + mTransitionSteps);+ LOG.info("Transition step resolution: " + mTransitionResolution);+ paramsBuffer = ByteBuffer.allocate(GENERIC_ON_OFF_SET_TRANSITION_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.put((byte) (mState ? 0x01 : 0x00));+ paramsBuffer.put((byte) tId);+ paramsBuffer.put((byte) (mTransitionResolution << 6 | mTransitionSteps));+ final int delay = mDelay;+ paramsBuffer.put((byte) delay);+ }+ mParameters = paramsBuffer.array();++ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericOnOffSetUnacknowledged.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericOnOffSetUnacknowledged.javanew file mode 100644index 000000000..a49f72e18--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericOnOffSetUnacknowledged.java@@ -0,0 +1,96 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.ApplicationKey;+import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ApplicationMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.SecureUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++/**+ * To be used as a wrapper class when creating a GenericOnOffSetUnacknowledged message.+ */+@SuppressWarnings("unused")+public class GenericOnOffSetUnacknowledged extends GenericMessage {++ public static final Logger LOG = Logger.getLogger(GenericOnOffSetUnacknowledged.class.getName());+ private static final int OP_CODE = ApplicationMessageOpCodes.GENERIC_ON_OFF_SET_UNACKNOWLEDGED;+ private static final int GENERIC_ON_OFF_SET_TRANSITION_PARAMS_LENGTH = 4;+ private static final int GENERIC_ON_OFF_SET_PARAMS_LENGTH = 2;++ private final Integer mTransitionSteps;+ private final Integer mTransitionResolution;+ private final Integer mDelay;+ private final boolean mState;+ private final int tId;++ /**+ * Constructs GenericOnOffSet message.+ *+ * @param appKey {@link ApplicationKey} key for this message+ * @param state Boolean state of the GenericOnOffModel+ * @param tId transaction id+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public GenericOnOffSetUnacknowledged(final ApplicationKey appKey,+ final boolean state,+ final int tId) throws IllegalArgumentException {+ this(appKey, state, tId, null, null, null);+ }++ /**+ * Constructs GenericOnOffSet message.+ *+ * @param appKey {@link ApplicationKey} key for this message+ * @param state Boolean state of the GenericOnOffModel+ * @param tId transaction id+ * @param transitionSteps Transition steps for the level+ * @param transitionResolution Transition resolution for the level+ * @param delay Delay for this message to be executed 0 - 1275 milliseconds+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public GenericOnOffSetUnacknowledged(final ApplicationKey appKey,+ final boolean state,+ final int tId,+ /* @Nullable */ final Integer transitionSteps,+ /* @Nullable */ final Integer transitionResolution,+ /* @Nullable */ final Integer delay) {+ super(appKey);+ this.mTransitionSteps = transitionSteps;+ this.mTransitionResolution = transitionResolution;+ this.mDelay = delay;+ this.mState = state;+ this.tId = tId;+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ @Override+ void assembleMessageParameters() {+ mAid = SecureUtils.calculateK4(mAppKey.getKey());+ final ByteBuffer paramsBuffer;+ LOG.info("State: " + (mState ? "ON" : "OFF"));+ if (mTransitionSteps == null || mTransitionResolution == null || mDelay == null) {+ paramsBuffer = ByteBuffer.allocate(GENERIC_ON_OFF_SET_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.put((byte) (mState ? 0x01 : 0x00));+ paramsBuffer.put((byte) this.tId);+ } else {+ LOG.info("Transition steps: " + mTransitionSteps);+ LOG.info("Transition step resolution: " + mTransitionResolution);+ paramsBuffer = ByteBuffer.allocate(GENERIC_ON_OFF_SET_TRANSITION_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.put((byte) (mState ? 0x01 : 0x00));+ paramsBuffer.put((byte) this.tId);+ paramsBuffer.put((byte) (mTransitionResolution << 6 | mTransitionSteps));+ final int delay = mDelay;+ paramsBuffer.put((byte) delay);+ }+ mParameters = paramsBuffer.array();++ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericOnOffStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericOnOffStatus.javanew file mode 100644index 000000000..30d92fbc9--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericOnOffStatus.java@@ -0,0 +1,96 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ApplicationMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++/**+ * To be used as a wrapper class for when creating the GenericOnOffStatus Message.+ */+public final class GenericOnOffStatus extends GenericStatusMessage {++ public static final Logger LOG = Logger.getLogger(GenericOnOffStatus.class.getName());+ private static final int OP_CODE = ApplicationMessageOpCodes.GENERIC_ON_OFF_STATUS;+ private static final int GENERIC_ON_OFF_STATE_ON = 0x01;+ private boolean mPresentOn;+ private Boolean mTargetOn;+ private int mRemainingTime;+ private int mTransitionSteps;+ private int mTransitionResolution;++ /**+ * Constructs the GenericOnOffStatus mMessage.+ *+ * @param message Access Message+ */+ public GenericOnOffStatus(final AccessMessage message) {+ super(message);+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ void parseStatusParameters() {+ LOG.info("Received generic on off status from: " + MeshAddress.formatAddress(mMessage.getSrc(), true));+ final ByteBuffer buffer = ByteBuffer.wrap(mParameters).order(ByteOrder.LITTLE_ENDIAN);+ buffer.position(0);+ mPresentOn = buffer.get() == GENERIC_ON_OFF_STATE_ON;+ LOG.info("Present on: " + mPresentOn);+ if (buffer.limit() > 1) {+ mTargetOn = buffer.get() == GENERIC_ON_OFF_STATE_ON;+ mRemainingTime = buffer.get() & 0xFF;+ mTransitionSteps = (mRemainingTime & 0x3F);+ mTransitionResolution = (mRemainingTime >> 6);+ LOG.info("Target on: " + mTargetOn);+ LOG.info("Remaining time, transition number of steps: " + mTransitionSteps);+ LOG.info("Remaining time, transition number of step resolution: " + mTransitionResolution);+ LOG.info("Remaining time: " + MeshParserUtils.getRemainingTime(mRemainingTime));+ }+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ /**+ * Returns the present state of the GenericOnOffModel+ *+ * @return true if on and false other wise+ */+ public final boolean getPresentState() {+ return mPresentOn;+ }++ /**+ * Returns the target state of the GenericOnOffModel+ *+ * @return true if on and false other wise+ */+ public final Boolean getTargetState() {+ return mTargetOn;+ }++ /**+ * Returns the transition steps.+ *+ * @return transition steps+ */+ public int getTransitionSteps() {+ return mTransitionSteps;+ }++ /**+ * Returns the transition resolution.+ *+ * @return transition resolution+ */+ public int getTransitionResolution() {+ return mTransitionResolution;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericStatusMessage.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericStatusMessage.javanew file mode 100644index 000000000..162ca17a1--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/GenericStatusMessage.java@@ -0,0 +1,37 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++public abstract class GenericStatusMessage extends MeshMessage {+++ GenericStatusMessage(final AccessMessage message) {+ mMessage = message;+ }++ /**+ * Parses the status parameters returned by a status message+ */+ abstract void parseStatusParameters();++ @Override+ public final int getAkf() {+ return 1;+ }++ @Override+ public final int getAid() {+ return mMessage.getAid();+ }++ @Override+ public final byte[] getParameters() {+ return mParameters;+ }++ /**+ * Returns the address where the message was originated from+ */+ public int getSrcAddress() {+ return mMessage.getSrc();+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/InternalMeshMsgHandlerCallbacks.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/InternalMeshMsgHandlerCallbacks.javanew file mode 100644index 000000000..c2fe32ad3--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/InternalMeshMsgHandlerCallbacks.java@@ -0,0 +1,13 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++/**+ * Callbacks to notify the mesh message handler to notify events from transport layers.+ */+public interface InternalMeshMsgHandlerCallbacks {+ /**+ * Callback to notify the incomplete timer has expired+ *+ * @param address address of the message+ */+ void onIncompleteTimerExpired(final int address);+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/LightCtlStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/LightCtlStatus.javanew file mode 100644index 000000000..350ea7f11--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/LightCtlStatus.java@@ -0,0 +1,119 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ApplicationMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++/**+ * To be used as a wrapper class to create generic level status message.+ */+public final class LightCtlStatus extends GenericStatusMessage {++ public static final Logger LOG = Logger.getLogger(LightCtlStatus.class.getName());+ private static final int LIGHT_CTL_STATUS_MANDATORY_LENGTH = 4;+ private static final int OP_CODE = ApplicationMessageOpCodes.LIGHT_CTL_STATUS;+ private int mPresentCtlLightness;+ private int mPresentCtlTemperature;+ private Integer mTargetCtlLightness;+ private Integer mTargetCtlTemperature;+ private int mTransitionSteps;+ private int mTransitionResolution;++ /**+ * Constructs LightCtlStatus message+ *+ * @param message access message+ */+ public LightCtlStatus(final AccessMessage message) {+ super(message);+ this.mMessage = message;+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ void parseStatusParameters() {+ LOG.info("Received light ctl status from: " + MeshAddress.formatAddress(mMessage.getSrc(), true));+ final ByteBuffer buffer = ByteBuffer.wrap(mParameters).order(ByteOrder.LITTLE_ENDIAN);+ mPresentCtlLightness = buffer.getShort() & 0xFFFF;+ mPresentCtlTemperature = buffer.getShort() & 0xFFFF;+ LOG.info("Present lightness: " + mPresentCtlLightness);+ LOG.info("Present temperature: " + mPresentCtlTemperature);+ if (buffer.limit() > LIGHT_CTL_STATUS_MANDATORY_LENGTH) {+ mTargetCtlLightness = buffer.getShort() & 0xFFFF;+ mTargetCtlTemperature = buffer.getShort() & 0xFFFF;+ final int remainingTime = buffer.get() & 0xFF;+ mTransitionSteps = (remainingTime & 0x3F);+ mTransitionResolution = (remainingTime >> 6);+ LOG.info("Target lightness: " + mTargetCtlLightness);+ LOG.info("Target temperature: " + mTargetCtlTemperature);+ LOG.info("Remaining time, transition number of steps: " + mTransitionSteps);+ LOG.info("Remaining time, transition number of step resolution: " + mTransitionResolution);+ LOG.info("Remaining time: " + MeshParserUtils.getRemainingTime(remainingTime));+ }+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ /**+ * Returns the present level of the GenericOnOffModel+ *+ * @return present level+ */+ public final int getPresentLightness() {+ return mPresentCtlLightness;+ }++ /**+ * Returns the target level of the GenericOnOffModel+ *+ * @return target level+ */+ public final Integer getTargetLightness() {+ return mTargetCtlLightness;+ }++ /**+ * Returns the present level of the GenericOnOffModel+ *+ * @return present level+ */+ public final int getPresentTemperature() {+ return mPresentCtlTemperature;+ }++ /**+ * Returns the target level of the GenericOnOffModel+ *+ * @return target level+ */+ public final Integer getTargetTemperature() {+ return mTargetCtlTemperature;+ }++ /**+ * Returns the transition steps.+ *+ * @return transition steps+ */+ public int getTransitionSteps() {+ return mTransitionSteps;+ }++ /**+ * Returns the transition resolution.+ *+ * @return transition resolution+ */+ public int getTransitionResolution() {+ return mTransitionResolution;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/LightHslStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/LightHslStatus.javanew file mode 100644index 000000000..cfe7de86d--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/LightHslStatus.java@@ -0,0 +1,108 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ApplicationMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++/**+ * To be used as a wrapper class to create generic level status message.+ */+@SuppressWarnings({"WeakerAccess"})+public final class LightHslStatus extends GenericStatusMessage {++ public static final Logger LOG = Logger.getLogger(LightHslStatus.class.getName());+ private static final int LIGHT_CTL_STATUS_MANDATORY_LENGTH = 6;+ private static final int OP_CODE = ApplicationMessageOpCodes.LIGHT_HSL_STATUS;+ private int mPresentHslLightness;+ private int mPresentHslHue;+ private int mPresentHslSaturation;+ private int mTransitionSteps;+ private int mTransitionResolution;++ /**+ * Constructs LightHslStatus message+ * @param message access message+ */+ public LightHslStatus(final AccessMessage message) {+ super(message);+ this.mMessage = message;+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ void parseStatusParameters() {+ LOG.info("Received light hsl status from: " + MeshAddress.formatAddress(mMessage.getSrc(), true));+ final ByteBuffer buffer = ByteBuffer.wrap(mParameters).order(ByteOrder.LITTLE_ENDIAN);+ mPresentHslLightness = buffer.getShort() & 0xFFFF;+ mPresentHslHue = buffer.getShort() & 0xFFFF;+ mPresentHslSaturation = buffer.getShort() & 0xFFFF;+ LOG.info("Present lightness: " + mPresentHslLightness);+ LOG.info("Present hue: " + mPresentHslHue);+ LOG.info("Present saturation: " + mPresentHslSaturation);+ if (buffer.limit() > LIGHT_CTL_STATUS_MANDATORY_LENGTH) {+ final int remainingTime = buffer.get() & 0xFF;+ mTransitionSteps = (remainingTime & 0x3F);+ mTransitionResolution = (remainingTime >> 6);+ LOG.info("Remaining time, transition number of steps: " + mTransitionSteps);+ LOG.info("Remaining time, transition number of step resolution: " + mTransitionResolution);+ LOG.info("Remaining time: " + MeshParserUtils.getRemainingTime(remainingTime));+ }+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ /**+ * Returns the present level of the GenericOnOffModel+ *+ * @return present level+ */+ public final int getPresentLightness() {+ return mPresentHslLightness;+ }++ /**+ * Returns the present level of the GenericOnOffModel+ *+ * @return present level+ */+ public final int getPresentSaturation() {+ return mPresentHslSaturation;+ }++ /**+ * Returns the present level of the GenericOnOffModel+ *+ * @return present level+ */+ public final int getPresentHue() {+ return mPresentHslHue;+ }+++ /**+ * Returns the transition steps.+ *+ * @return transition steps+ */+ public int getTransitionSteps() {+ return mTransitionSteps;+ }++ /**+ * Returns the transition resolution.+ *+ * @return transition resolution+ */+ public int getTransitionResolution() {+ return mTransitionResolution;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/LightLightnessStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/LightLightnessStatus.javanew file mode 100644index 000000000..616031321--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/LightLightnessStatus.java@@ -0,0 +1,95 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ApplicationMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++/**+ * To be used as a wrapper class to create generic level status message.+ */+public final class LightLightnessStatus extends GenericStatusMessage {++ public static final Logger LOG = Logger.getLogger(LightLightnessStatus.class.getName());+ private static final int LIGHT_LIGHTNESS_STATUS_MANDATORY_LENGTH = 2;+ private static final int OP_CODE = ApplicationMessageOpCodes.LIGHT_LIGHTNESS_STATUS;+ private int mPresentLightness;+ private Integer mTargetLightness;+ private int mTransitionSteps;+ private int mTransitionResolution;++ /**+ * Constructs LightLightnessStatus message+ *+ * @param message access message+ */+ public LightLightnessStatus(final AccessMessage message) {+ super(message);+ this.mMessage = message;+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ void parseStatusParameters() {+ LOG.info("Received light lightness status from: " + MeshAddress.formatAddress(mMessage.getSrc(), true));+ final ByteBuffer buffer = ByteBuffer.wrap(mParameters).order(ByteOrder.LITTLE_ENDIAN);+ mPresentLightness = buffer.getShort() & 0xFFFF;+ LOG.info("Present level: " + mPresentLightness);+ if (buffer.limit() > LIGHT_LIGHTNESS_STATUS_MANDATORY_LENGTH) {+ mTargetLightness = buffer.getShort() & 0xFFFF;+ final int remainingTime = buffer.get() & 0xFF;+ mTransitionSteps = (remainingTime & 0x3F);+ mTransitionResolution = (remainingTime >> 6);+ LOG.info("Target level: " + mTargetLightness);+ LOG.info("Remaining time, transition number of steps: " + mTransitionSteps);+ LOG.info("Remaining time, transition number of step resolution: " + mTransitionResolution);+ LOG.info("Remaining time: " + MeshParserUtils.getRemainingTime(remainingTime));+ }+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ /**+ * Returns the present level of the GenericOnOffModel+ *+ * @return present level+ */+ public final int getPresentLightness() {+ return mPresentLightness;+ }++ /**+ * Returns the target level of the GenericOnOffModel+ *+ * @return target level+ */+ public final Integer getTargetLightness() {+ return mTargetLightness;+ }++ /**+ * Returns the transition steps.+ *+ * @return transition steps+ */+ public int getTransitionSteps() {+ return mTransitionSteps;+ }++ /**+ * Returns the transition resolution.+ *+ * @return transition resolution+ */+ public int getTransitionResolution() {+ return mTransitionResolution;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/LowerTransportLayer.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/LowerTransportLayer.javanew file mode 100644index 000000000..56dc5b9c3--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/LowerTransportLayer.java@@ -0,0 +1,857 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.MeshManagerApi;+import org.openremote.agent.protocol.bluetooth.mesh.control.BlockAcknowledgementMessage;+import org.openremote.agent.protocol.bluetooth.mesh.opcodes.TransportLayerOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.ExtendedInvalidCipherTextException;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.HashMap;+import java.util.Map;+import java.util.Set;+import java.util.TreeMap;+import java.util.concurrent.Future;+import java.util.logging.Logger;++/**+ * LowerTransportLayer implementation of the mesh network architecture as per the mesh profile specification.+ * <p>+ * This class generates the messages as per the lower transport layer requirements, segmentation and reassembly of mesh messages sent and received,+ * retransmitting messages.+ * </p>+ */+abstract class LowerTransportLayer extends UpperTransportLayer {++ public static final Logger LOG = Logger.getLogger(LowerTransportLayer.class.getName());++ private static final int BLOCK_ACK_TIMER = 150; //Increased from minimum value 150;+ private static final int UNSEGMENTED_HEADER = 0;+ private static final int SEGMENTED_HEADER = 1;+ private static final int UNSEGMENTED_MESSAGE_HEADER_LENGTH = 1;+ private static final int SEGMENTED_MESSAGE_HEADER_LENGTH = 4;+ private static final int UNSEGMENTED_ACK_MESSAGE_HEADER_LENGTH = 3;+ private static final long INCOMPLETE_TIMER_DELAY = 10 * 1000; // According to the spec the incomplete timer must be a minimum of 10 seconds.++ private final Map<Integer, byte[]> segmentedAccessMessageMap = new HashMap<>();+ private final Map<Integer, byte[]> segmentedControlMessageMap = new HashMap<>();+ LowerTransportLayerCallbacks mLowerTransportLayerCallbacks;+ private boolean mSegmentedAccessAcknowledgementTimerStarted;+ private Integer mSegmentedAccessBlockAck;+ private boolean mSegmentedControlAcknowledgementTimerStarted;+ private Integer mSegmentedControlBlockAck;+ private boolean mIncompleteTimerStarted;+ private boolean mBlockAckSent;+ private long mDuration;++ protected abstract Future<?> startTask(Runnable runnable, Long delay);+ protected abstract void stopTask(Future<?> task);+ protected abstract void stopAllTasks();++ private Future<?> incompleteTimerTask = null;++ /**+ * Runnable for incomplete timer+ */+ private final Runnable mIncompleteTimerRunnable = new Runnable() {+ @Override+ public void run() {+ synchronized (LowerTransportLayer.this) {+ mLowerTransportLayerCallbacks.onIncompleteTimerExpired();+ //Reset the incomplete timer flag once it expires+ mIncompleteTimerStarted = false;+ }+ }+ };++ /**+ * Sets the lower transport layer callbacks+ *+ * @param callbacks {@link LowerTransportLayerCallbacks} callbacks+ */+ abstract void setLowerTransportLayerCallbacks(final LowerTransportLayerCallbacks callbacks);++ /**+ * Creates the network layer pdu+ *+ * @param message message with underlying data+ * @return Complete pdu message that is ready to be sent+ */+ protected abstract Message createNetworkLayerPDU(final Message message);++ @Override+ synchronized void createMeshMessage(final Message message) {+ super.createMeshMessage(message);+ if (message instanceof AccessMessage) {+ createLowerTransportAccessPDU((AccessMessage) message);+ } else {+ createLowerTransportControlPDU((ControlMessage) message);+ }+ }++ @Override+ synchronized void createVendorMeshMessage(final Message message) {+ if (message instanceof AccessMessage) {+ super.createVendorMeshMessage(message);+ createLowerTransportAccessPDU((AccessMessage) message);+ } else {+ createLowerTransportControlPDU((ControlMessage) message);+ }+ }++ @Override+ public synchronized final void createLowerTransportAccessPDU(final AccessMessage message) {+ final byte[] upperTransportPDU = message.getUpperTransportPdu();+ final Map<Integer, byte[]> lowerTransportAccessPduMap;+ if (upperTransportPDU.length <= MAX_SEGMENTED_ACCESS_PAYLOAD_LENGTH) {+ message.setSegmented(false);+ final byte[] lowerTransportPDU = createUnsegmentedAccessMessage(message);+ lowerTransportAccessPduMap = new HashMap<>();+ lowerTransportAccessPduMap.put(0, lowerTransportPDU);+ } else {+ message.setSegmented(true);+ lowerTransportAccessPduMap = createSegmentedAccessMessage(message);+ }++ message.setLowerTransportAccessPdu(lowerTransportAccessPduMap);+ }++ @Override+ public synchronized final void createLowerTransportControlPDU(final ControlMessage message) {+ switch (message.getPduType()) {+ case MeshManagerApi.PDU_TYPE_PROXY_CONFIGURATION:+ final Map<Integer, byte[]> lowerTransportControlPduArray = new HashMap<>();+ lowerTransportControlPduArray.put(0, message.getTransportControlPdu());+ message.setLowerTransportControlPdu(lowerTransportControlPduArray);+ break;+ case MeshManagerApi.PDU_TYPE_NETWORK:+ final byte[] transportControlPdu = message.getTransportControlPdu();+ if (transportControlPdu.length <= MAX_UNSEGMENTED_CONTROL_PAYLOAD_LENGTH) {+ LOG.info("Creating unsegmented transport control");+ createUnsegmentedControlMessage(message);+ } else {+ LOG.info("Creating segmented transport control");+ createSegmentedControlMessage(message);+ }+ }+ }++ @Override+ final synchronized void reassembleLowerTransportAccessPDU(final AccessMessage accessMessage) {+ final Map<Integer, byte[]> lowerTransportAccessPdu = removeLowerTransportAccessMessageHeader(accessMessage);+ final byte[] upperTransportPdu = MeshParserUtils.concatenateSegmentedMessages(lowerTransportAccessPdu);+ accessMessage.setUpperTransportPdu(upperTransportPdu);+ }++ @Override+ final synchronized void reassembleLowerTransportControlPDU(final ControlMessage controlMessage) {+ final Map<Integer, byte[]> lowerTransportPdu = removeLowerTransportControlMessageHeader(controlMessage);+ final byte[] lowerTransportControlPdu = MeshParserUtils.concatenateSegmentedMessages(lowerTransportPdu);+ controlMessage.setTransportControlPdu(lowerTransportControlPdu);+ }++ /**+ * Removes the transport header of the access message.+ *+ * @param message access message received.+ * @return map containing the messages.+ */+ private Map<Integer, byte[]> removeLowerTransportAccessMessageHeader(final AccessMessage message) {+ final Map<Integer, byte[]> messages = message.getLowerTransportAccessPdu();+ if (message.isSegmented()) {+ /*+ for (int i = 0; i < messages.size(); i++) {+ final byte[] data = messages.get(i);+ final int length = data.length - SEGMENTED_MESSAGE_HEADER_LENGTH; //header size of unsegmented messages is 4;+ messages.put(i, removeHeader(data, 4, length));+ }+ */+ for (Integer index : messages.keySet()) {+ final byte[] data = messages.get(index);+ final int length = data.length - SEGMENTED_MESSAGE_HEADER_LENGTH; //header size of unsegmented messages is 4;+ messages.put(index, removeHeader(data, 4, length));+ }+ } else {+ /*+ final byte[] data = messages.get(0);+ final int length = data.length - UNSEGMENTED_MESSAGE_HEADER_LENGTH; //header size of unsegmented messages is 1;+ messages.put(0, removeHeader(data, 1, length));+ */+ Integer index = (Integer)messages.keySet().toArray()[0];+ final byte[] data = messages.get(index);+ final int length = data.length - UNSEGMENTED_MESSAGE_HEADER_LENGTH; //header size of unsegmented messages is 1;+ messages.put(index, removeHeader(data, 1, length));+ }+ return messages;+ }++ /**+ * Removes the transport header of the control message.+ *+ * @param message control message.+ * @return map containing the messages.+ */+ private Map<Integer, byte[]> removeLowerTransportControlMessageHeader(final ControlMessage message) {+ final Map<Integer, byte[]> messages = message.getLowerTransportControlPdu();+ if (messages.size() > 1) {+ /*+ for (int i = 0; i < messages.size(); i++) {+ final byte[] data = messages.get(i);+ final int length = data.length - SEGMENTED_MESSAGE_HEADER_LENGTH; //header size of unsegmented messages is 4;+ messages.put(i, removeHeader(data, 4, length));+ }+ */+ for (Integer index : messages.keySet()) {+ final byte[] data = messages.get(index);+ final int length = data.length - SEGMENTED_MESSAGE_HEADER_LENGTH; //header size of unsegmented messages is 4;+ messages.put(index, removeHeader(data, 4, length));+ }+ } else {+ final int opCode = message.getOpCode();+ final byte[] data;+ final int length;+ if (opCode == TransportLayerOpCodes.SAR_ACK_OPCODE) {+ // data = messages.get(0);+ Integer index = (Integer)messages.keySet().toArray()[0];+ data = messages.get(index);+ length = data.length - UNSEGMENTED_ACK_MESSAGE_HEADER_LENGTH; //header size of unsegmented acknowledgement messages is 3;+ // messages.put(0, removeHeader(data, UNSEGMENTED_ACK_MESSAGE_HEADER_LENGTH, length));+ messages.put(index, removeHeader(data, UNSEGMENTED_ACK_MESSAGE_HEADER_LENGTH, length));+ } else {+ // data = messages.get(0);+ Integer index = (Integer)messages.keySet().toArray()[0];+ data = messages.get(index);+ length = data.length - UNSEGMENTED_MESSAGE_HEADER_LENGTH; //header size of unsegmented messages is 1;+ // messages.put(0, removeHeader(data, UNSEGMENTED_MESSAGE_HEADER_LENGTH, length));+ messages.put(index, removeHeader(data, UNSEGMENTED_MESSAGE_HEADER_LENGTH, length));+ }+ }+ return messages;+ }++ /**+ * Removes the header from a given array.+ *+ * @param data message.+ * @param offset header offset.+ * @param length header length.+ * @return an array without the header.+ */+ private byte[] removeHeader(final byte[] data, final int offset, final int length) {+ final ByteBuffer buffer = ByteBuffer.allocate(length).order(ByteOrder.BIG_ENDIAN);+ buffer.put(data, offset, length);+ return buffer.array();+ }++ /**+ * Creates an unsegmented access message.+ *+ * @param message access message.+ * @return Unsegmented access message.+ */+ private byte[] createUnsegmentedAccessMessage(final AccessMessage message) {+ final byte[] encryptedUpperTransportPDU = message.getUpperTransportPdu();+ final int seg = message.isSegmented() ? 1 : 0;+ final int akfAid = ((message.getAkf() << 6) | message.getAid());+ final byte header = (byte) (((seg << 7) | akfAid));+ final ByteBuffer lowerTransportBuffer = ByteBuffer.allocate(1 + encryptedUpperTransportPDU.length).order(ByteOrder.BIG_ENDIAN);+ lowerTransportBuffer.put(header);+ lowerTransportBuffer.put(encryptedUpperTransportPDU);+ final byte[] lowerTransportPDU = lowerTransportBuffer.array();+ LOG.info("Unsegmented Lower transport access PDU " + MeshParserUtils.bytesToHex(lowerTransportPDU, false));+ return lowerTransportPDU;+ }++ /**+ * Creates a segmented access message.+ *+ * @param message access message.+ * @return Segmented access message.+ */+ private Map<Integer, byte[]> createSegmentedAccessMessage(final AccessMessage message) {+ final byte[] encryptedUpperTransportPDU = message.getUpperTransportPdu();+ final int akfAid = ((message.getAkf() << 6) | message.getAid());+ final int aszmic = message.getAszmic();+ final byte[] sequenceNumber = message.getSequenceNumber();+ int seqZero = MeshParserUtils.calculateSeqZero(sequenceNumber);++ final int numberOfSegments = (encryptedUpperTransportPDU.length + (MAX_SEGMENTED_ACCESS_PAYLOAD_LENGTH - 1)) / MAX_SEGMENTED_ACCESS_PAYLOAD_LENGTH;+ final int segN = numberOfSegments - 1; //Zero based segN+ final Map<Integer, byte[]> lowerTransportPduMap = new HashMap<>();+ int offset = 0;+ int length;+ for (int segO = 0; segO < numberOfSegments; segO++) {+ //Here we calculate the size of the segments based on the offset and the maximum payload of a segment access message+ length = Math.min(encryptedUpperTransportPDU.length - offset, MAX_SEGMENTED_ACCESS_PAYLOAD_LENGTH);+ final ByteBuffer lowerTransportBuffer = ByteBuffer.allocate(SEGMENTED_MESSAGE_HEADER_LENGTH + length).order(ByteOrder.BIG_ENDIAN);+ lowerTransportBuffer.put((byte) ((SEGMENTED_HEADER << 7) | akfAid));+ lowerTransportBuffer.put((byte) ((aszmic << 7) | ((seqZero >> 6) & 0x7F)));+ lowerTransportBuffer.put((byte) (((seqZero << 2) & 0xFC) | ((segO >> 3) & 0x03)));+ lowerTransportBuffer.put((byte) (((segO << 5) & 0xE0) | ((segN) & 0x1F)));+ lowerTransportBuffer.put(encryptedUpperTransportPDU, offset, length);+ offset += length;++ final byte[] lowerTransportPDU = lowerTransportBuffer.array();+ LOG.info("Segmented Lower transport access PDU: " + MeshParserUtils.bytesToHex(lowerTransportPDU, false) + " " + segO + " of " + numberOfSegments);+ lowerTransportPduMap.put(segO, lowerTransportPDU);+ }+ return lowerTransportPduMap;+ }++ /**+ * Creates an unsegmented control.+ *+ * @param message control message.+ */+ private void createUnsegmentedControlMessage(final ControlMessage message) {+ int pduLength;+ final ByteBuffer lowerTransportBuffer;+ message.setSegmented(false);+ final int opCode = message.getOpCode();+ final byte[] parameters = message.getParameters();+ final byte[] upperTransportControlPDU = message.getTransportControlPdu();+ final int header = (byte) ((UNSEGMENTED_HEADER << 7) | opCode);+ if (parameters != null) {+ pduLength = UNSEGMENTED_MESSAGE_HEADER_LENGTH + parameters.length + upperTransportControlPDU.length;+ lowerTransportBuffer = ByteBuffer.allocate(pduLength).order(ByteOrder.BIG_ENDIAN);+ lowerTransportBuffer.put((byte) header);+ lowerTransportBuffer.put(parameters);+ } else {+ pduLength = UNSEGMENTED_MESSAGE_HEADER_LENGTH + upperTransportControlPDU.length;+ lowerTransportBuffer = ByteBuffer.allocate(pduLength).order(ByteOrder.BIG_ENDIAN);+ lowerTransportBuffer.put((byte) header);+ }++ lowerTransportBuffer.put(upperTransportControlPDU);+ final byte[] lowerTransportPDU = lowerTransportBuffer.array();+ LOG.info("Unsegmented Lower transport control PDU " + MeshParserUtils.bytesToHex(lowerTransportPDU, false));+ final Map<Integer, byte[]> lowerTransportControlPduMap = new HashMap<>();+ lowerTransportControlPduMap.put(0, lowerTransportPDU);+ message.setLowerTransportControlPdu(lowerTransportControlPduMap);+ }++ /**+ * Creates a segmented control message.+ *+ * @param controlMessage control message to be sent.+ */+ private void createSegmentedControlMessage(final ControlMessage controlMessage) {+ controlMessage.setSegmented(false);+ final byte[] encryptedUpperTransportControlPDU = controlMessage.getTransportControlPdu();+ final int opCode = controlMessage.getOpCode();+ final int rfu = 0;+ final byte[] sequenceNumber = controlMessage.getSequenceNumber();+ final int seqZero = MeshParserUtils.calculateSeqZero(sequenceNumber);++ final int numberOfSegments = (encryptedUpperTransportControlPDU.length + (MAX_SEGMENTED_CONTROL_PAYLOAD_LENGTH - 1)) / MAX_SEGMENTED_CONTROL_PAYLOAD_LENGTH;+ final int segN = numberOfSegments - 1; //Zero based segN+ final Map<Integer, byte[]> lowerTransportControlPduMap = new HashMap<>();+ int offset = 0;+ int length;+ for (int segO = 0; segO < numberOfSegments; segO++) {+ //Here we calculate the size of the segments based on the offset and the maximum payload of a segment access message+ length = Math.min(encryptedUpperTransportControlPDU.length - offset, MAX_SEGMENTED_CONTROL_PAYLOAD_LENGTH);+ final ByteBuffer lowerTransportBuffer = ByteBuffer.allocate(SEGMENTED_MESSAGE_HEADER_LENGTH + length).order(ByteOrder.BIG_ENDIAN);+ lowerTransportBuffer.put((byte) ((SEGMENTED_HEADER << 7) | opCode));+ lowerTransportBuffer.put((byte) ((rfu << 7) | ((seqZero >> 6) & 0x7F)));+ lowerTransportBuffer.put((byte) (((seqZero << 2) & 0xFC) | ((segO >> 3) & 0x03)));+ lowerTransportBuffer.put((byte) (((segO << 5) & 0xE0) | (segN & 0x1F)));+ lowerTransportBuffer.put(encryptedUpperTransportControlPDU, offset, length);+ offset += length;++ final byte[] lowerTransportPDU = lowerTransportBuffer.array();+ LOG.info("Segmented Lower transport access PDU: " + MeshParserUtils.bytesToHex(lowerTransportPDU, false) + " " + segO + " of " + numberOfSegments);+ lowerTransportControlPduMap.put(segO, lowerTransportPDU);+ }+ controlMessage.setLowerTransportControlPdu(lowerTransportControlPduMap);+ }++ /**+ * Checks if the received message is a segmented message+ *+ * @param lowerTransportHeader header for the lower transport pdu+ * @return true if segmented and false if not+ */+ /*package*/+ final boolean isSegmentedMessage(final byte lowerTransportHeader) {+ return ((lowerTransportHeader >> 7) & 0x01) == 1;+ }++ /**+ * Parses a unsegmented lower transport access pdu+ *+ * @param pdu The complete pdu was received from the node. This is already de-obfuscated+ * and decrypted at network layer.+ * @param ivIndex IV Index of the received pdu+ * @param sequenceNumber Sequence number of the message.+ */+ /*package*/+ synchronized final AccessMessage parseUnsegmentedAccessLowerTransportPDU(final byte[] pdu,+ final int ivIndex,+ final byte[] sequenceNumber) {+ AccessMessage message = null;+ final byte header = pdu[10]; //Lower transport pdu starts here+ final int seg = (header >> 7) & 0x01;+ final int akf = (header >> 6) & 0x01;+ final int aid = header & 0x3F;+ if (seg == 0) { //Unsegmented message+ LOG.info("IV Index of received message: " + ivIndex);+ final int seqAuth = (ivIndex << 24) | MeshParserUtils.convert24BitsToInt(sequenceNumber);+ final byte[] src = MeshParserUtils.getSrcAddress(pdu);+ final int srcAdd = MeshParserUtils.unsignedBytesToInt(src[1], src[0]);+ LOG.info("SeqAuth: " + seqAuth);+ if (!isValidSeqAuth(seqAuth, srcAdd)) {+ return null;+ }+ mMeshNode.setSeqAuth(srcAdd, seqAuth);+ mMeshNode.setSequenceNumber(MeshParserUtils.convert24BitsToInt(sequenceNumber));+ message = new AccessMessage();+ if (akf == 0) {// device key was used to encrypt+ final int lowerTransportPduLength = pdu.length - 10;+ final ByteBuffer lowerTransportBuffer = ByteBuffer.allocate(lowerTransportPduLength).order(ByteOrder.BIG_ENDIAN);+ lowerTransportBuffer.put(pdu, 10, lowerTransportPduLength);+ final byte[] lowerTransportPDU = lowerTransportBuffer.array();+ final Map<Integer, byte[]> messages = new HashMap<>();+ messages.put(0, lowerTransportPDU);+ message.setSegmented(false);+ message.setAszmic(0); //aszmic is always 0 for unsegmented access messages+ message.setAkf(akf);+ message.setAid(aid);+ message.setLowerTransportAccessPdu(messages);+ } else {+ final int lowerTransportPduLength = pdu.length - 10;+ final ByteBuffer lowerTransportBuffer = ByteBuffer.allocate(lowerTransportPduLength).order(ByteOrder.BIG_ENDIAN);+ lowerTransportBuffer.put(pdu, 10, lowerTransportPduLength);+ final byte[] lowerTransportPDU = lowerTransportBuffer.array();+ final Map<Integer, byte[]> messages = new HashMap<>();+ messages.put(0, lowerTransportPDU);+ message.setSegmented(false);+ message.setAszmic(0); //aszmic is always 0 for unsegmented access messages+ message.setAkf(akf);+ message.setAid(aid);+ message.setLowerTransportAccessPdu(messages);+ }+ }+ return message;+ }++ /**+ * Parses a segmented lower transport access pdu.+ *+ * @param ttl TTL of the acknowledgement+ * @param pdu The complete pdu was received from the node. This is already de-obfuscated and decrypted at network layer.+ * @param ivIndex Current IV Index of the network+ * @param sequenceNumber Sequence number+ */+ /*package*/+ synchronized final AccessMessage parseSegmentedAccessLowerTransportPDU(final int ttl,+ final byte[] pdu,+ final int ivIndex,+ final byte[] sequenceNumber) {+ final byte header = pdu[10]; //Lower transport pdu starts here+ final int akf = (header >> 6) & 0x01;+ final int aid = header & 0x3F;++ final int szmic = (pdu[11] >> 7) & 0x01;+ final int seqZero = ((pdu[11] & 0x7F) << 6) | ((pdu[12] & 0xFC) >> 2);+ final int segO = ((pdu[12] & 0x03) << 3) | ((pdu[13] & 0xE0) >> 5);+ final int segN = ((pdu[13]) & 0x1F);++ final byte[] src = MeshParserUtils.getSrcAddress(pdu);+ final byte[] dst = MeshParserUtils.getDstAddress(pdu);++ final int blockAckSrc = MeshParserUtils.unsignedBytesToInt(dst[1], dst[0]); //Destination of the received packet would be the source for the ack+ final int blockAckDst = MeshParserUtils.unsignedBytesToInt(src[1], src[0]); //Source of the received packet would be the destination for the ack++ LOG.info("SEG O: " + segO);+ LOG.info("SEG N: " + segN);++ final int seqNumber = getTransportLayerSequenceNumber(MeshParserUtils.convert24BitsToInt(sequenceNumber), seqZero);+ final int seqAuth = ivIndex << 24 | seqNumber;+ final Integer lastSeqAuth = mMeshNode.getSeqAuth(blockAckDst);+ if (lastSeqAuth != null)+ LOG.info("Last SeqAuth value " + lastSeqAuth);++ LOG.info("Current SeqAuth value " + seqAuth);++ final int payloadLength = pdu.length - 10;+ final ByteBuffer payloadBuffer = ByteBuffer.allocate(payloadLength);+ payloadBuffer.put(pdu, 10, payloadLength);++ //Check if the current SeqAuth value is greater than the last and if the incomplete timer has not started, start it!+ if ((lastSeqAuth == null || lastSeqAuth < seqAuth)) {+ mMeshNode.setSequenceNumber(seqNumber);+ segmentedAccessMessageMap.clear();+ segmentedAccessMessageMap.put(segO, payloadBuffer.array());+ mMeshNode.setSeqAuth(blockAckDst, seqAuth);++ LOG.info("Starting incomplete timer for src: " + MeshAddress.formatAddress(blockAckDst, false));+ initIncompleteTimer();++ //Start acknowledgement calculation and timer only for messages directed to a unicast address.+ if (MeshAddress.isValidUnicastAddress(dst)) {+ // Calculate the initial block acknowledgement value+ mSegmentedAccessBlockAck = BlockAcknowledgementMessage.calculateBlockAcknowledgement(null, segO);+ //Start the block acknowledgement timer irrespective of which segment was received first+ initSegmentedAccessAcknowledgementTimer(seqZero, ttl, blockAckSrc, blockAckDst, segN);+ }+ } else {+ //if the seqauth values are the same and the init complete timer has already started for a received segmented message, we need to restart the incomplete timer+ if (lastSeqAuth == seqAuth) {+ if (mIncompleteTimerStarted) {+ if (segmentedAccessMessageMap.get(segO) == null) {+ segmentedAccessMessageMap.put(segO, payloadBuffer.array());+ }+ final int receivedSegmentedMessageCount = segmentedAccessMessageMap.size();+ LOG.info("Received segment message count: " + receivedSegmentedMessageCount);+ //Add +1 to segN since its zero based+ if (receivedSegmentedMessageCount != (segN + 1)) {+ restartIncompleteTimer();+ LOG.info("Restarting incomplete timer for src: " + MeshAddress.formatAddress(blockAckDst, false));++ //Start acknowledgement calculation and timer only for messages directed to a unicast address.+ //We also have to make sure we restart the acknowledgement timer only if the acknowledgement timer is not active and the incomplete timer is active+ if (MeshAddress.isValidUnicastAddress(dst) && !mSegmentedAccessAcknowledgementTimerStarted) {+ mSegmentedAccessBlockAck = BlockAcknowledgementMessage.calculateBlockAcknowledgement(mSegmentedAccessBlockAck, segO);+ LOG.info("Restarting block acknowledgement timer for src: " + MeshAddress.formatAddress(blockAckDst, false));+ //Start the block acknowledgement timer irrespective of which segment was received first+ initSegmentedAccessAcknowledgementTimer(seqZero, ttl, blockAckSrc, blockAckDst, segN);+ }+ } else {+ if (MeshAddress.isValidUnicastAddress(dst)) {+ mSegmentedAccessBlockAck = BlockAcknowledgementMessage.calculateBlockAcknowledgement(mSegmentedAccessBlockAck, segO);+ handleImmediateBlockAcks(seqZero, ttl, blockAckSrc, blockAckDst, segN);+ } else {+ //We should cancel the incomplete timer since we have received all segments+ cancelIncompleteTimer();+ }++ final AccessMessage accessMessage = new AccessMessage();+ accessMessage.setAszmic(szmic);+ accessMessage.setSequenceNumber(MeshParserUtils.getSequenceNumberBytes(seqNumber));+ accessMessage.setAkf(akf);+ accessMessage.setAid(aid);+ accessMessage.setSegmented(true);+ // final SparseArray<byte[]> segmentedMessages = segmentedAccessMessageMap.clone();+ final Map<Integer, byte[]> segmentedMessages = new HashMap<>();+ for (Integer index : segmentedAccessMessageMap.keySet()) {+ segmentedMessages.put(index, segmentedAccessMessageMap.get(index).clone());+ }+ accessMessage.setLowerTransportAccessPdu(segmentedMessages);+ return accessMessage;+ }+ } else {+ LOG.info("Ignoring message since the incomplete timer has expired and all messages have been received");+ }+ }+ }+ return null;+ }++ /**+ * Send immediate block acknowledgement+ *+ * @param seqZero seqzero of the message+ * @param ttl ttl of the message+ * @param src source address of the message+ * @param dst destination address of the message+ * @param segN total segment count+ */+ private void handleImmediateBlockAcks(final int seqZero, final int ttl, final int src, final int dst, final int segN) {+ cancelIncompleteTimer();+ sendBlockAck(seqZero, ttl, src, dst, segN);+ }++ /**+ * Parses a unsegmented lower transport control pdu.+ *+ * @param decryptedProxyPdu The complete pdu was received from the node. This is already de-obfuscated and decrypted at network layer.+ */+ /*package*/+ synchronized final void parseUnsegmentedControlLowerTransportPDU(final ControlMessage controlMessage,+ final byte[] decryptedProxyPdu) throws ExtendedInvalidCipherTextException {++ final Map<Integer, byte[]> unsegmentedMessages = new HashMap<>();+ final int lowerTransportPduLength = decryptedProxyPdu.length - 10;+ final ByteBuffer lowerTransportBuffer = ByteBuffer.allocate(lowerTransportPduLength).order(ByteOrder.BIG_ENDIAN);+ lowerTransportBuffer.put(decryptedProxyPdu, 10, lowerTransportPduLength);+ final byte[] lowerTransportPDU = lowerTransportBuffer.array();+ unsegmentedMessages.put(0, lowerTransportPDU);+ final int opCode;+ final int pduType = decryptedProxyPdu[0];+ switch (pduType) {+ case MeshManagerApi.PDU_TYPE_NETWORK:+ final byte header = decryptedProxyPdu[10]; //Lower transport pdu starts here+ opCode = header & 0x7F;+ controlMessage.setPduType(MeshManagerApi.PDU_TYPE_NETWORK);//Set the pdu type here+ controlMessage.setAszmic(0);+ controlMessage.setOpCode(opCode);+ controlMessage.setLowerTransportControlPdu(unsegmentedMessages);+ parseLowerTransportLayerPDU(controlMessage);+ break;+ case MeshManagerApi.PDU_TYPE_PROXY_CONFIGURATION:+ controlMessage.setPduType(MeshManagerApi.PDU_TYPE_PROXY_CONFIGURATION);+ controlMessage.setLowerTransportControlPdu(unsegmentedMessages);+ parseUpperTransportPDU(controlMessage);+ break;+ }+ }++ /**+ * Parses a segmented lower transport control pdu.+ *+ * @param pdu The complete pdu was received from the node. This is already de-obfuscated and decrypted at network layer.+ */+ /*package*/+ synchronized final ControlMessage parseSegmentedControlLowerTransportPDU(final byte[] pdu) {++ final byte header = pdu[10]; //Lower transport pdu starts here+ final int akf = (header >> 6) & 0x01;+ final int aid = header & 0x3F;++ final int szmic = (pdu[11] >> 7) & 0x01;+ final int seqZero = ((pdu[11] & 0x7F) << 6) | ((pdu[12] & 0xFC) >> 2);+ final int segO = ((pdu[12] & 0x3) << 3) | ((pdu[13] & 0xe0) >> 5);+ final int segN = ((pdu[13]) & 0x1F);++ final int ttl = pdu[2] & 0x7F;+ final byte[] src = MeshParserUtils.getSrcAddress(pdu);+ final byte[] dst = MeshParserUtils.getDstAddress(pdu);++ final int blockAckSrc = MeshParserUtils.unsignedBytesToInt(dst[1], dst[0]); //Destination of the received packet would be the source for the ack+ final int blockAckDst = MeshParserUtils.unsignedBytesToInt(src[1], src[0]); //Source of the received packet would be the destination for the ack++ LOG.info("SEG O: " + segO);+ LOG.info("SEG N: " + segN);++ //Start the timer irrespective of which segment was received first+ initSegmentedControlAcknowledgementTimer(seqZero, ttl, blockAckDst, blockAckSrc, segN);+ mSegmentedControlBlockAck = BlockAcknowledgementMessage.calculateBlockAcknowledgement(mSegmentedControlBlockAck, segO);+ LOG.info("Block acknowledgement value for " + mSegmentedControlBlockAck + " Seg O " + segO);++ final int payloadLength = pdu.length - 10;++ final ByteBuffer payloadBuffer = ByteBuffer.allocate(payloadLength);+ payloadBuffer.put(pdu, 10, payloadLength);+ segmentedControlMessageMap.put(segO, payloadBuffer.array());++ //Check the message count against the zero-based segN;+ final int receivedSegmentedMessageCount = segmentedControlMessageMap.size() - 1;+ if (segN == receivedSegmentedMessageCount) {+ LOG.info("All segments received");+ //Remove the incomplete timer if all segments were received++ // mHandler.removeCallbacks(mIncompleteTimerRunnable);+ stopTask(incompleteTimerTask);+ incompleteTimerTask = null;++ LOG.info("Block ack sent? " + mBlockAckSent);+ if (mDuration > System.currentTimeMillis() && !mBlockAckSent) {+ if (MeshAddress.isValidUnicastAddress(dst)) {++ // mHandler.removeCallbacksAndMessages(null);+ stopAllTasks();+ incompleteTimerTask = null;++ LOG.info("Cancelling Scheduled block ack and incomplete timer, sending an immediate block ack");+ sendBlockAck(seqZero, ttl, blockAckSrc, blockAckDst, segN);+ //mBlockAckSent = false;+ }+ }+ final int upperTransportSequenceNumber = getTransportLayerSequenceNumber(MeshParserUtils.getSequenceNumberFromPDU(pdu), seqZero);+ final byte[] sequenceNumber = MeshParserUtils.getSequenceNumberBytes(upperTransportSequenceNumber);+ final ControlMessage message = new ControlMessage();+ message.setAszmic(szmic);+ message.setSequenceNumber(sequenceNumber);+ message.setAkf(akf);+ message.setAid(aid);+ message.setSegmented(true);+ // final SparseArray<byte[]> segmentedMessages = segmentedControlMessageMap.clone();+ Map<Integer, byte[]> segmentedMessages = new HashMap<>();+ for (Integer index : segmentedControlMessageMap.keySet()) {+ segmentedMessages.put(index, segmentedControlMessageMap.get(index).clone());+ }+ segmentedControlMessageMap.clear();+ message.setLowerTransportControlPdu(segmentedMessages);+ return message;+ }++ return null;+ }++ /**+ * Start incomplete timer for segmented messages.+ */+ private void initIncompleteTimer() {++ // mHandler.postDelayed(mIncompleteTimerRunnable, INCOMPLETE_TIMER_DELAY);+ incompleteTimerTask = startTask(mIncompleteTimerRunnable, INCOMPLETE_TIMER_DELAY);++ mIncompleteTimerStarted = true;+ }++ /**+ * Restarts the incomplete timer+ */+ private void restartIncompleteTimer() {+ //Remove the existing incomplete timer+ if (mIncompleteTimerStarted) {++ // mHandler.removeCallbacks(mIncompleteTimerRunnable);+ stopTask(incompleteTimerTask);+ incompleteTimerTask = null;+ }+ //Call init to start the timer again+ initIncompleteTimer();+ }++ /**+ * Cancels an already started the incomplete timer+ */+ private void cancelIncompleteTimer() {+ //Remove the existing incomplete timer+ mIncompleteTimerStarted = false;++ // mHandler.removeCallbacks(mIncompleteTimerRunnable);+ stopTask(incompleteTimerTask);+ incompleteTimerTask = null;+ }++ /**+ * Start acknowledgement timer for segmented messages.+ *+ * @param seqZero Seqzero of the segmented messages.+ * @param ttl TTL of the segmented messages.+ * @param dst Destination address.+ */+ private void initSegmentedAccessAcknowledgementTimer(final int seqZero, final int ttl, final int src, final int dst, final int segN) {+ if (!mSegmentedAccessAcknowledgementTimerStarted) {+ mSegmentedAccessAcknowledgementTimerStarted = true;+ LOG.info("TTL: " + ttl);+ final int duration = (BLOCK_ACK_TIMER + (50 * ttl));+ LOG.info("Duration: " + duration);+ mDuration = System.currentTimeMillis() + duration;++ // mHandler.postDelayed(() -> {+ // LOG.info("Acknowledgement timer expiring");+ // sendBlockAck(seqZero, ttl, src, dst, segN);+ //}, duration);++ startTask(() -> {+ synchronized (LowerTransportLayer.this) {+ LOG.info("Acknowledgement timer expiring");+ sendBlockAck(seqZero, ttl, src, dst, segN);++ }}, new Integer(duration).longValue()+ );+ }+ }++ /**+ * Start acknowledgement timer for segmented messages.+ *+ * @param seqZero Seqzero of the segmented messages.+ * @param ttl TTL of the segmented messages.+ * @param src Source address which is the element address+ * @param dst Destination address.+ */+ private void initSegmentedControlAcknowledgementTimer(final int seqZero, final int ttl, final int src, final int dst, final int segN) {+ if (!mSegmentedControlAcknowledgementTimerStarted) {+ mSegmentedControlAcknowledgementTimerStarted = true;+ final int duration = BLOCK_ACK_TIMER + (50 * ttl);+ mDuration = System.currentTimeMillis() + duration;+ // mHandler.postDelayed(() -> sendBlockAck(seqZero, ttl, src, dst, segN), duration);++ startTask(+ () -> {+ synchronized (LowerTransportLayer.this) {+ sendBlockAck(seqZero, ttl, src, dst, segN);+ }}, new Integer(duration).longValue()+ );+ }+ }++ /**+ * Send block acknowledgement+ *+ * @param seqZero Seqzero of the segmented messages.+ * @param ttl TTL of the segmented messages.+ * @param src Source address which is the element address+ * @param dst Destination address.+ */+ private void sendBlockAck(final int seqZero, final int ttl, final int src, final int dst, final int segN) {+ final int blockAck = mSegmentedAccessBlockAck;+ if (BlockAcknowledgementMessage.hasAllSegmentsBeenReceived(blockAck, segN)) {+ LOG.info("All segments received cancelling incomplete timer");+ cancelIncompleteTimer();+ }++ final byte[] upperTransportControlPdu = createAcknowledgementPayload(seqZero, blockAck);+ LOG.info("Block acknowledgement payload: " + MeshParserUtils.bytesToHex(upperTransportControlPdu, false));+ final ControlMessage controlMessage = new ControlMessage();+ controlMessage.setOpCode(TransportLayerOpCodes.SAR_ACK_OPCODE);+ controlMessage.setTransportControlPdu(upperTransportControlPdu);+ controlMessage.setTtl(ttl);+ controlMessage.setPduType(MeshManagerApi.PDU_TYPE_NETWORK);+ controlMessage.setSrc(src);+ controlMessage.setDst(dst);+ controlMessage.setIvIndex(mUpperTransportLayerCallbacks.getIvIndex());+ final int sequenceNumber = mUpperTransportLayerCallbacks.getNode(controlMessage.getSrc()).incrementSequenceNumber();+ final byte[] sequenceNum = MeshParserUtils.getSequenceNumberBytes(sequenceNumber);+ controlMessage.setSequenceNumber(sequenceNum);+ mBlockAckSent = true;+ mLowerTransportLayerCallbacks.sendSegmentAcknowledgementMessage(controlMessage);+ mSegmentedAccessAcknowledgementTimerStarted = false;+ }++ /**+ * Creates the acknowledgement parameters.+ *+ * @param seqZero Seqzero of the message.+ * @param blockAcknowledgement Block acknowledgement+ * @return acknowledgement parameters.+ */+ private byte[] createAcknowledgementPayload(final int seqZero, final int blockAcknowledgement) {+ final int obo = 0;+ final int rfu = 0;++ final ByteBuffer buffer = ByteBuffer.allocate(6).order(ByteOrder.BIG_ENDIAN);+ buffer.put((byte) ((obo << 7) | (seqZero >> 6) & 0x7F));+ buffer.put((byte) (((seqZero << 2) & 0xFC) | rfu));+ buffer.putInt(blockAcknowledgement);+ return buffer.array();+ }++ /**+ * Parse transport layer control pdu.+ *+ * @param controlMessage underlying message containing the access pdu.+ */+ private void parseLowerTransportLayerPDU(final ControlMessage controlMessage) {+ //First we reassemble the transport layer message if its a segmented message+ reassembleLowerTransportControlPDU(controlMessage);+ final byte[] transportControlPdu = controlMessage.getTransportControlPdu();+ final int opCode = controlMessage.getOpCode();++ if (opCode == TransportLayerOpCodes.SAR_ACK_OPCODE) {+ final BlockAcknowledgementMessage acknowledgement = new BlockAcknowledgementMessage(transportControlPdu);+ controlMessage.setTransportControlMessage(acknowledgement);+ }++ }++ /**+ * Validates Sequence authentication value.+ *+ * @param seqAuth Sequence authentication.+ * @param src Source address.+ */+ private boolean isValidSeqAuth(final int seqAuth,+ final int src) {+ final Integer lastSeqAuth = mMeshNode.getSeqAuth(src);+ return lastSeqAuth == null || lastSeqAuth < seqAuth;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/LowerTransportLayerCallbacks.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/LowerTransportLayerCallbacks.javanew file mode 100644index 000000000..94e197fa6--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/LowerTransportLayerCallbacks.java@@ -0,0 +1,18 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++public interface LowerTransportLayerCallbacks {++ /**+ * Callback to notify that a block acknowledgement message be sent now.+ *+ * @param controlMessage control message to be sent+ */+ void sendSegmentAcknowledgementMessage(final ControlMessage controlMessage);++ /**+ * Callback to notify that the incomplete timer has expired.+ */+ void onIncompleteTimerExpired();++ int getTtl();+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/MeshMessage.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/MeshMessage.javanew file mode 100644index 000000000..72b033ff2--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/MeshMessage.java@@ -0,0 +1,97 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++/**+ * Abstract wrapper class for mesh message.+ */+public abstract class MeshMessage {++ private final int mAszmic = 0;+ protected Message mMessage;+ byte[] mParameters;+ protected Integer messageTtl = null;++ /**+ * Returns the application key flag used for this message.+ *+ * @return application key flag+ */+ abstract int getAkf();++ /**+ * Returns application key identifier used for this message.+ *+ * @return application key identifier+ */+ abstract int getAid();++ /**+ * Returns the opCode of this message+ *+ * @return opcode+ */+ public abstract int getOpCode();++ /**+ * Returns the parameters of this message.+ *+ * @return parameters+ */+ abstract byte[] getParameters();++ /**+ * Returns the size of message integrity check used for this message.+ *+ * @return aszmic+ */+ public final int getAszmic() {+ return mAszmic;+ }++ /**+ * Returns the message+ */+ public Message getMessage() {+ return mMessage;+ }++ /**+ * Set the access message+ *+ * @param message access message+ */+ void setMessage(final Message message) {+ mMessage = message;+ }++ /**+ * Returns the source address of the message+ */+ public int getSrc() {+ return mMessage.getSrc();+ }++ /**+ * Returns the destination address of the message+ */+ public int getDst() {+ return mMessage.getDst();+ }++ /**+ * Returns the TTL set for the mesh message+ * @return TTL value or null if not set.+ */+ public Integer getMessageTtl() {+ return messageTtl;+ }++ /**+ * Sets the TTL for this message.+ * If a TTL is not specified the message will use the default ttl set for the provisioner node.+ * @param messageTtl TTL value+ */+ public void setMessageTtl(final Integer messageTtl) {+ this.messageTtl = messageTtl;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/MeshMessageHandlerApi.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/MeshMessageHandlerApi.javanew file mode 100644index 000000000..758a515ce--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/MeshMessageHandlerApi.java@@ -0,0 +1,16 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import java.util.UUID;++/**+ * Mesh message handler api+ */+public interface MeshMessageHandlerApi {+ /**+ * Sends a mesh message specified within the {@link MeshMessage} object+ *+ * @param label Label UUID for destination address+ * @param meshMessage {@link MeshMessage} Mesh message containing the message opcode and message parameters+ */+ void createMeshMessage(final int src, final int dst, /* @Nullable */ final UUID label, final MeshMessage meshMessage);+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/MeshMessageState.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/MeshMessageState.javanew file mode 100644index 000000000..766642582--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/MeshMessageState.java@@ -0,0 +1,171 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.InternalTransportCallbacks;+import org.openremote.agent.protocol.bluetooth.mesh.MeshStatusCallbacks;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.util.List;+import java.util.logging.Logger;++/**+ * This generic class handles the mesh messages received or sent.+ * <p>+ * This class handles sending, resending and parsing mesh messages. Each message sent by the library has its own state.+ * {@link ConfigMessageState} and {@link GenericMessageState} extends this class based on the type of the message.+ * Currently the library supports basic Configuration and Generic Messages.+ * </p>+ */+abstract class MeshMessageState implements LowerTransportLayerCallbacks {++ public static final Logger LOG = Logger.getLogger(MeshMessageState.class.getName());++ MeshMessage mMeshMessage;+ final MeshTransport mMeshTransport;+ private final InternalMeshMsgHandlerCallbacks meshMessageHandlerCallbacks;+ protected InternalTransportCallbacks mInternalTransportCallbacks;+ MeshStatusCallbacks mMeshStatusCallbacks;+ int mSrc;+ int mDst;+ protected Message message;++ /**+ * Constructs the base mesh message state class+ *+ * @param meshMessage {@link MeshMessage} Mesh message+ * @param meshTransport {@link MeshTransport} Mesh transport+ * @param callbacks {@link InternalMeshMsgHandlerCallbacks} Internal mesh message handler callbacks+ */+ MeshMessageState(/* @Nullable */ final MeshMessage meshMessage,+ final MeshTransport meshTransport,+ final InternalMeshMsgHandlerCallbacks callbacks) {+ this.mMeshMessage = meshMessage;+ if (meshMessage != null) {+ this.message = meshMessage.getMessage();+ }+ this.meshMessageHandlerCallbacks = callbacks;+ this.mMeshTransport = meshTransport;+ this.mMeshTransport.setLowerTransportLayerCallbacks(this);+ }++ /**+ * Set transport callbacks+ *+ * @param callbacks callbacks+ */+ synchronized void setTransportCallbacks(final InternalTransportCallbacks callbacks) {+ this.mInternalTransportCallbacks = callbacks;+ }++ /**+ * Set mesh status call backs+ *+ * @param callbacks callbacks+ */+ synchronized void setStatusCallbacks(final MeshStatusCallbacks callbacks) {+ this.mMeshStatusCallbacks = callbacks;+ }++ /**+ * Returns the current mesh state+ */+ abstract MessageState getState();++ /**+ * Returns the mesh transport+ */+ synchronized MeshTransport getMeshTransport() {+ return mMeshTransport;+ }++ /**+ * Returns the mesh message relating to the state+ */+ public synchronized MeshMessage getMeshMessage() {+ return mMeshMessage;+ }++ /**+ * Starts sending the mesh pdu+ */+ public synchronized void executeSend() {+ if (message.getNetworkLayerPdu().size() > 0) {+ for (int i = 0; i < message.getNetworkLayerPdu().size(); i++) {+ mInternalTransportCallbacks.onMeshPduCreated(mDst, message.getNetworkLayerPdu().get(i));+ }++ if (mMeshStatusCallbacks != null) {+ mMeshStatusCallbacks.onMeshMessageProcessed(mDst, mMeshMessage);+ }+ }+ }++ /**+ * Re-sends the mesh pdu segments that were lost in flight+ *+ * @param retransmitPduIndexes list of indexes of the messages to be+ */+ final synchronized void executeResend(final List<Integer> retransmitPduIndexes) {+ if (message.getNetworkLayerPdu().size() > 0 && !retransmitPduIndexes.isEmpty()) {+ for (int i = 0; i < retransmitPduIndexes.size(); i++) {+ final int segO = retransmitPduIndexes.get(i);+ if (message.getNetworkLayerPdu().get(segO) != null) {+ final byte[] pdu = message.getNetworkLayerPdu().get(segO);+ LOG.info("Resending segment " + segO + " : " + MeshParserUtils.bytesToHex(pdu, false));+ final Message retransmitMeshMessage = mMeshTransport.createRetransmitMeshMessage(message, segO);+ mInternalTransportCallbacks.onMeshPduCreated(mDst, retransmitMeshMessage.getNetworkLayerPdu().get(segO));+ }+ }+ }+ }++ @Override+ public synchronized void onIncompleteTimerExpired() {+ LOG.info("Incomplete timer has expired, all segments were not received!");+ if (meshMessageHandlerCallbacks != null) {+ meshMessageHandlerCallbacks.onIncompleteTimerExpired(mDst);++ if (mMeshStatusCallbacks != null) {+ mMeshStatusCallbacks.onTransactionFailed(mDst, true);+ }+ }+ }++ @Override+ public synchronized int getTtl() {+ return message.getTtl();+ }++ @Override+ public synchronized void sendSegmentAcknowledgementMessage(final ControlMessage controlMessage) {+ //We don't send acknowledgements here+ final ControlMessage message = mMeshTransport.createSegmentBlockAcknowledgementMessage(controlMessage);+ LOG.info("Sending acknowledgement: " + MeshParserUtils.bytesToHex(message.getNetworkLayerPdu().get(0), false));+ mInternalTransportCallbacks.onMeshPduCreated(message.getDst(), message.getNetworkLayerPdu().get(0));+ mMeshStatusCallbacks.onBlockAcknowledgementProcessed(message.getDst(), controlMessage);+ }++ public enum MessageState {++ //Proxy configuration message+ PROXY_CONFIG_MESSAGE_STATE(500),++ //Configuration message States+ CONFIG_MESSAGE_STATE(501),++ //Application message States+ GENERIC_MESSAGE_STATE(502),+ VENDOR_MODEL_ACKNOWLEDGED_STATE(1000),+ VENDOR_MODEL_UNACKNOWLEDGED_STATE(1001);++ private int state;++ MessageState(final int state) {+ this.state = state;+ }++ public int getState() {+ return state;+ }+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/MeshModel.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/MeshModel.javanew file mode 100644index 000000000..8f6ac0a6d--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/MeshModel.java@@ -0,0 +1,256 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;++import java.util.ArrayList;+import java.util.Collections;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.UUID;++/**+ * Base mesh model class+ * <p>+ * This class contains properties such as Model Identifier, bound keys, key indexes, subscription+ * and publication settings belonging to a mesh model.+ * </p>+ */+public abstract class MeshModel {++ protected int mModelId;++ final List<Integer> mBoundAppKeyIndexes = new ArrayList<>();++ final Map<Integer, String> mBoundAppKeys = new LinkedHashMap<>();++ final List<Integer> subscriptionAddresses = new ArrayList<>();++ final List<UUID> labelUuids = new ArrayList<>();++ PublicationSettings mPublicationSettings;+ protected int currentScene;+ protected int targetScene;++ protected List<Integer> sceneNumbers = new ArrayList<>();++ public MeshModel(final int modelId) {+ this.mModelId = modelId;+ }++ MeshModel() {+ }++ /**+ * Returns the 16-bit model id which could be a SIG Model or a Vendor Model+ *+ * @return modelId+ */+ public abstract int getModelId();++ /**+ * Returns the Bluetooth SIG defined model name+ *+ * @return model name+ */+ public abstract String getModelName();++ /**+ * Returns bound appkey indexes for this model+ */+ public List<Integer> getBoundAppKeyIndexes() {+ return Collections.unmodifiableList(mBoundAppKeyIndexes);+ }++ public void setBoundAppKeyIndex(final int appKeyIndex) {+ if (!mBoundAppKeyIndexes.contains(appKeyIndex))+ mBoundAppKeyIndexes.add(appKeyIndex);+ }++ public void setBoundAppKeyIndexes(final List<Integer> indexes) {+ mBoundAppKeyIndexes.clear();+ mBoundAppKeyIndexes.addAll(indexes);+ }++ @SuppressWarnings("RedundantCollectionOperation")+ public void removeBoundAppKeyIndex(final int appKeyIndex) {+ if (mBoundAppKeyIndexes.contains(appKeyIndex)) {+ final int position = mBoundAppKeyIndexes.indexOf(appKeyIndex);+ mBoundAppKeyIndexes.remove(position);+ }+ }++ /**+ * Returns the list of subscription addresses belonging to this model+ *+ * @return subscription addresses+ */+ public List<Integer> getSubscribedAddresses() {+ return Collections.unmodifiableList(subscriptionAddresses);+ }++ /**+ * Returns the list of label UUIDs subscribed to this model+ */+ public List<UUID> getLabelUUID() {+ return Collections.unmodifiableList(labelUuids);+ }++ /**+ * Returns the label UUID for a given virtual address+ *+ * @param address 16-bit virtual address+ */+ public UUID getLabelUUID(final int address) {+ return MeshAddress.getLabelUuid(labelUuids, address);+ }++ /**+ * Sets the data from the {@link ConfigModelPublicationStatus}+ *+ * @param status publication set status+ */+ protected void setPublicationStatus(final ConfigModelPublicationStatus status,+ final UUID labelUUID) {+ if (status.isSuccessful()) {+ if (!MeshAddress.isValidUnassignedAddress(status.getPublishAddress())) {+ mPublicationSettings = new PublicationSettings(status.getPublishAddress(),+ labelUUID,+ status.getAppKeyIndex(),+ status.getCredentialFlag(),+ status.getPublishTtl(),+ status.getPublicationSteps(),+ status.getPublicationResolution(),+ status.getPublishRetransmitCount(),+ status.getPublishRetransmitIntervalSteps());+ } else {+ mPublicationSettings = null;+ }+ }+ }++ /**+ * Updates the data from the {@link ConfigModelPublicationStatus}+ *+ * @param status publication set status+ */+ protected void updatePublicationStatus(final ConfigModelPublicationStatus status) {+ if (status.isSuccessful()) {+ if (mPublicationSettings != null) {+ mPublicationSettings.setPublishAddress(status.getPublishAddress());+ if (!MeshAddress.isValidVirtualAddress(status.getPublishAddress())) {+ mPublicationSettings.setLabelUUID(null);+ }+ mPublicationSettings.setAppKeyIndex(status.getAppKeyIndex());+ mPublicationSettings.setCredentialFlag(status.getCredentialFlag());+ mPublicationSettings.setPublishTtl(status.getPublishTtl());+ mPublicationSettings.setPublicationSteps(status.getPublicationSteps());+ mPublicationSettings.setPublicationResolution(status.getPublicationResolution());+ mPublicationSettings.setPublishRetransmitCount(status.getPublishRetransmitCount());+ mPublicationSettings.setPublishRetransmitIntervalSteps(status.getPublishRetransmitIntervalSteps());+ }+ }+ }++ /**+ * Returns the publication settings used in this model+ *+ * @return publication settings+ */+ public PublicationSettings getPublicationSettings() {+ return mPublicationSettings;+ }++ public void setPublicationSettings(final PublicationSettings publicationSettings) {+ mPublicationSettings = publicationSettings;+ }++ /**+ * Sets the subscription address in a mesh model+ *+ * @param subscriptionAddress Subscription address+ */+ protected void addSubscriptionAddress(final int subscriptionAddress) {+ if (!subscriptionAddresses.contains(subscriptionAddress)) {+ subscriptionAddresses.add(subscriptionAddress);+ }+ }++ /**+ * Sets the subscription address in a mesh model+ *+ * @param labelUuid Label uuid of the the subscription address+ * @param address Subscription address+ */+ protected void addSubscriptionAddress(final UUID labelUuid, final int address) {+ if (!labelUuids.contains(labelUuid)) {+ labelUuids.add(labelUuid);+ }++ if (!subscriptionAddresses.contains(address)) {+ subscriptionAddresses.add(address);+ }+ }++ /**+ * Removes the subscription address in a mesh model+ *+ * @param address Subscription address+ */+ protected void removeSubscriptionAddress(final Integer address) {+ subscriptionAddresses.remove(address);+ }++ /**+ * Removes the subscription address in a mesh model+ *+ * @param labelUuid Label UUID+ * @param address Subscription address+ */+ protected void removeSubscriptionAddress(final UUID labelUuid,+ final Integer address) {+ labelUuids.remove(labelUuid);+ removeSubscriptionAddress(address);+ }++ /**+ * Removes all the subscription addresses in a mesh model+ */+ protected void removeAllSubscriptionAddresses() {+ labelUuids.clear();+ subscriptionAddresses.clear();+ }++ /**+ * Overwrites the subscription addresses in a mesh model by clearing the existing addresses and adding a new address+ *+ * @param subscriptionAddress Subscription address+ */+ protected void overwriteSubscriptionAddress(final Integer subscriptionAddress) {+ subscriptionAddresses.clear();+ addSubscriptionAddress(subscriptionAddress);+ }++ /**+ * Overwrites the subscription addresses in a mesh model by clearing the existing addresses and adding a new address+ *+ * @param labelUuid Label UUID+ * @param address Subscription address+ */+ protected void overwriteSubscriptionAddress(final UUID labelUuid,+ final Integer address) {+ labelUuids.clear();+ addSubscriptionAddress(labelUuid, address);+ overwriteSubscriptionAddress(address);+ }++ /**+ * Update the subscription addresses list+ *+ * @param addresses List of subscription addresses+ */+ protected void updateSubscriptionAddressesList(final List<Integer> addresses) {+ subscriptionAddresses.clear();+ subscriptionAddresses.addAll(addresses);+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/MeshTransport.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/MeshTransport.javanew file mode 100644index 000000000..8699732e6--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/MeshTransport.java@@ -0,0 +1,342 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.ApplicationKey;+import org.openremote.agent.protocol.bluetooth.mesh.MeshManagerApi;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;+import org.openremote.container.concurrent.ContainerScheduledExecutor;++import java.util.ArrayList;+import java.util.List;+import java.util.UUID;+import java.util.concurrent.CopyOnWriteArrayList;+import java.util.concurrent.Future;+import java.util.concurrent.ScheduledThreadPoolExecutor;+import java.util.concurrent.TimeUnit;+import java.util.logging.Logger;++/**+ * MeshTransport class is responsible for building the configuration and application layer mesh messages.+ */+final class MeshTransport extends NetworkLayer {++ public static final Logger LOG = Logger.getLogger(MeshTransport.class.getName());++ private static final int PROXY_CONFIGURATION_TTL = 0;++ /**+ * Constructs the MeshTransport+ *+ */+ /*+ MeshTransport(@NonNull final Context context) {+ this.mContext = context;+ initHandler();+ }+ */+ MeshTransport() {+ super();+ executor = new ContainerScheduledExecutor("Bluetooth-Mesh Thread Pool", 2);+ initHandler();+ }++ /**+ * Constructs MeshTransport+ *+ * @param node Mesh node+ */+ MeshTransport(final ProvisionedMeshNode node) {+ super();+ // this.mContext = context;+ this.mMeshNode = node;+ executor = new ContainerScheduledExecutor("Bluetooth-Mesh Thread Pool", 2);+ initHandler();+ }++ private final ScheduledThreadPoolExecutor executor;+ private final List<Future<?>> tasks = new CopyOnWriteArrayList<>();++ @Override+ protected Future<?> startTask(Runnable runnable, Long delay) {+ Future<?> task = null;+ if (delay == null || delay == 0) {+ task = executor.submit(runnable);+ } else {+ task = executor.schedule(runnable, delay, TimeUnit.MILLISECONDS);+ }+ tasks.add(task);+ return task;+ }++ @Override+ protected void stopTask(Future<?> task) {+ if (task != null) {+ task.cancel(true);+ tasks.remove(task);+ }+ }++ @Override+ protected void stopAllTasks() {+ List<Future<?>> allTasks = new ArrayList<>(tasks);+ for (Future<?> curTask : allTasks) {+ stopTask(curTask);+ }+ }++ // @Override+ protected final void initHandler() {+ // this.mHandler = new Handler(mContext.getMainLooper());+ }++ @Override+ protected synchronized final void setLowerTransportLayerCallbacks(final LowerTransportLayerCallbacks callbacks) {+ mLowerTransportLayerCallbacks = callbacks;+ }++ @Override+ final synchronized void setNetworkLayerCallbacks(final NetworkLayerCallbacks callbacks) {+ this.mNetworkLayerCallbacks = callbacks;+ }++ @Override+ final synchronized void setUpperTransportLayerCallbacks(final UpperTransportLayerCallbacks callbacks) {+ this.mUpperTransportLayerCallbacks = callbacks;+ }++ /**+ * Creates the an acknowledgement message for the received segmented messages+ *+ * @param controlMessage Control message containing the required opcodes and parameters to create the message+ * @return Control message containing the acknowledgement message pdu+ */+ final synchronized ControlMessage createSegmentBlockAcknowledgementMessage(final ControlMessage controlMessage) {+ createLowerTransportControlPDU(controlMessage);+ createNetworkLayerPDU(controlMessage);+ return controlMessage;+ }++ /**+ * Creates an access message to be sent to the peripheral node+ * <p>+ * This method will create the access message and propagate the message through the transport layers to create the final mesh pdu.+ * </p>+ *+ * @param src Source address of the provisioner/configurator.+ * @param dst Destination address to be sent to+ * @param key Device Key+ * @param akf Application key flag defines which key to be used to decrypt the message i.e device key or application key.+ * @param aid Identifier of the application key.+ * @param aszmic Defines the length of the transport mic length where 1 will encrypt withn 64 bit and 0 with 32 bit encryption.+ * @param accessOpCode Operation code for the access message.+ * @param accessMessageParameters Parameters for the access message.+ * @return access message containing the mesh pdu+ */+ final synchronized AccessMessage createMeshMessage(final int src,+ final int dst,+ /* @Nullable */ final Integer ttl,+ final byte[] key,+ final int akf,+ final int aid,+ final int aszmic,+ final int accessOpCode,+ final byte[] accessMessageParameters) {+ final ProvisionedMeshNode node = mUpperTransportLayerCallbacks.getNode(src);+ final int sequenceNumber = node.incrementSequenceNumber();+ final byte[] sequenceNum = MeshParserUtils.getSequenceNumberBytes(sequenceNumber);++ LOG.info("Src address: " + MeshAddress.formatAddress(src, false));+ LOG.info("Dst address: " + MeshAddress.formatAddress(dst, false));+ LOG.info("Key: " + MeshParserUtils.bytesToHex(key, false));+ LOG.info("akf: " + akf);+ LOG.info("aid: " + aid);+ LOG.info("aszmic: " + aszmic);+ LOG.info("Sequence number: " + sequenceNumber);+ LOG.info("Access message opcode: " + Integer.toHexString(accessOpCode));+ LOG.info("Access message parameters: " + MeshParserUtils.bytesToHex(accessMessageParameters, false));++ final AccessMessage message = new AccessMessage();+ message.setSrc(src);+ message.setDst(dst);+ message.setTtl(ttl == null ? node.getTtl() : ttl);+ message.setIvIndex(mUpperTransportLayerCallbacks.getIvIndex());+ message.setSequenceNumber(sequenceNum);+ message.setDeviceKey(key);+ message.setAkf(akf);+ message.setAid(aid);+ message.setAszmic(aszmic);+ message.setOpCode(accessOpCode);+ message.setParameters(accessMessageParameters);+ message.setPduType(MeshManagerApi.PDU_TYPE_NETWORK);++ super.createMeshMessage(message);+ return message;+ }++ /**+ * Creates an access message to be sent to the peripheral node+ * <p>+ * This method will create the access message and propagate the message through the transport layers to create the final mesh pdu.+ * </p>+ *+ * @param src Source address of the provisioner/configurator.+ * @param dst Destination address to be sent to+ * @param label Label UUID for destination address+ * @param key Application Key+ * @param akf Application key flag defines which key to be used to decrypt the message i.e device key or application key.+ * @param aid Identifier of the application key.+ * @param aszmic Defines the length of the transport mic length where 1 will encrypt withn 64 bit and 0 with 32 bit encryption.+ * @param accessOpCode Operation code for the access message.+ * @param accessMessageParameters Parameters for the access message.+ * @return access message containing the mesh pdu+ */+ final synchronized AccessMessage createMeshMessage(final int src,+ final int dst,+ /* @Nullable */ final UUID label,+ /* @Nullable */ final Integer ttl,+ /* @NonNull */ final ApplicationKey key,+ final int akf,+ final int aid,+ final int aszmic,+ final int accessOpCode,+ /* @Nullable */ final byte[] accessMessageParameters) {+ final ProvisionedMeshNode node = mUpperTransportLayerCallbacks.getNode(src);+ final int sequenceNumber = node.incrementSequenceNumber();+ final byte[] sequenceNum = MeshParserUtils.getSequenceNumberBytes(sequenceNumber);++ LOG.info("Src address: " + MeshAddress.formatAddress(src, false));+ LOG.info("Dst address: " + MeshAddress.formatAddress(dst, false));+ LOG.info("Key: " + MeshParserUtils.bytesToHex(key.getKey(), false));+ LOG.info("akf: " + akf);+ LOG.info("aid: " + aid);+ LOG.info("aszmic: " + aszmic);+ LOG.info("Sequence number: " + sequenceNumber);+ LOG.info("Access message opcode: " + Integer.toHexString(accessOpCode));+ LOG.info("Access message parameters: " + MeshParserUtils.bytesToHex(accessMessageParameters, false));++ final AccessMessage message = new AccessMessage();+ message.setSrc(src);+ message.setDst(dst);+ message.setTtl(ttl == null ? node.getTtl() : ttl);+ if (label != null) {+ message.setLabel(label);+ }+ message.setIvIndex(mUpperTransportLayerCallbacks.getIvIndex());+ message.setSequenceNumber(sequenceNum);+ message.setApplicationKey(key);+ message.setAkf(akf);+ message.setAid(aid);+ message.setAszmic(aszmic);+ message.setOpCode(accessOpCode);+ message.setParameters(accessMessageParameters);+ message.setPduType(MeshManagerApi.PDU_TYPE_NETWORK);++ super.createMeshMessage(message);+ return message;+ }++ /**+ * Creates a vendor model access message to be sent to the peripheral node+ * <p>+ * This method will create the access message and propagate the message through the transport layers to create the final mesh pdu.+ * </p>+ *+ * @param src Source address of the provisioner/configurator.+ * @param dst Destination address to be sent to+ * @param label Label UUID+ * @param key Application key+ * @param akf Application key flag defines which key to be used to decrypt the message i.e device key or application key.+ * @param aid Identifier of the application key.+ * @param aszmic Defines the length of the transport mic length where 1 will encrypt within 64 bit and 0 with 32 bit encryption.+ * @param accessOpCode Operation code for the access message.+ * @param accessMessageParameters Parameters for the access message.+ * @return access message containing the mesh pdu+ */+ final synchronized AccessMessage createVendorMeshMessage(final int companyIdentifier,+ final int src,+ final int dst,+ /* @Nullable */ final UUID label,+ /* @Nullable */ final Integer ttl,+ /* @NonNull */ final ApplicationKey key,+ final int akf,+ final int aid,+ final int aszmic,+ final int accessOpCode,+ /* @Nullable */ final byte[] accessMessageParameters) {+ final ProvisionedMeshNode node = mUpperTransportLayerCallbacks.getNode(src);+ final int sequenceNumber = node.incrementSequenceNumber();+ final byte[] sequenceNum = MeshParserUtils.getSequenceNumberBytes(sequenceNumber);++ LOG.info("Src address: " + MeshAddress.formatAddress(src, false));+ LOG.info("Dst address: " + MeshAddress.formatAddress(dst, false));+ LOG.info("Key: " + MeshParserUtils.bytesToHex(key.getKey(), false));+ LOG.info("akf: " + akf);+ LOG.info("aid: " + aid);+ LOG.info("aszmic: " + aszmic);+ LOG.info("Sequence number: " + sequenceNumber);+ LOG.info("Access message opcode: " + Integer.toHexString(accessOpCode));+ LOG.info("Access message parameters: " + MeshParserUtils.bytesToHex(accessMessageParameters, false));++ final AccessMessage message = new AccessMessage();+ message.setCompanyIdentifier(companyIdentifier);+ message.setSrc(src);+ message.setDst(dst);+ message.setTtl(ttl == null ? node.getTtl() : ttl);+ if (label != null) {+ message.setLabel(label);+ }+ message.setIvIndex(mUpperTransportLayerCallbacks.getIvIndex());+ message.setSequenceNumber(sequenceNum);+ message.setApplicationKey(key);+ message.setAkf(akf);+ message.setAid(aid);+ message.setAszmic(aszmic);+ message.setOpCode(accessOpCode);+ message.setParameters(accessMessageParameters);+ message.setPduType(MeshManagerApi.PDU_TYPE_NETWORK);++ super.createVendorMeshMessage(message);+ return message;+ }++ /**+ * Creates a proxy configuration message to be sent to the peripheral node+ *+ * @param src Source address of the provisioner/configurator.+ * @param dst destination address to be sent to+ * @param opcode Operation code for the access message.+ * @param parameters Parameters for the access message.+ * @return Control message containing the proxy configuration pdu+ */+ final synchronized ControlMessage createProxyConfigurationMessage(final int src,+ final int dst,+ final int opcode, final byte[] parameters) {+ final ProvisionedMeshNode node = mUpperTransportLayerCallbacks.getNode(src);+ final int sequenceNumber = node.incrementSequenceNumber();+ final byte[] sequenceNum = MeshParserUtils.getSequenceNumberBytes(sequenceNumber);++ LOG.info("Src address: " + MeshAddress.formatAddress(src, false));+ LOG.info("Dst address: " + MeshAddress.formatAddress(dst, false));+ LOG.info("Sequence number: " + sequenceNumber);+ LOG.info("Control message opcode: " + Integer.toHexString(opcode));+ LOG.info("Control message parameters: " + MeshParserUtils.bytesToHex(parameters, false));++ final ControlMessage message = new ControlMessage();+ message.setSrc(src);+ message.setDst(dst);+ message.setTtl(node.getTtl());+ message.setTtl(PROXY_CONFIGURATION_TTL); //TTL for proxy configuration messages are set to 0+ message.setIvIndex(mUpperTransportLayerCallbacks.getIvIndex());+ message.setSequenceNumber(sequenceNum);+ message.setOpCode(opcode);+ message.setParameters(parameters);+ message.setPduType(MeshManagerApi.PDU_TYPE_PROXY_CONFIGURATION);++ super.createMeshMessage(message);+ return message;+ }++ final synchronized Message createRetransmitMeshMessage(final Message message, final int segment) {+ return createRetransmitNetworkLayerPDU(message, segment);+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/Message.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/Message.javanew file mode 100644index 000000000..5f2560c50--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/Message.java@@ -0,0 +1,187 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.ApplicationKey;+import org.openremote.agent.protocol.bluetooth.mesh.NetworkKey;++import java.util.Map;++public abstract class Message {++ protected int ctl; // If ctl = 0 access message and ctl = 1 control message+ protected Map<Integer, byte[]> networkLayerPdu; // Mesh pdu+ private int pduType; // PDU Type+ private int ttl = 100; // Time to live+ private int src; // Source address+ private int dst; // Destination address+ private byte[] mSequenceNumber; // unique 24-bit value for each message+ private byte[] deviceKey; // Used for transport layer encryption of configuration messages+ private ApplicationKey applicationKey; // Used for transport layer encryption of application messages+ private NetworkKey networkKey; // Used for transport layer encryption of application messages+ private byte[] encryptionKey; // Derived from network key using k2 function+ private byte[] privacyKey; // Derived from privacy key using k2 function+ private int akf; // Use device key for encryption if akf = 0 or application key otherwise+ private int aid; // Used to identify the application key generated using k4 function+ private int aszmic; // if aszmic = 0 the transmic is 32-bits, if aszmic = 1 transmic 64-bits this is usually for a segmented message+ private int opCode; // Opcode of message+ private byte[] parameters; // Parameters of the message+ private int companyIdentifier; // Company identifier for vendor model messages+ private byte[] ivIndex; // IV Index of the network+ private boolean segmented;++ Message() {+ }++ public abstract int getCtl();++ public int getPduType() {+ return pduType;+ }++ public void setPduType(final int pduType) {+ this.pduType = pduType;+ }++ public final int getTtl() {+ return ttl;+ }++ public final void setTtl(final int ttl) {+ this.ttl = ttl;+ }++ public final int getSrc() {+ return src;+ }++ public final void setSrc(final int src) {+ this.src = src;+ }++ public final int getDst() {+ return dst;+ }++ public final void setDst(final int dst) {+ this.dst = dst;+ }++ public final byte[] getSequenceNumber() {+ return mSequenceNumber;+ }++ public final void setSequenceNumber(final byte[] sequenceNumber) {+ this.mSequenceNumber = sequenceNumber;+ }++ public final byte[] getDeviceKey() {+ return deviceKey;+ }++ public final void setDeviceKey(final byte[] deviceKey) {+ this.deviceKey = deviceKey;+ }++ public final ApplicationKey getApplicationKey() {+ return applicationKey;+ }++ public final void setApplicationKey(final ApplicationKey key) {+ this.applicationKey = key;+ }++ public NetworkKey getNetworkKey() {+ return networkKey;+ }++ public void setNetworkKey(final NetworkKey networkKey) {+ this.networkKey = networkKey;+ }++ public final byte[] getEncryptionKey() {+ return encryptionKey;+ }++ public final void setEncryptionKey(final byte[] encryptionKey) {+ this.encryptionKey = encryptionKey;+ }++ public final byte[] getPrivacyKey() {+ return privacyKey;+ }++ public final void setPrivacyKey(final byte[] privacyKey) {+ this.privacyKey = privacyKey;+ }++ public final int getAkf() {+ return akf;+ }++ public final void setAkf(final int akf) {+ this.akf = akf;+ }++ public final int getAid() {+ return aid;+ }++ public final void setAid(final int aid) {+ this.aid = aid;+ }++ public final int getAszmic() {+ return aszmic;+ }++ public final void setAszmic(final int aszmic) {+ this.aszmic = aszmic;+ }++ public final int getOpCode() {+ return opCode;+ }++ public final void setOpCode(final int opCode) {+ this.opCode = opCode;+ }++ public final byte[] getParameters() {+ return parameters;+ }++ public final void setParameters(final byte[] parameters) {+ this.parameters = parameters;+ }++ public final int getCompanyIdentifier() {+ return companyIdentifier;+ }++ public final void setCompanyIdentifier(final int companyIdentifier) {+ this.companyIdentifier = companyIdentifier;+ }++ public final byte[] getIvIndex() {+ return ivIndex;+ }++ public final void setIvIndex(final byte[] ivIndex) {+ this.ivIndex = ivIndex;+ }++ public final boolean isSegmented() {+ return segmented;+ }++ final void setSegmented(final boolean segmented) {+ this.segmented = segmented;+ }++ public final Map<Integer, byte[]> getNetworkLayerPdu() {+ return networkLayerPdu;+ }++ final void setNetworkLayerPdu(final Map<Integer, byte[]> pdu) {+ networkLayerPdu = pdu;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/NetworkLayer.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/NetworkLayer.javanew file mode 100644index 000000000..6a4816653--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/NetworkLayer.java@@ -0,0 +1,639 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.bouncycastle.crypto.InvalidCipherTextException;+import org.openremote.agent.protocol.bluetooth.mesh.MeshManagerApi;+import org.openremote.agent.protocol.bluetooth.mesh.NetworkKey;+import org.openremote.agent.protocol.bluetooth.mesh.Provisioner;+import org.openremote.agent.protocol.bluetooth.mesh.utils.ExtendedInvalidCipherTextException;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;+import org.openremote.agent.protocol.bluetooth.mesh.utils.SecureUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.ArrayList;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.logging.Logger;++/**+ * NetworkLayer implementation of the mesh network architecture as per the mesh profile specification.+ * <p>+ * NetworkLayer encrypts/decrypts mesh messages to be sent or received by the nodes in a mesh network.+ * <p/>+ */+abstract class NetworkLayer extends LowerTransportLayer {++ public static final Logger LOG = Logger.getLogger(NetworkLayer.class.getName());++ NetworkLayerCallbacks mNetworkLayerCallbacks;+ private Map<Integer, byte[]> segmentedAccessMessagesMessages;+ private Map<Integer, byte[]> segmentedControlMessagesMessages;++ /**+ * Set network layer callbacks+ *+ * @param callbacks {@link NetworkLayerCallbacks} callbacks+ */+ abstract void setNetworkLayerCallbacks(final NetworkLayerCallbacks callbacks);++ /**+ * Creates a mesh message+ *+ * @param message Message could be of type access or control message.+ */+ protected final void createMeshMessage(final Message message) {+ if (message instanceof AccessMessage) {+ super.createMeshMessage(message);+ } else {+ super.createMeshMessage(message);+ }+ createNetworkLayerPDU(message);+ }++ /**+ * Creates a vendor model mesh message+ *+ * @param message Message could be of type access or control message.+ */+ protected final void createVendorMeshMessage(final Message message) {+ if (message instanceof AccessMessage) {+ super.createVendorMeshMessage(message);+ } else {+ super.createVendorMeshMessage(message);+ }+ createNetworkLayerPDU(message);+ }++ @Override+ public synchronized final Message createNetworkLayerPDU(final Message message) {+ final SecureUtils.K2Output k2Output = getK2Output(message);+ final int nid = k2Output.getNid();+ final byte[] encryptionKey = k2Output.getEncryptionKey();+ LOG.info("Encryption key: " + MeshParserUtils.bytesToHex(encryptionKey, false));++ final byte[] privacyKey = k2Output.getPrivacyKey();+ LOG.info("Privacy key: " + MeshParserUtils.bytesToHex(privacyKey, false));+ final int ctl = message.getCtl();+ final int ttl = message.getTtl();+ final int ivi = message.getIvIndex()[3] & 0x01; // least significant bit of IV Index+ final byte iviNID = (byte) ((ivi << 7) | nid);+ final byte ctlTTL = (byte) ((ctl << 7) | ttl);++ final int src = message.getSrc();+ final Map<Integer, byte[]> lowerTransportPduMap;+ final Map<Integer, byte[]> encryptedPduPayload = new HashMap<>();+ final List<byte[]> sequenceNumbers = new ArrayList<>();++ final ProvisionedMeshNode node = mUpperTransportLayerCallbacks.getNode(message.getSrc());++ final int pduType = message.getPduType();+ switch (message.getPduType()) {+ case MeshManagerApi.PDU_TYPE_NETWORK:+ if (message instanceof AccessMessage) {+ lowerTransportPduMap = ((AccessMessage) message).getLowerTransportAccessPdu();+ } else {+ lowerTransportPduMap = ((ControlMessage) message).getLowerTransportControlPdu();+ }+ for (int i = 0; i < lowerTransportPduMap.size(); i++) {+ final byte[] lowerTransportPdu = lowerTransportPduMap.get(i);+ if (i != 0) {+ node.setSequenceNumber(MeshParserUtils.convert24BitsToInt(message.getSequenceNumber()));+ final byte[] sequenceNumber = MeshParserUtils.getSequenceNumberBytes(node.incrementSequenceNumber());+ message.setSequenceNumber(sequenceNumber);+ }+ sequenceNumbers.add(message.getSequenceNumber());+ LOG.info("Sequence Number: " + MeshParserUtils.bytesToHex(sequenceNumbers.get(i), false));+ final byte[] nonce = createNetworkNonce(ctlTTL, sequenceNumbers.get(i), src, message.getIvIndex());+ final byte[] encryptedPayload = encryptPdu(lowerTransportPdu, encryptionKey, nonce, message.getDst(), SecureUtils.getNetMicLength(message.getCtl()));+ encryptedPduPayload.put(i, encryptedPayload);+ LOG.info("Encrypted Network payload: " + MeshParserUtils.bytesToHex(encryptedPayload, false));+ }+ break;+ case MeshManagerApi.PDU_TYPE_PROXY_CONFIGURATION:+ lowerTransportPduMap = ((ControlMessage) message).getLowerTransportControlPdu();+ for (int i = 0; i < lowerTransportPduMap.size(); i++) {+ final byte[] lowerTransportPdu = lowerTransportPduMap.get(i);+ final byte[] sequenceNum = MeshParserUtils.getSequenceNumberBytes(node.incrementSequenceNumber());+ message.setSequenceNumber(sequenceNum);+ sequenceNumbers.add(message.getSequenceNumber());+ final byte[] nonce = createProxyNonce(message.getSequenceNumber(), src, message.getIvIndex());+ final byte[] encryptedPayload = encryptPdu(lowerTransportPdu, encryptionKey, nonce, message.getDst(), SecureUtils.getNetMicLength(message.getCtl()));+ encryptedPduPayload.put(i, encryptedPayload);+ LOG.info("Encrypted Network payload: " + MeshParserUtils.bytesToHex(encryptedPayload, false));+ }+ break;+ }++ final Map<Integer, byte[]> pduArray = new HashMap<>();+ for (int i = 0; i < encryptedPduPayload.size(); i++) {+ //Create the privacy random+ final byte[] encryptedPayload = encryptedPduPayload.get(i);+ final byte[] privacyRandom = createPrivacyRandom(encryptedPayload);+ //Next we create the PECB+ final byte[] pecb = createPECB(message.getIvIndex(), privacyRandom, privacyKey);++ final byte[] header = obfuscateNetworkHeader(ctlTTL, sequenceNumbers.get(i), src, pecb);+ final byte[] pdu = ByteBuffer.allocate(1 + 1 + header.length + encryptedPayload.length).order(ByteOrder.BIG_ENDIAN)+ .put((byte) pduType)+ .put(iviNID)+ .put(header)+ .put(encryptedPayload)+ .array();+ pduArray.put(i, pdu);+ message.setNetworkLayerPdu(pduArray);+ }++ return message;+ }++ final synchronized Message createRetransmitNetworkLayerPDU(final Message message, final int segment) {+ final SecureUtils.K2Output k2Output = getK2Output(message);+ final int nid = k2Output.getNid();+ final byte[] encryptionKey = k2Output.getEncryptionKey();+ LOG.info("Encryption key: " + MeshParserUtils.bytesToHex(encryptionKey, false));++ final byte[] privacyKey = k2Output.getPrivacyKey();+ LOG.info("Privacy key: " + MeshParserUtils.bytesToHex(privacyKey, false));+ final int ctl = message.getCtl();+ final int ttl = message.getTtl();+ final int ivi = message.getIvIndex()[3] & 0x01; // least significant bit of IV Index+ final byte iviNID = (byte) ((ivi << 7) | nid);+ final byte ctlTTL = (byte) ((ctl << 7) | ttl);++ final int src = message.getSrc();+ final Map<Integer, byte[]> lowerTransportPduMap;+ if (message instanceof AccessMessage) {+ lowerTransportPduMap = ((AccessMessage) message).getLowerTransportAccessPdu();+ } else {+ lowerTransportPduMap = ((ControlMessage) message).getLowerTransportControlPdu();+ }++ byte[] encryptedNetworkPayload = null;+ final int pduType = message.getPduType();+ if (message.getPduType() == MeshManagerApi.PDU_TYPE_NETWORK) {+ final ProvisionedMeshNode node = mUpperTransportLayerCallbacks.getNode(message.getSrc());+ final byte[] lowerTransportPdu = lowerTransportPduMap.get(segment);+ node.setSequenceNumber(MeshParserUtils.convert24BitsToInt(message.getSequenceNumber()));+ //final int sequenceNumber = node.incrementSequenceNumber();//incrementSequenceNumber(mNetworkLayerCallbacks.getProvisioner(), message.getSequenceNumber());+ final byte[] sequenceNum = MeshParserUtils.getSequenceNumberBytes(node.incrementSequenceNumber());+ message.setSequenceNumber(sequenceNum);++ LOG.info("Sequence Number: " + MeshParserUtils.bytesToHex(sequenceNum, false));++ final byte[] nonce = createNetworkNonce(ctlTTL, sequenceNum, src, message.getIvIndex());+ encryptedNetworkPayload = encryptPdu(lowerTransportPdu, encryptionKey, nonce, message.getDst(), SecureUtils.getNetMicLength(message.getCtl()));+ if (encryptedNetworkPayload == null)+ return null;+ LOG.info("Encrypted Network payload: " + MeshParserUtils.bytesToHex(encryptedNetworkPayload, false));+ }++ final Map<Integer, byte[]> pduArray = new HashMap<>();+ if (encryptedNetworkPayload == null)+ return null;++ final byte[] privacyRandom = createPrivacyRandom(encryptedNetworkPayload);+ //Next we create the PECB+ final byte[] pecb = createPECB(message.getIvIndex(), privacyRandom, privacyKey);++ final byte[] header = obfuscateNetworkHeader(ctlTTL, message.getSequenceNumber(), src, pecb);+ final byte[] pdu = ByteBuffer.allocate(1 + 1 + header.length + encryptedNetworkPayload.length).order(ByteOrder.BIG_ENDIAN)+ .put((byte) pduType)+ .put(iviNID)+ .put(header)+ .put(encryptedNetworkPayload)+ .array();+ pduArray.put(segment, pdu);+ message.setNetworkLayerPdu(pduArray);+ return message;+ }++ /**+ * Parse received mesh message+ * <p>+ * This method will drop messages with an invalid sequence number as all mesh messages are supposed to have a sequence+ * </p>+ *+ * @param key Network Key used to decrypt+ * @param node Mesh node.+ * @param data PDU received from the mesh node.+ * @param networkHeader Network header.+ * @param decryptedNetworkPayload Decrypted network payload.+ * @param ivIndex IV Index of the network.+ * @return complete {@link Message} that was successfully parsed or null otherwise.+ */+ final synchronized Message parseMeshMessage(final NetworkKey key,+ final ProvisionedMeshNode node,+ final byte[] data,+ final byte[] networkHeader,+ final byte[] decryptedNetworkPayload,+ final int ivIndex,+ final byte[] sequenceNumber) throws ExtendedInvalidCipherTextException {+ mMeshNode = node;+ final Provisioner provisioner = mNetworkLayerCallbacks.getProvisioner();+ final int ctlTtl = networkHeader[0];+ final int ctl = (ctlTtl >> 7) & 0x01;+ final int ttl = ctlTtl & 0x7F;+ // LOG.info("TTL for received message: " + ttl);+ final int src = MeshParserUtils.unsignedBytesToInt(networkHeader[5], networkHeader[4]);+ if (ctl == 1) {+ return parseControlMessage(key, provisioner.getProvisionerAddress(), data, networkHeader, decryptedNetworkPayload, src, sequenceNumber);+ } else {+ return parseAccessMessage(key, data, networkHeader, decryptedNetworkPayload, src, sequenceNumber, ivIndex);+ }+ }++ /**+ * Parses access message+ *+ * @param key Network Key used to decrypt+ * @param data Received from the node.+ * @param networkHeader De-obfuscated network header.+ * @param decryptedNetworkPayload Decrypted network payload.+ * @param src Source address.+ * @param sequenceNumber Sequence number of the received message.+ * @param ivIndex IV Index used for decryption.+ * @return access message+ */+ private AccessMessage parseAccessMessage(final NetworkKey key,+ final byte[] data,+ final byte[] networkHeader,+ final byte[] decryptedNetworkPayload,+ final int src,+ final byte[] sequenceNumber,+ int ivIndex) throws ExtendedInvalidCipherTextException {+ try {+ int receivedTtl = networkHeader[0] & 0x7F;+ final int dst = MeshParserUtils.unsignedBytesToInt(decryptedNetworkPayload[1], decryptedNetworkPayload[0]);+ LOG.info("Dst: " + MeshAddress.formatAddress(dst, true));++ if (isSegmentedMessage(decryptedNetworkPayload[2])) {+ LOG.info("Received a segmented access message from: " + MeshAddress.formatAddress(src, false));++ //Check if the received segmented message is from the same src as the previous segment+ //Ideal case this check is not needed but let's leave it for now.+ if (!mMeshNode.hasUnicastAddress(src)) {+ LOG.info("Segment received is from a different src than the one we are processing, let's drop it");+ return null;+ }++ if (segmentedAccessMessagesMessages == null) {+ segmentedAccessMessagesMessages = new HashMap<>();+ segmentedAccessMessagesMessages.put(0, data);+ } else {+ final int k = segmentedAccessMessagesMessages.size();+ segmentedAccessMessagesMessages.put(k, data);+ }+ //Removing the mDst here+ final byte[] pdu = ByteBuffer.allocate(2 + networkHeader.length + decryptedNetworkPayload.length)+ .order(ByteOrder.BIG_ENDIAN)+ .put(data, 0, 2)+ .put(networkHeader)+ .put(decryptedNetworkPayload)+ .array();++ // Spec states, section 3.5.2.4 page 77+ // If the received segments were sent with TTL set to 0, it is recommended that the+ // corresponding Segment Acknowledgment message is sent with TTL set to 0.+ final int ttl = receivedTtl == 0 ? receivedTtl : mNetworkLayerCallbacks.getProvisioner().getGlobalTtl();+ final AccessMessage message = parseSegmentedAccessLowerTransportPDU(ttl, pdu, ivIndex, sequenceNumber);++ if (message != null) {+ // final SparseArray<byte[]> segmentedMessages = segmentedAccessMessagesMessages.clone();+ Map<Integer, byte[]> segmentedMessages = new HashMap<>();+ for (Integer index : segmentedAccessMessagesMessages.keySet()) {+ segmentedMessages.put(index, segmentedAccessMessagesMessages.get(index).clone());+ }+ segmentedAccessMessagesMessages = null;+ message.setNetworkKey(key);+ message.setIvIndex(MeshParserUtils.intToBytes(ivIndex));+ message.setNetworkLayerPdu(segmentedMessages);+ message.setTtl(receivedTtl);+ message.setSrc(src);+ message.setDst(dst);+ parseUpperTransportPDU(message);+ parseAccessLayerPDU(message);+ }+ return message;++ } else {++ //Removing the mDst here+ final byte[] pdu = ByteBuffer.allocate(2 + networkHeader.length + decryptedNetworkPayload.length)+ .order(ByteOrder.BIG_ENDIAN)+ .put(data, 0, 2)+ .put(networkHeader)+ .put(decryptedNetworkPayload)+ .array();+ final AccessMessage message = parseUnsegmentedAccessLowerTransportPDU(pdu, ivIndex, sequenceNumber);+ if (message == null)+ return null;+ message.setNetworkKey(key);+ message.setIvIndex(MeshParserUtils.intToBytes(ivIndex));+ final Map<Integer, byte[]> pduArray = new HashMap<>();+ pduArray.put(0, data);+ message.setNetworkLayerPdu(pduArray);+ message.setTtl(receivedTtl);+ message.setSrc(src);+ message.setDst(dst);+ message.setSequenceNumber(sequenceNumber);+ parseUpperTransportPDU(message);+ parseAccessLayerPDU(message);+ return message;+ }+ } catch (InvalidCipherTextException ex) {+ throw new ExtendedInvalidCipherTextException(ex.getMessage(), ex.getCause(), NetworkLayer.class.getSimpleName());+ }+ }++ /**+ * Parses control message+ *+ * @param key Network Key used to decrypt+ * @param provisionerAddress Provisioner address.+ * @param data Data received from the node.+ * @param networkHeader De-obfuscated network header.+ * @param decryptedNetworkPayload Decrypted network payload.+ * @param src Source address where the pdu originated from.+ * @param sequenceNumber Sequence number of the received message.+ * @return a complete {@link ControlMessage} or null if the message was unable to parsed+ */+ private ControlMessage parseControlMessage(final NetworkKey key,+ /* @Nullable */ final Integer provisionerAddress,+ final byte[] data,+ final byte[] networkHeader,+ final byte[] decryptedNetworkPayload,+ final int src,+ final byte[] sequenceNumber) throws ExtendedInvalidCipherTextException {+ try {+ final int ttl = networkHeader[0] & 0x7F;+ final int dst = MeshParserUtils.unsignedBytesToInt(decryptedNetworkPayload[1], decryptedNetworkPayload[0]);++ //Removing the mDst here+ final byte[] decryptedProxyPdu = ByteBuffer.allocate(2 + networkHeader.length + decryptedNetworkPayload.length)+ .order(ByteOrder.BIG_ENDIAN)+ .put(data, 0, 2)+ .put(networkHeader)+ .put(decryptedNetworkPayload)+ .array();++ //We check the pdu type+ final int pduType = data[0];+ switch (pduType) {+ case MeshManagerApi.PDU_TYPE_NETWORK:++ //This is not possible however let's return null+ if (provisionerAddress == null) {+ return null;+ }++ //Check if the message is directed to us, if its not ignore the message+ if (provisionerAddress != dst) {+ LOG.info("Received a control message that was not directed to us, so we drop it");+ return null;+ }++ if (isSegmentedMessage(decryptedNetworkPayload[2])) {+ return parseSegmentedControlMessage(key, data, decryptedProxyPdu, ttl, src, dst);+ } else {+ return parseUnsegmentedControlMessage(key, data, decryptedProxyPdu, ttl, src, dst, sequenceNumber);+ }+ case MeshManagerApi.PDU_TYPE_PROXY_CONFIGURATION:+ //Proxy configuration messages are segmented only at the gatt level+ return parseUnsegmentedControlMessage(key, data, decryptedProxyPdu, ttl, src, dst, sequenceNumber);+ default:+ return null;+ }+ } catch (InvalidCipherTextException ex) {+ throw new ExtendedInvalidCipherTextException(ex.getMessage(), ex.getCause(), NetworkLayer.class.getSimpleName());+ }+ }++ /**+ * Parses an unsegmented control message+ *+ * @param key Network Key used to decrypt+ * @param data Received pdu data+ * @param decryptedProxyPdu Decrypted proxy pdu+ * @param ttl TTL of the pdu+ * @param src Source address where the pdu originated from+ * @param dst Destination address to which the pdu was sent+ * @param sequenceNumber Sequence number of the pdu+ * @return a complete {@link ControlMessage} or null if the message was unable to parsed+ */+ private ControlMessage parseUnsegmentedControlMessage(final NetworkKey key,+ final byte[] data,+ final byte[] decryptedProxyPdu,+ final int ttl,+ final int src,+ final int dst,+ final byte[] sequenceNumber) throws ExtendedInvalidCipherTextException {+ final ControlMessage message = new ControlMessage();+ message.setNetworkKey(key);+ message.setIvIndex(mUpperTransportLayerCallbacks.getIvIndex());+ final Map<Integer, byte[]> proxyPduArray = new HashMap<>();+ proxyPduArray.put(0, data);+ message.setNetworkLayerPdu(proxyPduArray);+ message.setTtl(ttl);+ message.setSrc(src);+ message.setDst(dst);+ message.setSequenceNumber(sequenceNumber);+ message.setSegmented(false);+ parseUnsegmentedControlLowerTransportPDU(message, decryptedProxyPdu);++ return message;+ }++ /**+ * Parses a unsegmented control message+ *+ * @param key Network Key used to decrypt+ * @param data Received pdu data+ * @param decryptedProxyPdu Decrypted proxy pdu+ * @param ttl TTL of the pdu+ * @param src Source address where the pdu originated from+ * @param dst Destination address to which the pdu was sent+ * @return a complete {@link ControlMessage} or null if the message was unable to parsed+ */+ private ControlMessage parseSegmentedControlMessage(final NetworkKey key, final byte[] data, final byte[] decryptedProxyPdu, final int ttl, final int src, final int dst) {+ if (segmentedControlMessagesMessages == null) {+ segmentedControlMessagesMessages = new HashMap<>();+ segmentedControlMessagesMessages.put(0, data);+ } else {+ final int k = segmentedControlMessagesMessages.size();+ segmentedAccessMessagesMessages.put(k, data);+ }++ final ControlMessage message = parseSegmentedControlLowerTransportPDU(decryptedProxyPdu);+ if (message != null) {+ // final SparseArray<byte[]> segmentedMessages = segmentedControlMessagesMessages.clone();+ Map<Integer, byte[]> segmentedMessages = new HashMap<>();+ for (Integer index : segmentedControlMessagesMessages.keySet()) {+ segmentedMessages.put(index, segmentedControlMessagesMessages.get(index).clone());+ }+ segmentedControlMessagesMessages = null;+ message.setNetworkKey(key);+ message.setIvIndex(mUpperTransportLayerCallbacks.getIvIndex());+ message.setNetworkLayerPdu(segmentedMessages);+ message.setTtl(ttl);+ message.setSrc(src);+ message.setDst(dst);+ }+ return message;+ }++ /**+ * Returns the master credentials {@link SecureUtils.K2Output}+ *+ * @param message Message+ */+ private SecureUtils.K2Output getK2Output(final Message message) {+ final NetworkKey networkKey;+ if (message.getAkf() == APPLICATION_KEY_IDENTIFIER) {+ networkKey = mNetworkLayerCallbacks.getPrimaryNetworkKey();+ } else {+ final int netKeyIndex = message.getApplicationKey().getBoundNetKeyIndex();+ networkKey = mNetworkLayerCallbacks.getNetworkKey(netKeyIndex);+ }+ return networkKey.getTxDerivatives();+ }++ /**+ * Obfuscates the network header+ *+ * @param ctlTTL Message type and ttl bit+ * @param sequenceNumber Sequence number of the message+ * @param src Source address+ * @param pecb Value derived from the privacy random+ * @return Obfuscated network header+ */+ private byte[] obfuscateNetworkHeader(final byte ctlTTL, final byte[] sequenceNumber, final int src, final byte[] pecb) {++ final ByteBuffer buffer = ByteBuffer.allocate(1 + sequenceNumber.length + 2).order(ByteOrder.BIG_ENDIAN);+ buffer.put(ctlTTL);+ buffer.put(sequenceNumber); //sequence number+ buffer.putShort((short) src); //source address++ final byte[] headerBuffer = buffer.array();++ final ByteBuffer bufferPECB = ByteBuffer.allocate(6);+ bufferPECB.put(pecb, 0, 6);++ final byte[] obfuscated = new byte[6];+ for (int i = 0; i < 6; i++)+ obfuscated[i] = (byte) (headerBuffer[i] ^ pecb[i]);++ return obfuscated;+ }++ /**+ * De-obfuscates the network header+ *+ * @param pdu Received from the node+ * @return Obfuscated network header+ */+ static byte[] deObfuscateNetworkHeader(final byte[] pdu,+ final byte[] ivIndex,+ final byte[] privacyKey) {+ final ByteBuffer obfuscatedNetworkBuffer = ByteBuffer.allocate(6);+ obfuscatedNetworkBuffer.order(ByteOrder.BIG_ENDIAN);+ obfuscatedNetworkBuffer.put(pdu, 2, 6);+ final byte[] obfuscatedData = obfuscatedNetworkBuffer.array();++ final ByteBuffer privacyRandomBuffer = ByteBuffer.allocate(7);+ privacyRandomBuffer.order(ByteOrder.BIG_ENDIAN);+ privacyRandomBuffer.put(pdu, 8, 7);+ final byte[] privacyRandom = createPrivacyRandom(privacyRandomBuffer.array());++ final byte[] pecb = createPECB(ivIndex, privacyRandom, privacyKey);+ final byte[] deObfuscatedData = new byte[6];++ for (int i = 0; i < 6; i++)+ deObfuscatedData[i] = (byte) (obfuscatedData[i] ^ pecb[i]);++ return deObfuscatedData;+ }++ /**+ * Creates the privacy random.+ *+ * @param encryptedUpperTransportPDU Encrypted transport pdu+ * @return Privacy random+ */+ private static byte[] createPrivacyRandom(final byte[] encryptedUpperTransportPDU) {+ final byte[] privacyRandom = new byte[7];+ System.arraycopy(encryptedUpperTransportPDU, 0, privacyRandom, 0, privacyRandom.length);+ return privacyRandom;+ }++ private static byte[] createPECB(final byte[] ivIndex, final byte[] privacyRandom, final byte[] privacyKey) {+ final ByteBuffer buffer = ByteBuffer.allocate(5 + privacyRandom.length + ivIndex.length);+ buffer.order(ByteOrder.BIG_ENDIAN);+ buffer.put(new byte[]{0x00, 0x00, 0x00, 0x00, 0x00});+ buffer.put(ivIndex);+ buffer.put(privacyRandom);+ final byte[] temp = buffer.array();+ return SecureUtils.encryptWithAES(temp, privacyKey);+ }++ /**+ * Creates the network nonce+ *+ * @param ctlTTL Combined ctl and ttl value+ * @param sequenceNumber Sequence number of the message+ * @param src Source address+ * @return Network nonce+ */+ static byte[] createNetworkNonce(final byte ctlTTL, final byte[] sequenceNumber, final int src, final byte[] ivIndex) {+ final ByteBuffer networkNonce = ByteBuffer.allocate(13);+ networkNonce.put((byte) NONCE_TYPE_NETWORK); //Nonce type+ networkNonce.put(ctlTTL); // CTL and TTL+ networkNonce.put(sequenceNumber);+ networkNonce.putShort((short) src);+ networkNonce.put(new byte[]{PAD_NETWORK_NONCE, PAD_NETWORK_NONCE}); //PAD+ networkNonce.put(ivIndex);+ return networkNonce.array();+ }++ /**+ * Creates the proxy nonce+ *+ * @param sequenceNumber Sequence number of the message+ * @param src Source address+ * @return Proxy nonce+ */+ static byte[] createProxyNonce(final byte[] sequenceNumber, final int src, final byte[] ivIndex) {+ final ByteBuffer applicationNonceBuffer = ByteBuffer.allocate(13);+ applicationNonceBuffer.put((byte) NONCE_TYPE_PROXY); //Nonce type+ applicationNonceBuffer.put((byte) PAD_PROXY_NONCE); //PAD+ applicationNonceBuffer.put(sequenceNumber);+ applicationNonceBuffer.putShort((short) src);+ applicationNonceBuffer.put(new byte[]{PAD_PROXY_NONCE, PAD_PROXY_NONCE});+ applicationNonceBuffer.put(ivIndex);+ return applicationNonceBuffer.array();+ }++ /**+ * Encrypts the pdu+ *+ * @param lowerTransportPdu lower transport pdu to be encrypted+ * @param encryptionKey Encryption key+ * @param nonce nonce depending on the pdu type+ * @param dst Destination address+ * @param micLength Message integrity check length+ */+ private byte[] encryptPdu(final byte[] lowerTransportPdu,+ final byte[] encryptionKey,+ final byte[] nonce,+ final int dst,+ final int micLength) {+ //Adding the destination address on network layer+ final byte[] unencryptedNetworkPayload = ByteBuffer.allocate(2 + lowerTransportPdu.length).order(ByteOrder.BIG_ENDIAN)+ .putShort((short) dst)+ .put(lowerTransportPdu).array();+ //Network layer encryption+ return SecureUtils.encryptCCM(unencryptedNetworkPayload, encryptionKey, nonce, micLength);+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/NetworkLayerCallbacks.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/NetworkLayerCallbacks.javanew file mode 100644index 000000000..40338f1ed--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/NetworkLayerCallbacks.java@@ -0,0 +1,39 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.NetworkKey;+import org.openremote.agent.protocol.bluetooth.mesh.Provisioner;++import java.util.List;++public interface NetworkLayerCallbacks {++ /**+ * Callback to retrieve the current provisioner of the network+ */+ Provisioner getProvisioner();++ /**+ * Callback to retrieve a provisioner of the mesh network+ *+ * @param unicastAddress address of the provisioner+ */+ Provisioner getProvisioner(final int unicastAddress);++ /**+ * Callback to retrieve the primary network key of the mesh network.+ * <p>This usually is the key with the 0th index in the netkey list</p>+ */+ NetworkKey getPrimaryNetworkKey();++ /**+ * Callback to retrieve the network key of the mesh network.+ *+ * @param keyIndex Index of the network key+ */+ NetworkKey getNetworkKey(final int keyIndex);++ /**+ * Callback to retrieve the list of {@link NetworkKey} belonging to this network.+ */+ List<NetworkKey> getNetworkKeys();+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProvisionedBaseMeshNode.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProvisionedBaseMeshNode.javanew file mode 100644index 000000000..8c0e06f42--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProvisionedBaseMeshNode.java@@ -0,0 +1,274 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.Features;+import org.openremote.agent.protocol.bluetooth.mesh.NodeKey;+import org.openremote.agent.protocol.bluetooth.mesh.utils.NetworkTransmitSettings;+import org.openremote.agent.protocol.bluetooth.mesh.utils.RelaySettings;++import java.util.ArrayList;+import java.util.HashMap;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;++abstract class ProvisionedBaseMeshNode {++ public static final int DISABLED = 0;+ public static final int ENABLED = 1;+ public static final int UNSUPPORTED = 2;+ public static final int LOW = 0; //Low security+ public static final int HIGH = 1; //High security+ protected static final String TAG = ProvisionedBaseMeshNode.class.getSimpleName();+ public long mTimeStampInMillis;+ protected String nodeName = "My Node";+ protected Integer ttl = 5;+ protected Boolean secureNetworkBeaconSupported;+ protected NetworkTransmitSettings networkTransmitSettings;+ protected RelaySettings relaySettings;+ /**+ * Unique identifier of the mesh network+ */+ String meshUuid;+ /**+ * Device UUID+ */+ String uuid;+ int security = LOW;+ int unicastAddress;+ boolean isConfigured;+ byte[] deviceKey;+ int sequenceNumber = 0;+ Integer companyIdentifier = null;+ Integer productIdentifier = null;+ Integer versionIdentifier = null;+ Integer crpl = null;+ Features nodeFeatures = null;+ // SparseIntArrayParcelable mSeqAuth = new SparseIntArrayParcelable();+ Map<Integer, Integer> mSeqAuth = new HashMap<>();+ List<NodeKey> mAddedNetKeys = new ArrayList<>();+ List<NodeKey> mAddedAppKeys = new ArrayList<>();+ byte[] mFlags;+ Map<Integer, Element> mElements = new LinkedHashMap<>();+ boolean excluded = false;+ int nodeIdentityState;++ public ProvisionedBaseMeshNode() {+ }++ public String getMeshUuid() {+ return meshUuid;+ }++ public void setMeshUuid(final String meshUuid) {+ this.meshUuid = meshUuid;+ }++ public String getUuid() {+ return uuid;+ }++ public void setUuid(final String uuid) {+ this.uuid = uuid;+ }++ public final boolean isConfigured() {+ return isConfigured;+ }++ public final void setConfigured(final boolean configured) {+ isConfigured = configured;+ }++ public final String getNodeName() {+ return nodeName;+ }++ public final void setNodeName(final String nodeName) {+ if (nodeName != null && nodeName.length() > 0)+ this.nodeName = nodeName;+ }++ public final int getUnicastAddress() {+ return unicastAddress;+ }++ /**+ * Sets the unicast address of the node+ * <p>This is to be used only by the library</p>+ */+ public final void setUnicastAddress(final int unicastAddress) {+ this.unicastAddress = unicastAddress;+ }++ /**+ * Returns the number of elements in the node+ */+ public int getNumberOfElements() {+ return mElements.size();+ }++ /**+ * Returns the unicast address used by the last element in the node+ */+ public int getLastUnicastAddress() {+ final int elementCount = getNumberOfElements();+ return elementCount == 1 ? unicastAddress : (unicastAddress + (elementCount - 1));+ }++ public final Integer getTtl() {+ return ttl;+ }++ public final void setTtl(final Integer ttl) {+ this.ttl = ttl;+ }++ public final byte[] getFlags() {+ return mFlags;+ }++ public final void setFlags(final byte[] flags) {+ this.mFlags = flags;+ }++ public long getTimeStamp() {+ return mTimeStampInMillis;+ }++ public void setTimeStamp(final long timestamp) {+ mTimeStampInMillis = timestamp;+ }++ //+ // Returns the {@link SecurityState} of the node+ //+ //@SecurityState+ public int getSecurity() {+ return security;+ }++ //+ // Set security state of the node {@link SecurityState}+ //+ public void setSecurity(/*@SecurityState*/ final int security) {+ this.security = security;+ }++ /**+ * Returns true if the node is blacklisted or false otherwise+ *+ * @deprecated Use {@link #isExcluded()} instead+ */+ @Deprecated+ public boolean isBlackListed() {+ return isExcluded();+ }++ /**+ * Blacklist a node.+ *+ * @param blackListed true if blacklisted+ * @deprecated Use {@link #setExcluded(boolean)} instead+ */+ @Deprecated+ public void setBlackListed(final boolean blackListed) {+ setExcluded(blackListed);+ }++ //+ // Returns the {@link SecureNetworkBeacon} beacon of this node+ //+ public Boolean isSecureNetworkBeaconSupported() {+ return secureNetworkBeaconSupported;+ }++ //+ //Sets the {@link SecureNetworkBeacon} beacon for this node+ //+ public void setSecureNetworkBeaconSupported(final Boolean enable) {+ this.secureNetworkBeaconSupported = enable;+ }++ /**+ * Returns {@link NetworkTransmitSettings} of this node+ */+ public NetworkTransmitSettings getNetworkTransmitSettings() {+ return networkTransmitSettings;+ }++ /**+ * Sets {@link NetworkTransmitSettings} of this node+ */+ public void setNetworkTransmitSettings(final NetworkTransmitSettings networkTransmitSettings) {+ this.networkTransmitSettings = networkTransmitSettings;+ }++ /**+ * Returns {@link RelaySettings} of this node+ */+ public RelaySettings getRelaySettings() {+ return relaySettings;+ }++ /**+ * Sets {@link NetworkTransmitSettings} of this node+ */+ public void setRelaySettings(final RelaySettings relaySettings) {+ this.relaySettings = relaySettings;+ }++ /**+ * Returns true if the node is marked as excluded.+ *+ * @return true if marked as excluded or false otherwise.+ */+ public boolean isExcluded() {+ return excluded;+ }++ //+ // Returns the node {@link NodeIdentityState}.+ //+ // @NodeIdentityState+ public int getNodeIdentityState() {+ return nodeIdentityState;+ }++ //+ // Marks a node as excluded. Note that to exclude a node from a network, users must call+ // {@link MeshNetwork#excludeNode(ProvisionedMeshNode)}+ //+ // @param excluded true if the node is to be excluded or false otherwise+ //+ public void setExcluded(final boolean excluded) {+ this.excluded = excluded;+ }++ /*+ @Retention(RetentionPolicy.SOURCE)+ @IntDef({LOW, HIGH})+ public @interface SecurityState {+ }+ */++ /**+ * Secure Network Beacon state determines if a node is periodically broadcasting Secure Network Beacons.+ */+ /*+ @Retention(RetentionPolicy.SOURCE)+ @IntDef({DISABLED, ENABLED})+ public @interface SecureNetworkBeaconState {+ }+ */++ /**+ * The Node Identity state determines if a node is advertising with Node Identity messages on a subnet.+ * If the Mesh Proxy Service is exposed, the node can be configured to advertise with Node Identity on a subnet.+ */+ /*+ @Retention(RetentionPolicy.SOURCE)+ @IntDef({DISABLED, ENABLED, UNSUPPORTED})+ public @interface NodeIdentityState {+ }+ */+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProvisionedMeshNode.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProvisionedMeshNode.javanew file mode 100644index 000000000..f68f9dbbd--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProvisionedMeshNode.java@@ -0,0 +1,460 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.ApplicationKey;+import org.openremote.agent.protocol.bluetooth.mesh.Features;+import org.openremote.agent.protocol.bluetooth.mesh.NetworkKey;+import org.openremote.agent.protocol.bluetooth.mesh.NodeKey;+import org.openremote.agent.protocol.bluetooth.mesh.Provisioner;+import org.openremote.agent.protocol.bluetooth.mesh.models.ConfigurationServerModel;+import org.openremote.agent.protocol.bluetooth.mesh.models.SigModelParser;+import org.openremote.agent.protocol.bluetooth.mesh.provisionerstates.UnprovisionedMeshNode;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;+import org.openremote.agent.protocol.bluetooth.mesh.utils.SecureUtils;++import java.util.ArrayList;+import java.util.Collections;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.logging.Logger;++public final class ProvisionedMeshNode extends ProvisionedBaseMeshNode {++ public static final Logger LOG = Logger.getLogger(ProvisionedMeshNode.class.getName());++ public ProvisionedMeshNode() {+ }++ /**+ * Constructor to be used only by hte library+ *+ * @param node {@link UnprovisionedMeshNode}+ */+ public ProvisionedMeshNode(final UnprovisionedMeshNode node) {+ uuid = node.getDeviceUuid().toString();+ isConfigured = node.isConfigured();+ nodeName = node.getNodeName();+ mAddedNetKeys.add(new NodeKey(node.getKeyIndex()));+ mFlags = node.getFlags();+ unicastAddress = node.getUnicastAddress();+ deviceKey = node.getDeviceKey();+ ttl = node.getTtl();+ final NetworkKey networkKey = new NetworkKey(node.getKeyIndex(), node.getNetworkKey());+ mTimeStampInMillis = node.getTimeStamp();+ }++ /**+ * Constructor to be used only by the library+ *+ * @param provisioner {@link Provisioner}+ * @param netKeys List of {@link NetworkKey}+ * @param appKeys List of {@link ApplicationKey}+ */+ public ProvisionedMeshNode(final Provisioner provisioner,+ final List<NetworkKey> netKeys,+ final List<ApplicationKey> appKeys) {+ this.meshUuid = provisioner.getMeshUuid();+ uuid = provisioner.getProvisionerUuid();+ isConfigured = true;+ nodeName = provisioner.getProvisionerName();+ for (NetworkKey key : netKeys) {+ mAddedNetKeys.add(new NodeKey(key.getKeyIndex(), false));+ }+ for (ApplicationKey key : appKeys) {+ mAddedAppKeys.add(new NodeKey(key.getKeyIndex(), false));+ }+ if (provisioner.getProvisionerAddress() != null)+ unicastAddress = provisioner.getProvisionerAddress();+ sequenceNumber = 0;+ deviceKey = SecureUtils.generateRandomNumber();+ ttl = provisioner.getGlobalTtl();+ mTimeStampInMillis = System.currentTimeMillis();+ final MeshModel model = SigModelParser.getSigModel(SigModelParser.CONFIGURATION_CLIENT);+ final HashMap<Integer, MeshModel> models = new HashMap<>();+ models.put(model.getModelId(), model);+ final Element element = new Element(unicastAddress, 0, models);+ final HashMap<Integer, Element> elements = new HashMap<>();+ elements.put(unicastAddress, element);+ mElements = elements;+ nodeFeatures = new Features(Features.UNSUPPORTED, Features.UNSUPPORTED, Features.UNSUPPORTED, Features.UNSUPPORTED);+ }++ public final Map<Integer, Element> getElements() {+ return mElements;+ }++ /**+ * Check if an unicast address is the address of an element+ *+ * @param unicastAddress the address to check+ * @return if this address is the address of an element+ */+ public final boolean hasUnicastAddress(final int unicastAddress) {+ if (unicastAddress == getUnicastAddress())+ return true;+ for (Element element : mElements.values()) {+ if (element.getElementAddress() == unicastAddress)+ return true;+ }+ return false;+ }++ public final void setElements(final Map<Integer, Element> elements) {+ mElements = elements;+ }++ public final byte[] getDeviceKey() {+ return deviceKey;+ }++ public void setDeviceKey(final byte[] deviceKey) {+ this.deviceKey = deviceKey;+ }++ public final int getSequenceNumber() {+ return sequenceNumber;+ }++ /**+ * Sets the sequence number+ * <p>+ * This is only meant to be used internally within the library.+ * However this is open now for users to set the sequence number manually in provisioner node.+ * </p>+ *+ * @param sequenceNumber sequence number of the node+ */+ public final void setSequenceNumber(final int sequenceNumber) {+ this.sequenceNumber = sequenceNumber;+ }++ public final Integer getCompanyIdentifier() {+ return companyIdentifier;+ }++ public final void setCompanyIdentifier(final Integer companyIdentifier) {+ this.companyIdentifier = companyIdentifier;+ }++ public final Integer getProductIdentifier() {+ return productIdentifier;+ }++ public final void setProductIdentifier(final Integer productIdentifier) {+ this.productIdentifier = productIdentifier;+ }++ public final Integer getVersionIdentifier() {+ return versionIdentifier;+ }++ public final void setVersionIdentifier(final Integer versionIdentifier) {+ this.versionIdentifier = versionIdentifier;+ }++ public final Integer getCrpl() {+ return crpl;+ }++ public final void setCrpl(final Integer crpl) {+ this.crpl = crpl;+ }++ /**+ * Returns the {@link Features} of the node+ */+ public final Features getNodeFeatures() {+ return nodeFeatures;+ }++ /**+ * Set {@link Features} of the node+ *+ * @param features feature set supported by the node+ */+ public final void setNodeFeatures(final Features features) {+ this.nodeFeatures = features;+ }++ /**+ * Returns the list of Network keys added to this node+ */+ public final List<NodeKey> getAddedNetKeys() {+ return Collections.unmodifiableList(mAddedNetKeys);+ }++ public final void setAddedNetKeys(final List<NodeKey> addedNetKeyIndexes) {+ mAddedNetKeys = addedNetKeyIndexes;+ }++ /**+ * Adds a NetKey index that was added to the node+ *+ * @param index NetKey index+ */+ protected final void setAddedNetKeyIndex(final int index) {+ if (!MeshParserUtils.isNodeKeyExists(mAddedNetKeys, index)) {+ mAddedNetKeys.add(new NodeKey(index));+ }+ }++ /**+ * Update a net key's updated state+ *+ * @param index NetKey index+ */+ protected final void updateAddedNetKey(final int index) {+ final NodeKey nodeKey = MeshParserUtils.getNodeKey(mAddedNetKeys, index);+ if (nodeKey != null) {+ nodeKey.setUpdated(true);+ }+ }++ /**+ * Update the added net key list of the node+ *+ * @param indexes NetKey index+ */+ protected final void updateNetKeyList(final List<Integer> indexes) {+ mAddedNetKeys.clear();+ for (Integer index : indexes) {+ mAddedNetKeys.add(new NodeKey(index, false));+ }+ }++ /**+ * Removes an NetKey index that was added to the node+ *+ * @param index NetKey index+ */+ protected final void removeAddedNetKeyIndex(final int index) {+ for (int i = 0; i < mAddedNetKeys.size(); i++) {+ final int keyIndex = mAddedNetKeys.get(i).getIndex();+ if (keyIndex == index) {+ mAddedNetKeys.remove(i);+ for (Element element : mElements.values()) {+ for (MeshModel model : element.getMeshModels().values()) {+ if (model.getModelId() == SigModelParser.CONFIGURATION_SERVER) {+ final ConfigurationServerModel configServerModel = (ConfigurationServerModel) model;+ if (configServerModel.getHeartbeatPublication() != null &&+ configServerModel.getHeartbeatPublication().getNetKeyIndex() == index) {+ configServerModel.setHeartbeatPublication(null);+ }+ }+ }+ }+ break;+ }+ }+ }++ /**+ * Returns the list of added AppKey indexes to the node+ */+ public final List<NodeKey> getAddedAppKeys() {+ return mAddedAppKeys;+ }++ public final void setAddedAppKeys(final List<NodeKey> addedAppKeyIndexes) {+ mAddedAppKeys = addedAppKeyIndexes;+ }++ /**+ * Adds an AppKey index that was added to the node+ *+ * @param index AppKey index+ */+ protected final void setAddedAppKeyIndex(final int index) {+ if (!MeshParserUtils.isNodeKeyExists(mAddedAppKeys, index)) {+ this.mAddedAppKeys.add(new NodeKey(index));+ }+ }++ /**+ * Update an app key's updated state+ *+ * @param index AppKey index+ */+ protected final void updateAddedAppKey(final int index) {+ final NodeKey nodeKey = MeshParserUtils.getNodeKey(mAddedNetKeys, index);+ if (nodeKey != null) {+ nodeKey.setUpdated(true);+ }+ }++ /**+ * Update the added net key list of the node+ *+ * @param netKeyIndex NetKey Index+ * @param indexes AppKey indexes+ */+ protected final void updateAppKeyList(final int netKeyIndex, final List<Integer> indexes, final List<ApplicationKey> keyIndexes) {+ if (mAddedAppKeys.isEmpty()) {+ mAddedAppKeys.addAll(addAppKeyList(indexes, new ArrayList<>()));+ } else {+ final ArrayList<NodeKey> tempList = new ArrayList<>(mAddedAppKeys);+ for (ApplicationKey applicationKey : keyIndexes) {+ if (applicationKey.getBoundNetKeyIndex() == netKeyIndex) {+ for (NodeKey nodeKey : mAddedAppKeys) {+ if (nodeKey.getIndex() == applicationKey.getKeyIndex()) {+ tempList.remove(nodeKey);+ }+ }+ }+ }+ mAddedAppKeys.clear();+ addAppKeyList(indexes, tempList);+ mAddedAppKeys.addAll(tempList);+ }+ }++ private List<NodeKey> addAppKeyList(final List<Integer> indexes, final ArrayList<NodeKey> tempList) {+ for (Integer index : indexes) {+ tempList.add(new NodeKey(index, false));+ }+ return tempList;+ }++ /**+ * Removes an AppKey index that was added to the node+ *+ * @param index AppKey index+ */+ protected final void removeAddedAppKeyIndex(final int index) {+ for (int i = 0; i < mAddedAppKeys.size(); i++) {+ final int keyIndex = mAddedAppKeys.get(i).getIndex();+ if (keyIndex == index) {+ mAddedAppKeys.remove(i);+ for (Map.Entry<Integer, Element> elementEntry : getElements().entrySet()) {+ final Element element = elementEntry.getValue();+ for (Map.Entry<Integer, MeshModel> modelEntry : element.getMeshModels().entrySet()) {+ final MeshModel model = modelEntry.getValue();+ if (model != null) {+ for (int j = 0; j < model.getBoundAppKeyIndexes().size(); j++) {+ final int boundKeyIndex = model.getBoundAppKeyIndexes().get(j);+ if (boundKeyIndex == index) {+ model.mBoundAppKeyIndexes.remove(j);+ break;+ }+ }+ }+ }+ }+ break;+ }+ }+ }++ /**+ * Sets the data from the {@link ConfigCompositionDataStatus}+ *+ * @param configCompositionDataStatus Composition data status object+ */+ protected final void setCompositionData(final ConfigCompositionDataStatus configCompositionDataStatus) {+ companyIdentifier = configCompositionDataStatus.getCompanyIdentifier();+ productIdentifier = configCompositionDataStatus.getProductIdentifier();+ versionIdentifier = configCompositionDataStatus.getVersionIdentifier();+ crpl = configCompositionDataStatus.getCrpl();+ final boolean relayFeatureSupported = configCompositionDataStatus.isRelayFeatureSupported();+ final boolean proxyFeatureSupported = configCompositionDataStatus.isProxyFeatureSupported();+ final boolean friendFeatureSupported = configCompositionDataStatus.isFriendFeatureSupported();+ final boolean lowPowerFeatureSupported = configCompositionDataStatus.isLowPowerFeatureSupported();+ nodeFeatures = new Features(friendFeatureSupported ? Features.ENABLED : Features.UNSUPPORTED,+ lowPowerFeatureSupported ? Features.ENABLED : Features.UNSUPPORTED,+ proxyFeatureSupported ? Features.ENABLED : Features.UNSUPPORTED,+ relayFeatureSupported ? Features.ENABLED : Features.UNSUPPORTED);+ mElements.putAll(configCompositionDataStatus.getElements());+ }++ private int getFeatureState(final Boolean feature) {+ if (feature != null && feature) {+ return 2;+ }+ return 0;+ }++ /**+ * Sets the bound app key data from the {@link ConfigModelAppStatus}+ *+ * @param configModelAppStatus ConfigModelAppStatus containing the bound app key information+ */+ protected final void setAppKeyBindStatus(+ final ConfigModelAppStatus configModelAppStatus) {+ if (configModelAppStatus.isSuccessful()) {+ final Element element = mElements.get(configModelAppStatus.getElementAddress());+ if (element != null) {+ final int modelIdentifier = configModelAppStatus.getModelIdentifier();+ final MeshModel model = element.getMeshModels().get(modelIdentifier);+ if (model != null) {+ final int appKeyIndex = configModelAppStatus.getAppKeyIndex();+ model.setBoundAppKeyIndex(appKeyIndex);+ }+ }+ }+ }++ /**+ * Sets the unbind app key data from the {@link ConfigModelAppStatus}+ *+ * @param configModelAppStatus ConfigModelAppStatus containing the unbound app key information+ */+ protected final void setAppKeyUnbindStatus(+ final ConfigModelAppStatus configModelAppStatus) {+ if (configModelAppStatus.isSuccessful()) {+ final Element element = mElements.get(configModelAppStatus.getElementAddress());+ if (element != null) {+ final int modelIdentifier = configModelAppStatus.getModelIdentifier();+ final MeshModel model = element.getMeshModels().get(modelIdentifier);+ final int appKeyIndex = configModelAppStatus.getAppKeyIndex();+ if (model != null) {+ model.removeBoundAppKeyIndex(appKeyIndex);+ }+ }+ }+ }++ private void sortElements(final Map<Integer, Element> unorderedElements) {+ final Set<Integer> unorderedKeys = unorderedElements.keySet();++ final List<Integer> orderedKeys = new ArrayList<>(unorderedKeys);+ Collections.sort(orderedKeys);+ for (int key : orderedKeys) {+ mElements.put(key, unorderedElements.get(key));+ }+ }++ void setSeqAuth(final int src, final int seqAuth) {+ mSeqAuth.put(src, seqAuth);+ }++ public Integer getSeqAuth(final int src) {+ if (mSeqAuth.size() == 0) {+ return null;+ }++ return mSeqAuth.get(src);+ }++ public boolean isExist(final int modelId) {+ for (Map.Entry<Integer, Element> elementEntry : mElements.entrySet()) {+ final Element element = elementEntry.getValue();+ for (Map.Entry<Integer, MeshModel> modelEntry : element.getMeshModels().entrySet()) {+ final MeshModel model = modelEntry.getValue();+ if (model != null && model.getModelId() == modelId) {+ return true;+ }+ }+ }+ return false;+ }++ /**+ * Increments the sequence number+ */+ public int incrementSequenceNumber() {+ return sequenceNumber = sequenceNumber + 1;+ }+++}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProxyConfigAddAddressToFilter.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProxyConfigAddAddressToFilter.javanew file mode 100644index 000000000..2e3f7c0ce--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProxyConfigAddAddressToFilter.java@@ -0,0 +1,58 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ProxyConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.AddressArray;++import java.util.ArrayList;+import java.util.List;++/**+ * To be used as a wrapper class to create the ProxyConfigSetFilterType message.+ */+public class ProxyConfigAddAddressToFilter extends ProxyConfigMessage {++ private final List<AddressArray> addresses;++ /**+ * Sets the proxy filter+ *+ * @param addresses List of addresses to be added to the filter+ */+ public ProxyConfigAddAddressToFilter(final List<AddressArray> addresses) throws IllegalArgumentException {+ this.addresses = new ArrayList<>();+ this.addresses.addAll(addresses);+ assembleMessageParameters();+ }++ @Override+ void assembleMessageParameters() throws IllegalArgumentException {+ if(addresses.isEmpty())+ throw new IllegalArgumentException("Address list cannot be empty!");+ final int length = (int) Math.pow(2 , addresses.size());+ mParameters = new byte[length];+ int count = 0;+ for (AddressArray addressArray : addresses) {+ mParameters[count] = addressArray.getAddress()[0];+ mParameters[count + 1] = addressArray.getAddress()[1];+ count += 2;+ }+ }++ @Override+ public int getOpCode() {+ return ProxyConfigMessageOpCodes.ADD_ADDRESS;+ }++ @Override+ byte[] getParameters() {+ return mParameters;+ }++ /**+ * Returns the addresses that were added to the proxy filter+ */+ public List<AddressArray> getAddresses(){+ return addresses;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProxyConfigFilterStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProxyConfigFilterStatus.javanew file mode 100644index 000000000..e25b5bc27--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProxyConfigFilterStatus.java@@ -0,0 +1,58 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ProxyConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;+import org.openremote.agent.protocol.bluetooth.mesh.utils.ProxyFilterType;++import java.util.logging.Logger;++/**+ * To be used as a wrapper class to create the ProxyConfigSetFilterType message.+ */+public class ProxyConfigFilterStatus extends ProxyConfigStatusMessage {+ public static final Logger LOG = Logger.getLogger(ProxyConfigFilterStatus.class.getName());+++ private ProxyFilterType mFilterType;+ private int mAddressListSize;++ public ProxyConfigFilterStatus(final ControlMessage controlMessage) {+ super(controlMessage);+ this.mParameters = controlMessage.getParameters();+ parseStatusParameters();+ }++ @Override+ public int getOpCode() {+ return ProxyConfigMessageOpCodes.FILTER_STATUS;+ }++ @Override+ byte[] getParameters() {+ return mParameters;+ }++ @Override+ void parseStatusParameters() {+ mFilterType = new ProxyFilterType(MeshParserUtils.unsignedByteToInt(mParameters[0]));+ //Note proxy protocol is in big endian+ mAddressListSize = MeshParserUtils.unsignedBytesToInt(mParameters[2], mParameters[1]);+ LOG.info("Filter type: " + mFilterType.getFilterTypeName());+ LOG.info("Filter size: " + mAddressListSize);+ }++ /**+ * Returns the {@link ProxyFilterType} set on the proxy+ */+ public ProxyFilterType getFilterType() {+ return mFilterType;+ }++ /**+ * Returns the size of the address list in the proxy filter+ */+ public int getListSize(){+ return mAddressListSize;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProxyConfigMessage.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProxyConfigMessage.javanew file mode 100644index 000000000..76dfe7048--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProxyConfigMessage.java@@ -0,0 +1,31 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++/**+ * Abstract wrapper class for mesh message.+ */+abstract class ProxyConfigMessage extends MeshMessage {++ /**+ * Creates the parameters for a given mesh message.+ */+ abstract void assembleMessageParameters();++ /**+ * Returns the parameters of this message.+ *+ * @return parameters+ */+ abstract byte[] getParameters();+++ @Override+ int getAkf() {+ return -1;+ }++ @Override+ int getAid() {+ return -1;+ }++}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProxyConfigMessageState.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProxyConfigMessageState.javanew file mode 100644index 000000000..871b19804--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProxyConfigMessageState.java@@ -0,0 +1,49 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++/**+ * This generic state class handles the proxy configuration messages received or sent.+ * <p>+ * Each message sent by the library has its own state.+ * </p>+ */+class ProxyConfigMessageState extends MeshMessageState {++ private static final String TAG = ProxyConfigMessageState.class.getSimpleName();++ /**+ * Constructs the ProxyConfigMessageState for sending/receiving proxy configuration messages+ *+ * @param src Source address+ * @param dst Destination address+ * @param meshMessage {@link MeshMessage} Mesh proxy config message+ * @param meshTransport {@link MeshTransport} Mesh transport+ * @param callbacks {@link InternalMeshMsgHandlerCallbacks} Internal callbacks+ */+ ProxyConfigMessageState(final int src,+ final int dst,+ final MeshMessage meshMessage,+ final MeshTransport meshTransport,+ final InternalMeshMsgHandlerCallbacks callbacks) {+ super(meshMessage, meshTransport, callbacks);+ this.mSrc = src;+ this.mDst = dst;+ createControlMessage();+ }++ @Override+ public synchronized MessageState getState() {+ return MessageState.PROXY_CONFIG_MESSAGE_STATE;+ }++ /**+ * Creates the control message to be sent to the node+ */+ private synchronized void createControlMessage() {+ final ProxyConfigMessage proxyConfigMessage = (ProxyConfigMessage) mMeshMessage;+ final int opCode = proxyConfigMessage.getOpCode();+ final byte[] parameters = proxyConfigMessage.getParameters();+ message = mMeshTransport.createProxyConfigurationMessage(mSrc, mDst, opCode, parameters);+ proxyConfigMessage.setMessage(message);+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProxyConfigRemoveAddressFromFilter.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProxyConfigRemoveAddressFromFilter.javanew file mode 100644index 000000000..a0178192d--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProxyConfigRemoveAddressFromFilter.java@@ -0,0 +1,57 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ProxyConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.AddressArray;++import java.util.ArrayList;+import java.util.List;++/**+ * To be used as a wrapper class to create the ProxyConfigSetFilterType message.+ */+public class ProxyConfigRemoveAddressFromFilter extends ProxyConfigMessage {++ private final List<AddressArray> addresses;++ /**+ * Sets the proxy filter+ *+ * @param addresses List of addresses to be added to the filter+ */+ public ProxyConfigRemoveAddressFromFilter(final List<AddressArray> addresses) throws IllegalArgumentException {+ this.addresses = new ArrayList<>();+ this.addresses.addAll(addresses);+ assembleMessageParameters();+ }++ @Override+ void assembleMessageParameters() throws IllegalArgumentException {+ if (addresses.isEmpty())+ throw new IllegalArgumentException("Address list cannot be empty!");+ final int length = (int) Math.pow(2, addresses.size());+ mParameters = new byte[length];+ int count = 0;+ for (AddressArray addressArray : addresses) {+ mParameters[count] = addressArray.getAddress()[0];+ mParameters[count + 1] = addressArray.getAddress()[1];+ count += 2;+ }+ }++ @Override+ public int getOpCode() {+ return ProxyConfigMessageOpCodes.REMOVE_ADDRESS;+ }++ @Override+ byte[] getParameters() {+ return mParameters;+ }++ /**+ * Returns the addresses that were added to the proxy filter+ */+ public List<AddressArray> getAddresses() {+ return addresses;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProxyConfigSetFilterType.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProxyConfigSetFilterType.javanew file mode 100644index 000000000..ba51f5af3--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProxyConfigSetFilterType.java@@ -0,0 +1,38 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ProxyConfigMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.ProxyFilterType;++/**+ * To be used as a wrapper class to create the ProxyConfigSetFilterType message.+ */+@SuppressWarnings({"WeakerAccess"})+public class ProxyConfigSetFilterType extends ProxyConfigMessage {++ private final ProxyFilterType filterType;++ /**+ * Sets the proxy filter+ *+ * @param filterType Filter type set by the proxy configuration+ */+ public ProxyConfigSetFilterType(final ProxyFilterType filterType) {+ this.filterType = filterType;+ assembleMessageParameters();+ }++ @Override+ void assembleMessageParameters() {+ mParameters = new byte[]{(byte) filterType.getType()};+ }++ @Override+ public int getOpCode() {+ return ProxyConfigMessageOpCodes.SET_FILTER_TYPE;+ }++ @Override+ byte[] getParameters() {+ return mParameters;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProxyConfigStatusMessage.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProxyConfigStatusMessage.javanew file mode 100644index 000000000..7acd3fac1--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProxyConfigStatusMessage.java@@ -0,0 +1,27 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++/**+ * Abstract wrapper class for mesh message.+ */+abstract class ProxyConfigStatusMessage extends MeshMessage {++ ProxyConfigStatusMessage(final ControlMessage message) {+ mMessage = message;+ }++ /**+ * Parses the status parameters returned by a status message+ */+ abstract void parseStatusParameters();++ @Override+ int getAid() {+ return -1;+ }++ @Override+ int getAkf() {+ return -1;+ }++}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/PublicationSettings.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/PublicationSettings.javanew file mode 100644index 000000000..9fddb7727--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/PublicationSettings.java@@ -0,0 +1,369 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import java.util.UUID;++import static org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils.RESOLUTION_100_MS;+import static org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils.RESOLUTION_10_M;+import static org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils.RESOLUTION_10_S;+import static org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils.RESOLUTION_1_S;++public class PublicationSettings {++ private static final int DEFAULT_PUBLISH_TTL = 0x7F;+ private static final int DEFAULT_PUBLICATION_STEPS = 0;+ private static final int DEFAULT_PUBLICATION_RESOLUTION = 0b00;+ public static final int MIN_PUBLICATION_RETRANSMIT_COUNT = 0b000;+ public static final int MAX_PUBLICATION_RETRANSMIT_COUNT = 0b111;+ private static final int DEFAULT_PUBLICATION_RETRANSMIT_INTERVAL_STEPS = 0b00000;+ private static final int MAX_PUBLICATION_RETRANSMIT_INTERVAL_STEPS = 0b11111;++ private int publishAddress;+ private UUID labelUUID;+ private int appKeyIndex;+ private boolean credentialFlag;+ private int publishTtl = DEFAULT_PUBLISH_TTL;+ private int publicationSteps = DEFAULT_PUBLICATION_STEPS;+ private int publicationResolution = DEFAULT_PUBLICATION_RESOLUTION;+ private int publishRetransmitCount = MIN_PUBLICATION_RETRANSMIT_COUNT;+ private int publishRetransmitIntervalSteps = DEFAULT_PUBLICATION_RETRANSMIT_INTERVAL_STEPS;++ public PublicationSettings() {+ }++ /**+ * Constructs a PublicationSettings+ *+ * @param publishAddress Address to which the element must publish+ * @param appKeyIndex Index of the application key+ * @param credentialFlag Credentials flag define which credentials to be used, set true to use+ * friendship credentials and false for master credentials. Currently supports only master credentials+ * @param publishRetransmitCount Number of publication retransmits+ * @param publishRetransmitIntervalSteps Publish retransmit interval steps+ */+ public PublicationSettings(final int publishAddress,+ final int appKeyIndex,+ final boolean credentialFlag,+ final int publishRetransmitCount,+ final int publishRetransmitIntervalSteps) {+ this(publishAddress, appKeyIndex, credentialFlag,+ DEFAULT_PUBLISH_TTL,+ DEFAULT_PUBLICATION_STEPS,+ DEFAULT_PUBLICATION_RESOLUTION,+ MIN_PUBLICATION_RETRANSMIT_COUNT,+ DEFAULT_PUBLICATION_RETRANSMIT_INTERVAL_STEPS);+ }++ /**+ * Constructs a PublicationSettings+ *+ * @param publishAddress Address to which the element must publish+ * @param appKeyIndex Index of the application key+ * @param credentialFlag Credentials flag define which credentials to be used, set true to use+ * friendship credentials and false for master credentials. Currently supports only master credentials+ * @param publishTtl Publication ttl+ * @param publicationSteps Publication steps for the publication period+ * @param publicationResolution Publication resolution of the publication period+ * @param publishRetransmitCount Number of publication retransmits+ * @param publishRetransmitIntervalSteps Publish retransmit interval steps+ */+ PublicationSettings(final int publishAddress,+ final int appKeyIndex,+ final boolean credentialFlag,+ final int publishTtl,+ final int publicationSteps,+ final int publicationResolution,+ final int publishRetransmitCount,+ final int publishRetransmitIntervalSteps) {+ this(publishAddress, null, appKeyIndex, credentialFlag, publishTtl,+ publicationSteps, publicationResolution, publishRetransmitCount, publishRetransmitIntervalSteps);+ }++ /**+ * Constructs a PublicationSettings+ *+ * @param publishAddress Address to which the element must publish+ * @param appKeyIndex Index of the application key+ * @param credentialFlag Credentials flag define which credentials to be used, set true to use+ * friendship credentials and false for master credentials. Currently supports only master credentials+ * @param publishTtl Publication ttl+ * @param publicationSteps Publication steps for the publication period+ * @param publicationResolution Publication resolution of the publication period+ * @param publishRetransmitCount Number of publication retransmits+ * @param publishRetransmitIntervalSteps Publish retransmit interval steps+ */+ PublicationSettings(final int publishAddress,+ final UUID labelUUID,+ final int appKeyIndex,+ final boolean credentialFlag,+ final int publishTtl,+ final int publicationSteps,+ final int publicationResolution,+ final int publishRetransmitCount,+ final int publishRetransmitIntervalSteps) {+ this.publishAddress = publishAddress;+ this.labelUUID = labelUUID;+ this.appKeyIndex = appKeyIndex;+ this.credentialFlag = credentialFlag;+ this.publishTtl = publishTtl;+ this.publicationSteps = publicationSteps;+ this.publicationResolution = publicationResolution;+ this.publishRetransmitCount = publishRetransmitCount;+ this.publishRetransmitIntervalSteps = publishRetransmitIntervalSteps;+ }++ /**+ * Returns the publish address, this is the address the model may publish messages when set+ *+ * @return publish address+ */+ public int getPublishAddress() {+ return publishAddress;+ }++ /**+ * Sets a publish address for this model+ *+ * @param publishAddress publish address+ */+ public void setPublishAddress(final int publishAddress) {+ this.publishAddress = publishAddress;+ }++ /**+ * Returns the label uuid for this model+ */+ public UUID getLabelUUID() {+ return labelUUID;+ }++ /**+ * Sets the label uuid for the publication settings of the model+ *+ * @param labelUUID 16-byte label uuid+ */+ void setLabelUUID(final UUID labelUUID) {+ this.labelUUID = labelUUID;+ }++ /**+ * Returns the app key index used for publishing by this model+ *+ * @return Global app key index+ */+ public int getAppKeyIndex() {+ return appKeyIndex;+ }++ /**+ * Set app key index to be used when publishing messages.+ *+ * @param appKeyIndex global application key index+ */+ public void setAppKeyIndex(final int appKeyIndex) {+ this.appKeyIndex = appKeyIndex;+ }++ public boolean getCredentialFlag() {+ return credentialFlag;+ }++ /**+ * Sets the credential flags true if friendship credentials is to be used or false if master credentials flags must be used.+ *+ * @param credentialFlag credential flag+ */+ void setCredentialFlag(final boolean credentialFlag) {+ this.credentialFlag = credentialFlag;+ }++ /**+ * Returns the ttl used for publication.+ *+ * @return publication ttl+ */+ public int getPublishTtl() {+ return publishTtl & 0xFF;+ }++ /**+ * Sets the ttl used for publication.+ */+ void setPublishTtl(final int publishTtl) {+ this.publishTtl = publishTtl;+ }++ /**+ * Returns the retransmit count used in publication+ *+ * @return publication retransmit count+ */+ public int getPublishRetransmitCount() {+ return publishRetransmitCount;+ }++ /**+ * Sets the retransmit count used in publication+ */+ void setPublishRetransmitCount(final int publishRetransmitCount) {+ this.publishRetransmitCount = publishRetransmitCount;+ }++ /**+ * Returns the retransmit interval steps used in publication+ *+ * @return publication retransmit interval steps+ */+ public int getPublishRetransmitIntervalSteps() {+ return publishRetransmitIntervalSteps;+ }++ /**+ * Sets the retransmit interval steps used in publication+ */+ void setPublishRetransmitIntervalSteps(final int publishRetransmitIntervalSteps) {+ this.publishRetransmitIntervalSteps = publishRetransmitIntervalSteps;+ }++ /**+ * Returns the publication steps used for publication+ *+ * @return publication steps+ */+ public int getPublicationSteps() {+ return publicationSteps;+ }++ /**+ * Sets the publication steps used for publication+ */+ void setPublicationSteps(final int publicationSteps) {+ this.publicationSteps = publicationSteps;+ }++ /**+ * Returns the resolution bit-field of publication steps. The resolution can be 100ms, 1 second, 10 seconds or 10 minutes+ *+ * @return resolution+ */+ public int getPublicationResolution() {+ return publicationResolution;+ }++ void setPublicationResolution(final int publicationResolution) {+ this.publicationResolution = publicationResolution;+ }++ /**+ * Encodes the publication period as an interval based on the resolution.+ */+ int serializePublicationResolution() {+ switch (publicationResolution) {+ default:+ case RESOLUTION_100_MS:+ return 100;+ case RESOLUTION_1_S:+ return 1000;+ case RESOLUTION_10_S:+ return 10 * 1000;+ case RESOLUTION_10_M:+ return 10 * 1000 * 60;+ }+ }++ /**+ * Decodes the publication period resolution.+ *+ * @param resolution publication period resolution+ */+ public static int deserializePublicationResolution(final int resolution) {+ switch (resolution) {+ default:+ case 100:+ return RESOLUTION_100_MS;+ case 1000:+ return RESOLUTION_1_S;+ case 10000:+ return RESOLUTION_10_S;+ case 600000:+ return RESOLUTION_10_M;+ }+ }++ /**+ * Returns the publish period in seconds+ */+ public int getPublishPeriod() {+ switch (publicationResolution) {+ default:+ case RESOLUTION_100_MS:+ return ((100 * publicationSteps) / 1000);+ case RESOLUTION_1_S:+ return publicationSteps;+ case RESOLUTION_10_S:+ return (10 * publicationSteps);+ case RESOLUTION_10_M:+ return (10 * publicationSteps) * 60;+ }+ }++ /**+ * Returns the publish period in seconds+ */+ public static int getPublishPeriod(final int publicationResolution, final int publicationSteps) {+ switch (publicationResolution) {+ default:+ case 0b00:+ return 100 * publicationSteps;+ case 0b01:+ return publicationSteps;+ case 0b10:+ return 10 * publicationSteps;+ case 0b11:+ return 10 * publicationSteps * 60;+ }+ }++ /**+ * Returns the retransmission interval in milliseconds+ */+ public int getRetransmissionInterval() {+ return (publishRetransmitIntervalSteps + 1) * 50;+ }++ /**+ * Returns the retransmit interval for a given number of retransmit interval steps in milliseconds+ *+ * @param intervalSteps Retransmit interval steps+ */+ public static int getRetransmissionInterval(final int intervalSteps) {+ if (intervalSteps >= DEFAULT_PUBLICATION_RETRANSMIT_INTERVAL_STEPS && intervalSteps <= MAX_PUBLICATION_RETRANSMIT_INTERVAL_STEPS)+ return (intervalSteps + 1) * 50;+ return 0;+ }++ /**+ * Returns the minimum retransmit interval supported in milliseconds+ */+ public static int getMinRetransmissionInterval() {+ return (DEFAULT_PUBLICATION_RETRANSMIT_INTERVAL_STEPS + 1) * 50;+ }++ /**+ * Returns the maximum retransmit interval supported in milliseconds+ */+ public static int getMaxRetransmissionInterval() {+ return (MAX_PUBLICATION_RETRANSMIT_INTERVAL_STEPS + 1) * 50;+ }++ /**+ * Returns the retransmit interval steps from the retransmit interval+ *+ * @param retransmitInterval Retransmit interval in milliseconds+ */+ public static int parseRetransmitIntervalSteps(final int retransmitInterval) {+ if (retransmitInterval >= 0 && retransmitInterval <= getMaxRetransmissionInterval()) {+ return ((retransmitInterval / 50) - 1);+ }+ throw new IllegalArgumentException("Invalid retransmit interval");+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/SceneDelete.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/SceneDelete.javanew file mode 100644index 000000000..8f9eac9d5--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/SceneDelete.java@@ -0,0 +1,58 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.ApplicationKey;+import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ApplicationMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.SecureUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++import static org.openremote.agent.protocol.bluetooth.mesh.Scene.isValidSceneNumber;++/**+ * To be used as a wrapper class when creating a SceneDelete message.+ */+public class SceneDelete extends GenericMessage {++ public static final Logger LOG = Logger.getLogger(SceneDelete.class.getName());+ private static final int OP_CODE = ApplicationMessageOpCodes.SCENE_DELETE;+ private static final int SCENE_DELETE_PARAMS_LENGTH = 2;++ private int sceneNumber;++ /**+ * Constructs SceneDelete message.+ *+ * @param appKey {@link ApplicationKey} key for this message+ * @param sceneNumber Scene number of SceneDelete message+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public SceneDelete(final ApplicationKey appKey,+ final int sceneNumber) {+ super(appKey);+ if (isValidSceneNumber(sceneNumber))+ this.sceneNumber = sceneNumber;+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ @Override+ void assembleMessageParameters() {+ mAid = SecureUtils.calculateK4(mAppKey.getKey());+ final ByteBuffer paramsBuffer;+ LOG.info("Scene Number: " + sceneNumber);+ paramsBuffer = ByteBuffer.allocate(SCENE_DELETE_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.putShort((short) sceneNumber);+ mParameters = paramsBuffer.array();+ }++ public int getSceneNumber() {+ return sceneNumber;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/SceneRecall.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/SceneRecall.javanew file mode 100644index 000000000..077e2c10c--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/SceneRecall.java@@ -0,0 +1,95 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.ApplicationKey;+import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ApplicationMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.SecureUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++/**+ * To be used as a wrapper class when creating a SceneStore message.+ */+public class SceneRecall extends GenericMessage {++ public static final Logger LOG = Logger.getLogger(SceneRecall.class.getName());+ private static final int OP_CODE = ApplicationMessageOpCodes.SCENE_RECALL;+ private static final int SCENE_RECALL_TRANSITION_PARAMS_LENGTH = 5;+ private static final int SCENE_RECALL_PARAMS_LENGTH = 3;++ private final Integer mTransitionSteps;+ private final Integer mTransitionResolution;+ private final Integer mDelay;+ private final int mSceneNumber;+ private final int tId;++ /**+ * Constructs SceneStore message.+ *+ * @param appKey {@link ApplicationKey} key for this message+ * @param sceneNumber SceneNumber+ * @param tId Transaction Id+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public SceneRecall(final ApplicationKey appKey,+ final int sceneNumber,+ final int tId) throws IllegalArgumentException {+ this(appKey, null, null, null, sceneNumber, tId);+ }++ /**+ * Constructs SceneStore message.+ *+ * @param appKey {@link ApplicationKey} key for this message+ * @param transitionSteps Transition steps for the level+ * @param transitionResolution Transition resolution for the level+ * @param delay Delay for this message to be executed 0 - 1275 milliseconds+ * @param sceneNumber sceneNumber+ * @param tId Transaction Id+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ @SuppressWarnings("WeakerAccess")+ public SceneRecall(final ApplicationKey appKey,+ /* @Nullable */ final Integer transitionSteps,+ /* @Nullable */ final Integer transitionResolution,+ /* @Nullable */ final Integer delay,+ final int sceneNumber,+ final int tId) {+ super(appKey);+ this.mTransitionSteps = transitionSteps;+ this.mTransitionResolution = transitionResolution;+ this.mDelay = delay;+ this.mSceneNumber = sceneNumber;+ this.tId = tId;+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ @Override+ void assembleMessageParameters() {+ mAid = SecureUtils.calculateK4(mAppKey.getKey());+ final ByteBuffer paramsBuffer;+ LOG.info("Scene number: " + mSceneNumber);+ if (mTransitionSteps == null || mTransitionResolution == null || mDelay == null) {+ paramsBuffer = ByteBuffer.allocate(SCENE_RECALL_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.putShort((short) mSceneNumber);+ paramsBuffer.put((byte) tId);+ } else {+ LOG.info("Transition steps: " + mTransitionSteps);+ LOG.info("Transition step resolution: " + mTransitionResolution);+ paramsBuffer = ByteBuffer.allocate(SCENE_RECALL_TRANSITION_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.putShort((short) mSceneNumber);+ paramsBuffer.put((byte) tId);+ paramsBuffer.put((byte) (mTransitionResolution << 6 | mTransitionSteps));+ final int delay = mDelay;+ paramsBuffer.put((byte) delay);+ }+ mParameters = paramsBuffer.array();+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/SceneRegisterStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/SceneRegisterStatus.javanew file mode 100644index 000000000..58c2f249d--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/SceneRegisterStatus.java@@ -0,0 +1,88 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ApplicationMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.ArrayList;+import java.util.logging.Logger;++/**+ * To be used as a wrapper class for when creating the GenericOnOffStatus Message.+ */+public final class SceneRegisterStatus extends GenericStatusMessage implements SceneStatuses {+ private static final int SCENE_REGISTER_STATUS_MANDATORY_LENGTH = 3;+ public static final Logger LOG = Logger.getLogger(SceneRegisterStatus.class.getName());+ private static final int OP_CODE = ApplicationMessageOpCodes.SCENE_REGISTER_STATUS;+ private int mStatus;+ private int mCurrentScene;+ private final ArrayList<Integer> mSceneList = new ArrayList<>();++ /**+ * Constructs the GenericOnOffStatus mMessage.+ *+ * @param message Access Message+ */+ public SceneRegisterStatus(final AccessMessage message) {+ super(message);+ this.mMessage = message;+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ void parseStatusParameters() {+ LOG.info("Received scene register status from: " + MeshAddress.formatAddress(mMessage.getSrc(), true));+ final ByteBuffer buffer = ByteBuffer.wrap(mParameters).order(ByteOrder.LITTLE_ENDIAN);+ buffer.position(0);+ mStatus = buffer.get() & 0xFF;+ mCurrentScene = buffer.getShort() & 0xFFFF;+ LOG.info("Status: " + mStatus);+ LOG.info("Current Scene: " + mCurrentScene);+ if (buffer.limit() > SCENE_REGISTER_STATUS_MANDATORY_LENGTH) {+ int sceneCount = (buffer.limit() - SCENE_REGISTER_STATUS_MANDATORY_LENGTH) / 2;+ for (int i = 0; i < sceneCount; i++) {+ mSceneList.add(buffer.getShort() & 0xFFFF);+ }+ LOG.info("Scenes stored: " + sceneCount);+ }+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ /**+ * Returns the present state of the GenericOnOffModel+ *+ * @return true if on and false other wise+ */+ public final int getStatus() {+ return mStatus;+ }++ public boolean isSuccessful() {+ return mStatus == 0x00;+ }++ /**+ * Returns the target state of the GenericOnOffModel+ *+ * @return true if on and false other wise+ */+ public final int getCurrentScene() {+ return mCurrentScene;+ }++ /**+ * Returns the scene list.+ *+ * @return scene list+ */+ public ArrayList<Integer> getSceneList() {+ return mSceneList;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/SceneStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/SceneStatus.javanew file mode 100644index 000000000..16b95c2cf--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/SceneStatus.java@@ -0,0 +1,118 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import static org.openremote.agent.protocol.bluetooth.mesh.opcodes.ApplicationMessageOpCodes.SCENE_STATUS;++/**+ * To be used as a wrapper class for when creating the GenericOnOffStatus Message.+ */+public final class SceneStatus extends GenericStatusMessage implements SceneStatuses {+ private static final int SCENE_STATUS_MANDATORY_LENGTH = 3;+ private static final String TAG = SceneStatus.class.getSimpleName();+ private static final int OP_CODE = SCENE_STATUS;+ private int mStatusCode;+ private int mCurrentScene;+ private int mTargetScene;+ private int mRemainingTime;+ private int mTransitionSteps;+ private int mTransitionResolution;++ public static final Logger LOG = Logger.getLogger(SceneStatus.class.getName());++ /**+ * Constructs the GenericOnOffStatus mMessage.+ *+ * @param message Access Message+ */+ public SceneStatus(final AccessMessage message) {+ super(message);+ this.mMessage = message;+ this.mParameters = message.getParameters();+ parseStatusParameters();+ }++ @Override+ void parseStatusParameters() {+ LOG.info("Received scene status from: " + MeshAddress.formatAddress(mMessage.getSrc(), true));+ final ByteBuffer buffer = ByteBuffer.wrap(mParameters).order(ByteOrder.LITTLE_ENDIAN);+ buffer.position(0);+ mStatusCode = buffer.get() & 0xFF;+ mCurrentScene = buffer.getShort() & 0xFFFF;+ LOG.info("Status: " + mStatusCode);+ LOG.info("Current Scene : " + mCurrentScene);+ if (buffer.limit() > SCENE_STATUS_MANDATORY_LENGTH) {+ mTargetScene = buffer.getShort() & 0xFFFF;+ mRemainingTime = buffer.get() & 0xFF;+ mTransitionSteps = (mRemainingTime & 0x3F);+ mTransitionResolution = (mRemainingTime >> 6);+ LOG.info("Target scene: " + mTargetScene);+ LOG.info("Remaining time, transition number of steps: " + mTransitionSteps);+ LOG.info("Remaining time, transition number of step resolution: " + mTransitionResolution);+ LOG.info("Remaining time: " + MeshParserUtils.getRemainingTime(mRemainingTime));+ }+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ /**+ * Returns the present state of the GenericOnOffModel+ *+ * @return true if on and false other wise+ */+ public final int getStatus() {+ return mStatusCode;+ }++ /**+ * Returns true if the message was successful.+ */+ public final boolean isSuccessful() {+ return mStatusCode == 0;+ }++ /**+ * Returns the target state of the GenericOnOffModel+ *+ * @return true if on and false other wise+ */+ public final int getCurrentScene() {+ return mCurrentScene;+ }++ /**+ * Returns the target state of the GenericOnOffModel+ *+ * @return true if on and false other wise+ */+ public final Integer getTargetScene() {+ return mTargetScene;+ }++ /**+ * Returns the transition steps.+ *+ * @return transition steps+ */+ public int getTransitionSteps() {+ return mTransitionSteps;+ }++ /**+ * Returns the transition resolution.+ *+ * @return transition resolution+ */+ public int getTransitionResolution() {+ return mTransitionResolution;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/SceneStatuses.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/SceneStatuses.javanew file mode 100644index 000000000..17d740d08--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/SceneStatuses.java@@ -0,0 +1,18 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++interface SceneStatuses {++ default String getStatusMessage(final int status) {+ switch (status) {+ case 0x00:+ return "Success.";+ case 0x01:+ return "Scene Register Full.";+ case 0x02:+ return "Scene Not Found.";+ default:+ return "Reserved for Future Use";++ }+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/SceneStore.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/SceneStore.javanew file mode 100644index 000000000..4a21f2b84--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/SceneStore.java@@ -0,0 +1,54 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.ApplicationKey;+import org.openremote.agent.protocol.bluetooth.mesh.opcodes.ApplicationMessageOpCodes;+import org.openremote.agent.protocol.bluetooth.mesh.utils.SecureUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Logger;++import static org.openremote.agent.protocol.bluetooth.mesh.Scene.isValidSceneNumber;++/**+ * To be used as a wrapper class when creating a SceneStore message.+ */+public class SceneStore extends GenericMessage {++ public static final Logger LOG = Logger.getLogger(SceneStore.class.getName());+ private static final int OP_CODE = ApplicationMessageOpCodes.SCENE_STORE;+ private static final int SCENE_STORE_PARAMS_LENGTH = 2;++ private int mSceneNumber;++ /**+ * Constructs SceneStore message.+ *+ * @param appKey Application key for this message+ * @param sceneNumber Scene number of SceneStore message+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public SceneStore(final ApplicationKey appKey,+ final int sceneNumber) {+ super(appKey);+ if (isValidSceneNumber(sceneNumber))+ this.mSceneNumber = sceneNumber;+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return OP_CODE;+ }++ @Override+ void assembleMessageParameters() {+ mAid = SecureUtils.calculateK4(mAppKey.getKey());+ final ByteBuffer paramsBuffer;+ LOG.info("Scene Number: " + mSceneNumber);+ paramsBuffer = ByteBuffer.allocate(SCENE_STORE_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);+ paramsBuffer.putShort((short) mSceneNumber);+ mParameters = paramsBuffer.array();+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/UpperTransportLayer.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/UpperTransportLayer.javanew file mode 100644index 000000000..fd969e5fd--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/UpperTransportLayer.java@@ -0,0 +1,381 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.bouncycastle.crypto.InvalidCipherTextException;++import org.openremote.agent.protocol.bluetooth.mesh.ApplicationKey;+import org.openremote.agent.protocol.bluetooth.mesh.Group;+import org.openremote.agent.protocol.bluetooth.mesh.MeshManagerApi;+import org.openremote.agent.protocol.bluetooth.mesh.utils.ExtendedInvalidCipherTextException;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;+import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;+import org.openremote.agent.protocol.bluetooth.mesh.utils.SecureUtils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.List;+import java.util.logging.Logger;++/**+ * UpperTransportLayer implementation of the mesh network architecture as per the mesh profile specification.+ * <p>+ * UpperTransportLayer class encrypts/decrypts Access PDUs created in the access layer.+ * </p>+ */+public abstract class UpperTransportLayer extends AccessLayer{++ public static final Logger LOG = Logger.getLogger(UpperTransportLayer.class.getName());++ private static final int PROXY_CONFIG_OPCODE_LENGTH = 1;+ static final int MAX_SEGMENTED_ACCESS_PAYLOAD_LENGTH = 12;+ public static final int MAX_UNSEGMENTED_CONTROL_PAYLOAD_LENGTH = 11;+ public static final int MAX_SEGMENTED_CONTROL_PAYLOAD_LENGTH = 8;++ //Nonce types+ public static final int NONCE_TYPE_NETWORK = 0x00;+ public static final int NONCE_TYPE_PROXY = 0x03;++ //Nonce paddings+ public static final int PAD_NETWORK_NONCE = 0x00;+ public static final int PAD_PROXY_NONCE = 0x00;+ public static final int APPLICATION_KEY_IDENTIFIER = 0; //Identifies that the device key is to be used+ private static final int MAX_UNSEGMENTED_ACCESS_PAYLOAD_LENGTH = 15;+ private static final int NONCE_TYPE_APPLICATION = 0x01;+ private static final int NONCE_TYPE_DEVICE = 0x02;+ private static final int PAD_APPLICATION_DEVICE_NONCE = 0b0000000;+ private static final int SZMIC = 1; //Transmic becomes 8 bytes+ private static final int TRANSPORT_SAR_SEQZERO_MASK = 8191;+ private static final int DEFAULT_UNSEGMENTED_MIC_LENGTH = 4; //octets+ private static final int MINIMUM_TRANSMIC_LENGTH = 4; // bytes+ private static final int MAXIMUM_TRANSMIC_LENGTH = 8; // bytes++ UpperTransportLayerCallbacks mUpperTransportLayerCallbacks;++ /**+ * Creates lower transport pdu+ */+ abstract void createLowerTransportAccessPDU(final AccessMessage message);++ /**+ * Creates lower transport pdu+ */+ abstract void createLowerTransportControlPDU(final ControlMessage message);++ /**+ * Removes the lower transport layer header and reassembles a segented lower transport access pdu in to one message+ *+ * @param accessMessage access message containing the lower transport pdus+ */+ abstract void reassembleLowerTransportAccessPDU(final AccessMessage accessMessage);++ /**+ * Removes the lower transport layer header and reassembles a segented lower transport control pdu in to one message+ *+ * @param controlMessage control message containing the lower transport pdus+ */+ abstract void reassembleLowerTransportControlPDU(final ControlMessage controlMessage);++ /**+ * Sets the upper transport layer callbacks+ *+ * @param callbacks {@link UpperTransportLayerCallbacks} callbacks+ */+ abstract void setUpperTransportLayerCallbacks(final UpperTransportLayerCallbacks callbacks);++ /**+ * Creates a mesh message containing an upper transport access pdu+ *+ * @param message The access message required to create the encrypted upper transport pdu+ */+ synchronized void createMeshMessage(final Message message) { //Access message+ if (message instanceof AccessMessage) {+ super.createMeshMessage(message);+ final AccessMessage accessMessage = (AccessMessage) message;+ final byte[] encryptedTransportPDU = encryptUpperTransportPDU(accessMessage);+ LOG.info("Encrypted upper transport pdu: " + MeshParserUtils.bytesToHex(encryptedTransportPDU, false));+ accessMessage.setUpperTransportPdu(encryptedTransportPDU);+ } else {+ createUpperTransportPDU(message);+ }+ }++ /**+ * Creates a vendor model mesh message containing an upper transport access pdu+ *+ * @param message The access message required to create the encrypted upper transport pdu+ */+ synchronized void createVendorMeshMessage(final Message message) { //Access message+ super.createVendorMeshMessage(message);+ final AccessMessage accessMessage = (AccessMessage) message;+ final byte[] encryptedTransportPDU = encryptUpperTransportPDU(accessMessage);+ LOG.info("Encrypted upper transport pdu: " + MeshParserUtils.bytesToHex(encryptedTransportPDU, false));+ accessMessage.setUpperTransportPdu(encryptedTransportPDU);+ }++ /**+ * Creates the upper transport access pdu+ *+ * @param message The message required to create the encrypted upper transport pdu+ */+ synchronized void createUpperTransportPDU(final Message message) {+ if (message instanceof AccessMessage) {+ //Access message+ final AccessMessage accessMessage = (AccessMessage) message;+ final byte[] encryptedTransportPDU = encryptUpperTransportPDU(accessMessage);+ LOG.info("Encrypted upper transport pdu: " + MeshParserUtils.bytesToHex(encryptedTransportPDU, false));+ accessMessage.setUpperTransportPdu(encryptedTransportPDU);+ } else {+ final ControlMessage controlMessage = (ControlMessage) message;+ final int opCode = controlMessage.getOpCode();+ final byte[] parameters = controlMessage.getParameters();+ final ByteBuffer accessMessageBuffer;+ if (parameters != null) {+ accessMessageBuffer = ByteBuffer.allocate(PROXY_CONFIG_OPCODE_LENGTH + parameters.length)+ .order(ByteOrder.BIG_ENDIAN)+ .put((byte) opCode)+ .put(parameters);+ } else {+ accessMessageBuffer = ByteBuffer.allocate(PROXY_CONFIG_OPCODE_LENGTH);+ accessMessageBuffer.put((byte) opCode);+ }+ final byte[] accessPdu = accessMessageBuffer.array();++ LOG.info("Created Transport Control PDU " + MeshParserUtils.bytesToHex(accessPdu, false));+ controlMessage.setTransportControlPdu(accessPdu);+ }+ }++ /**+ * Parse upper transport pdu+ *+ * @param message access message containing the upper transport pdu+ */+ synchronized final void parseUpperTransportPDU(final Message message) throws ExtendedInvalidCipherTextException {+ try {+ switch (message.getPduType()) {+ case MeshManagerApi.PDU_TYPE_NETWORK:+ if (message instanceof AccessMessage) { //Access message+ final AccessMessage accessMessage = (AccessMessage) message;+ reassembleLowerTransportAccessPDU(accessMessage);+ final byte[] decryptedUpperTransportControlPdu = decryptUpperTransportPDU(accessMessage);+ accessMessage.setAccessPdu(decryptedUpperTransportControlPdu);+ } else {+ //TODO+ //this where control messages such as heartbeat and friendship messages are to be implemented+ }+ break;+ case MeshManagerApi.PDU_TYPE_PROXY_CONFIGURATION:+ final ControlMessage controlMessage = (ControlMessage) message;+ if (controlMessage.getLowerTransportControlPdu().size() == 1) {+ final byte[] lowerTransportControlPdu = controlMessage.getLowerTransportControlPdu().get(0);+ final ByteBuffer buffer = ByteBuffer.wrap(lowerTransportControlPdu)+ .order(ByteOrder.BIG_ENDIAN);+ message.setOpCode(buffer.get());+ final byte[] parameters = new byte[buffer.capacity() - 1];+ buffer.get(parameters);+ message.setParameters(parameters);+ }+ break;+ }+ } catch (InvalidCipherTextException ex) {+ throw new ExtendedInvalidCipherTextException(ex.getMessage(), ex.getCause(), UpperTransportLayer.class.getSimpleName());+ }+ }++ /**+ * Encrypts upper transport pdu+ *+ * @param message access message object containing the upper transport pdu+ * @return encrypted upper transport pdu+ */+ private byte[] encryptUpperTransportPDU(final AccessMessage message) {+ final byte[] accessPDU = message.getAccessPdu();+ final int akf = message.getAkf();+ final int aszmic = message.getAszmic(); // upper transport layer will always have the aszmic as 0 because the mic is always 32bit++ final byte[] sequenceNumber = message.getSequenceNumber();+ final int src = message.getSrc();+ final int dst = message.getDst();+ final byte[] ivIndex = message.getIvIndex();+ final byte[] key;++ byte[] nonce;+ if (akf == APPLICATION_KEY_IDENTIFIER) {+ key = message.getDeviceKey();+ nonce = createDeviceNonce(aszmic, sequenceNumber, src, dst, ivIndex);+ LOG.info("Device nonce: " + MeshParserUtils.bytesToHex(nonce, false));+ } else {+ key = message.getApplicationKey().getKey();+ nonce = createApplicationNonce(aszmic, sequenceNumber, src, dst, ivIndex);+ LOG.info("Application nonce: " + MeshParserUtils.bytesToHex(nonce, false));+ }++ int transMicLength;+ final int encryptedPduLength = accessPDU.length + MINIMUM_TRANSMIC_LENGTH;++ if (encryptedPduLength <= MAX_UNSEGMENTED_ACCESS_PAYLOAD_LENGTH) {+ transMicLength = SecureUtils.getTransMicLength(message.getCtl());+ } else {+ transMicLength = SecureUtils.getTransMicLength(message.getAszmic());+ }+ if (MeshAddress.isValidVirtualAddress(dst)) {+ return SecureUtils.encryptCCM(accessPDU, key, nonce, MeshParserUtils.uuidToBytes(message.getLabel()), transMicLength);+ } else {+ return SecureUtils.encryptCCM(accessPDU, key, nonce, transMicLength);+ }+ }++ /**+ * Returns the decrypted upper transport pdu+ *+ * @param accessMessage Access message object containing the upper transport pdu+ */+ private byte[] decryptUpperTransportPDU(final AccessMessage accessMessage) throws InvalidCipherTextException {+ byte[] decryptedUpperTransportPDU;+ byte[] key;+ final int transportMicLength = accessMessage.getAszmic() == SZMIC ? MAXIMUM_TRANSMIC_LENGTH : MINIMUM_TRANSMIC_LENGTH;+ //Check if the key used for encryption is an application key or a device key+ final byte[] nonce;+ if (APPLICATION_KEY_IDENTIFIER == accessMessage.getAkf()) {+ key = mMeshNode.getDeviceKey();+ //If its a device key that was used to encrypt the message we need to create a device nonce to decrypt it+ nonce = createDeviceNonce(accessMessage.getAszmic(), accessMessage.getSequenceNumber(), accessMessage.getSrc(), accessMessage.getDst(), accessMessage.getIvIndex());+ decryptedUpperTransportPDU = SecureUtils.decryptCCM(accessMessage.getUpperTransportPdu(), key, nonce, transportMicLength);+ } else {+ final List<ApplicationKey> keys = mUpperTransportLayerCallbacks.getApplicationKeys(accessMessage.getNetworkKey().getKeyIndex());+ if (keys.isEmpty())+ throw new IllegalArgumentException("Unable to find the app key to decrypt the message");++ nonce = createApplicationNonce(accessMessage.getAszmic(), accessMessage.getSequenceNumber(), accessMessage.getSrc(),+ accessMessage.getDst(), accessMessage.getIvIndex());++ if (MeshAddress.isValidVirtualAddress(accessMessage.getDst())) {+ decryptedUpperTransportPDU = decrypt(accessMessage, mUpperTransportLayerCallbacks.gerVirtualGroups(), keys, nonce, transportMicLength);+ } else {+ decryptedUpperTransportPDU = decrypt(accessMessage, keys, nonce, transportMicLength);+ }+ }++ if (decryptedUpperTransportPDU == null)+ throw new IllegalArgumentException("Unable to decrypt the message, invalid application key identifier!");++ final byte[] tempBytes = new byte[decryptedUpperTransportPDU.length];+ ByteBuffer decryptedBuffer = ByteBuffer.wrap(tempBytes);+ decryptedBuffer.order(ByteOrder.LITTLE_ENDIAN);+ decryptedBuffer.put(decryptedUpperTransportPDU);+ decryptedUpperTransportPDU = decryptedBuffer.array();+ return decryptedUpperTransportPDU;+ }++ private byte[] decrypt(final AccessMessage accessMessage, final List<Group> groups, List<ApplicationKey> keys, final byte[] nonce, final int transportMicLength) {+ for (ApplicationKey key : keys) {+ for (Group group : groups) {+ if(group.getAddressLabel() != null) {+ if (key.getAid() == accessMessage.getAid()) {+ try {+ return SecureUtils+ .decryptCCM(accessMessage.getUpperTransportPdu(), key.getKey(), nonce, MeshParserUtils.uuidToBytes(group.getAddressLabel()), transportMicLength);+ } catch (Exception ex) {+ // Retrying decryption+ }+ }+ if (key.getOldAid() == accessMessage.getAid()) {++ try {+ return SecureUtils+ .decryptCCM(accessMessage.getUpperTransportPdu(), key.getOldKey(), nonce, MeshParserUtils.uuidToBytes(group.getAddressLabel()), transportMicLength);+ } catch (Exception ex) {+ // Retrying decryption+ }+ }+ }+ }+ }+ return null;+ }++ private byte[] decrypt(final AccessMessage accessMessage, List<ApplicationKey> keys, final byte[] nonce, final int transportMicLength) {+ for (ApplicationKey key : keys) {+ if (key.getAid() == accessMessage.getAid()) {+ try {+ return SecureUtils+ .decryptCCM(accessMessage.getUpperTransportPdu(), key.getKey(), nonce, transportMicLength);+ } catch (Exception ex) {+ // Retrying decryption.+ }++ }+ if (key.getOldAid() == accessMessage.getAid()) {+ try {+ return SecureUtils+ .decryptCCM(accessMessage.getUpperTransportPdu(), key.getKey(), nonce, transportMicLength);+ } catch (Exception ex) {+ // Retrying decryption.+ }+ }+ }+ return null;+ }++ /**+ * Creates the application nonce+ *+ * @param aszmic aszmic (szmic if a segmented access message)+ * @param sequenceNumber sequence number of the message+ * @param src source address+ * @param dst destination address+ * @return Application nonce+ */+ private byte[] createApplicationNonce(final int aszmic,+ final byte[] sequenceNumber,+ final int src,+ final int dst,+ final byte[] ivIndex) {+ final ByteBuffer applicationNonceBuffer = ByteBuffer.allocate(13);+ applicationNonceBuffer.put((byte) NONCE_TYPE_APPLICATION); //Nonce type+ applicationNonceBuffer.put((byte) ((aszmic << 7) | PAD_APPLICATION_DEVICE_NONCE)); //ASZMIC (SZMIC if a segmented access message) and PAD+ applicationNonceBuffer.put(sequenceNumber);+ applicationNonceBuffer.putShort((short) src);+ applicationNonceBuffer.putShort((short) dst);+ applicationNonceBuffer.put(ivIndex);+ return applicationNonceBuffer.array();+ }++ /**+ * Creates the device nonce+ *+ * @param aszmic aszmic (szmic if a segmented access message)+ * @param sequenceNumber sequence number of the message+ * @param src source address+ * @param dst destination address+ * @return Device nonce+ */+ private byte[] createDeviceNonce(final int aszmic,+ final byte[] sequenceNumber,+ final int src,+ final int dst,+ final byte[] ivIndex) {+ final ByteBuffer deviceNonceBuffer = ByteBuffer.allocate(13);+ deviceNonceBuffer.put((byte) NONCE_TYPE_DEVICE); //Nonce type+ deviceNonceBuffer.put((byte) ((aszmic << 7) | PAD_APPLICATION_DEVICE_NONCE)); //ASZMIC (SZMIC if a segmented access message) and PAD+ deviceNonceBuffer.put(sequenceNumber);+ deviceNonceBuffer.putShort((short) src);+ deviceNonceBuffer.putShort((short) dst);+ deviceNonceBuffer.put(ivIndex);+ return deviceNonceBuffer.array();+ }++ /**+ * Derives the original transport layer sequence number from the network layer sequence number that was received with every segment+ *+ * @param networkLayerSequenceNumber sequence number on network layer which is a part of the original pdu received+ * @param seqZero the lower 13 bits of the sequence number. This is a part of the lower transport pdu header and is the same value for all segments+ * @return original transport layer sequence number that was used to encrypt the transport layer pdu+ */+ final int getTransportLayerSequenceNumber(final int networkLayerSequenceNumber, final int seqZero) {+ if ((networkLayerSequenceNumber & TRANSPORT_SAR_SEQZERO_MASK) < seqZero) {+ return ((networkLayerSequenceNumber - ((networkLayerSequenceNumber & TRANSPORT_SAR_SEQZERO_MASK) - seqZero) - (TRANSPORT_SAR_SEQZERO_MASK + 1)));+ } else {+ return ((networkLayerSequenceNumber - ((networkLayerSequenceNumber & TRANSPORT_SAR_SEQZERO_MASK) - seqZero)));+ }+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/UpperTransportLayerCallbacks.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/UpperTransportLayerCallbacks.javanew file mode 100644index 000000000..4a601be05--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/UpperTransportLayerCallbacks.java@@ -0,0 +1,44 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.ApplicationKey;+import org.openremote.agent.protocol.bluetooth.mesh.Group;++import java.util.List;++/**+ * Upper transport layer call backs+ */+public interface UpperTransportLayerCallbacks {+++ /**+ * Callback to get the mesh node from the list of provisioned mesh node.+ *+ * @param unicastAddress unicast address of the mesh node+ */+ ProvisionedMeshNode getNode(final int unicastAddress);++ /**+ * Returns the IV Index of the mesh network+ */+ byte[] getIvIndex();++ /**+ * Returns the application key with the specific application key identifier+ *+ * @param aid application key identifier+ */+ byte[] getApplicationKey(final int aid);++ /**+ * Returns a list of Application Keys matching the bound net key index and AID.+ *+ * @param boundNetKeyIndex Index of the bound network key.+ */+ List<ApplicationKey> getApplicationKeys(final int boundNetKeyIndex);++ /**+ * Returns the list of groups+ */+ List<Group> gerVirtualGroups();+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/VendorModelMessageAcked.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/VendorModelMessageAcked.javanew file mode 100644index 000000000..90e650867--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/VendorModelMessageAcked.java@@ -0,0 +1,67 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.ApplicationKey;+import org.openremote.agent.protocol.bluetooth.mesh.utils.SecureUtils;++import java.util.logging.Logger;++/**+ * To be used as a wrapper class when creating an acknowledged VendorMode message.+ */+public class VendorModelMessageAcked extends GenericMessage {++ public static final Logger LOG = Logger.getLogger(VendorModelMessageAcked.class.getName());+ private static final int VENDOR_MODEL_OPCODE_LENGTH = 4;++ private final int mModelIdentifier;+ private final int mCompanyIdentifier;+ private final int mOpCode;++ /**+ * Constructs VendorModelMessageAcked message.+ *+ * @param appKey {@link ApplicationKey} for this message+ * @param modelId 32-bit Model identifier+ * @param companyIdentifier 16-bit Company identifier of the vendor model+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public VendorModelMessageAcked(final ApplicationKey appKey,+ final int modelId,+ final int companyIdentifier,+ final int opCode,+ final byte[] parameters) {+ super(appKey);+ this.mModelIdentifier = modelId;+ this.mCompanyIdentifier = companyIdentifier;+ this.mOpCode = opCode;+ mParameters = parameters;+ assembleMessageParameters();+ }++ @Override+ public int getOpCode() {+ return mOpCode;+ }++ @Override+ void assembleMessageParameters() {+ mAid = SecureUtils.calculateK4(mAppKey.getKey());+ }+++ /**+ * Returns the company identifier of the model+ *+ * @return 16-bit company identifier+ */+ public final int getCompanyIdentifier() {+ return mCompanyIdentifier;+ }++ /**+ * Returns the model identifier for this message+ */+ public int getModelIdentifier() {+ return mModelIdentifier;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/VendorModelMessageAckedState.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/VendorModelMessageAckedState.javanew file mode 100644index 000000000..bf3442059--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/VendorModelMessageAckedState.java@@ -0,0 +1,78 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.ApplicationKey;++import java.util.UUID;+import java.util.logging.Logger;++/**+ * State class for handling VendorModelMessageAckedState messages.+ */+class VendorModelMessageAckedState extends GenericMessageState {++ public static final Logger LOG = Logger.getLogger(VendorModelMessageAckedState.class.getName());++ /**+ * Constructs {@link VendorModelMessageAckedState}+ *+ * @param src Source address+ * @param dst Destination address to which the message must be sent to+ * @param vendorModelMessageAcked Wrapper class {@link VendorModelMessageStatus} containing the+ * opcode and parameters for {@link VendorModelMessageStatus} message+ * @param callbacks {@link InternalMeshMsgHandlerCallbacks} for internal callbacks+ * @throws IllegalArgumentException exception for invalid arguments+ */+ VendorModelMessageAckedState(final int src,+ final int dst,+ final VendorModelMessageAcked vendorModelMessageAcked,+ final MeshTransport meshTransport,+ final InternalMeshMsgHandlerCallbacks callbacks) throws IllegalArgumentException {+ this(src, dst, null, vendorModelMessageAcked, meshTransport, callbacks);+ }++ /**+ * Constructs {@link VendorModelMessageAckedState}+ *+ * @param src Source address+ * @param dst Destination address to which the message must be sent to+ * @param label Label UUID of destination address+ * @param vendorModelMessageAcked Wrapper class {@link VendorModelMessageStatus} containing the+ * opcode and parameters for {@link VendorModelMessageStatus} message+ * @param callbacks {@link InternalMeshMsgHandlerCallbacks} for internal callbacks+ * @throws IllegalArgumentException exception for invalid arguments+ */+ VendorModelMessageAckedState(final int src,+ final int dst,+ /* @Nullable */ UUID label,+ final VendorModelMessageAcked vendorModelMessageAcked,+ final MeshTransport meshTransport,+ final InternalMeshMsgHandlerCallbacks callbacks) throws IllegalArgumentException {+ super(src, dst, label, vendorModelMessageAcked, meshTransport, callbacks);+ }++ @Override+ public synchronized MessageState getState() {+ return MessageState.VENDOR_MODEL_ACKNOWLEDGED_STATE;+ }++ @Override+ protected synchronized final void createAccessMessage() {+ final VendorModelMessageAcked message = (VendorModelMessageAcked) mMeshMessage;+ final ApplicationKey key = message.getAppKey();+ final int akf = message.getAkf();+ final int aid = message.getAid();+ final int aszmic = message.getAszmic();+ final int opCode = message.getOpCode();+ final byte[] parameters = message.getParameters();+ final int companyIdentifier = message.getCompanyIdentifier();+ this.message = mMeshTransport.createVendorMeshMessage(companyIdentifier, mSrc, mDst, mLabel,+ message.messageTtl, key, akf, aid, aszmic, opCode, parameters);+ message.setMessage(this.message);+ }++ @Override+ public synchronized void executeSend() {+ LOG.info("Sending acknowledged vendor model message");+ super.executeSend();+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/VendorModelMessageStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/VendorModelMessageStatus.javanew file mode 100644index 000000000..3345f0aa4--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/VendorModelMessageStatus.java@@ -0,0 +1,49 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;++import java.util.logging.Logger;++/**+ * To be used as a wrapper class for when creating the VendorModelMessageStatus Message.+ */+public final class VendorModelMessageStatus extends GenericStatusMessage {++ public static final Logger LOG = Logger.getLogger(VendorModelMessageStatus.class.getName());+ private final int mModelIdentifier;++ /**+ * Constructs the VendorModelMessageStatus mMessage.+ *+ * @param message Access Message+ * @param modelIdentifier model identifier+ */+ public VendorModelMessageStatus(final AccessMessage message, final int modelIdentifier) {+ super(message);+ this.mParameters = message.getParameters();+ this.mModelIdentifier = modelIdentifier;+ parseStatusParameters();+ }++ @Override+ void parseStatusParameters() {+ LOG.info("Received Vendor model status: " + MeshParserUtils.bytesToHex(mParameters, false));+ }++ @Override+ public int getOpCode() {+ return mMessage.getOpCode();+ }++ public final byte[] getAccessPayload() {+ return ((AccessMessage) mMessage).getAccessPdu();+ }++ /**+ * Returns the model identifier of model the for this message+ */+ public int getModelIdentifier() {+ return mModelIdentifier;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/VendorModelMessageUnacked.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/VendorModelMessageUnacked.javanew file mode 100644index 000000000..d3f2d2e18--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/VendorModelMessageUnacked.java@@ -0,0 +1,65 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.ApplicationKey;+import org.openremote.agent.protocol.bluetooth.mesh.utils.SecureUtils;++import java.util.logging.Logger;++/**+ * To be used as a wrapper class when creating a unacknowledged VendorModel message.+ */+public class VendorModelMessageUnacked extends GenericMessage {++ public static final Logger LOG = Logger.getLogger(VendorModelMessageUnacked.class.getName());++ private final int mModelIdentifier;+ private final int mCompanyIdentifier;+ private final int mOpCode;++ /**+ * Constructs VendorModelMessageAcked message.+ *+ * @param appKey {@link ApplicationKey} for this message+ * @param modelId model identifier+ * @param companyIdentifier Company identifier of the vendor model+ * @throws IllegalArgumentException if any illegal arguments are passed+ */+ public VendorModelMessageUnacked(final ApplicationKey appKey,+ final int modelId,+ final int companyIdentifier,+ final int mOpCode,+ /* @Nullable */ final byte[] parameters) {+ super(appKey);+ this.mModelIdentifier = modelId;+ this.mCompanyIdentifier = companyIdentifier;+ this.mOpCode = mOpCode;+ mParameters = parameters;+ assembleMessageParameters();+ }++ @Override+ final void assembleMessageParameters() {+ mAid = SecureUtils.calculateK4(mAppKey.getKey());+ }++ @Override+ public int getOpCode() {+ return mOpCode;+ }++ /**+ * Returns the company identifier of the model+ *+ * @return 16-bit company identifier+ */+ public final int getCompanyIdentifier() {+ return mCompanyIdentifier;+ }++ /**+ * Returns the model identifier for this message+ */+ public int getModelIdentifier() {+ return mModelIdentifier;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/VendorModelMessageUnackedState.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/VendorModelMessageUnackedState.javanew file mode 100644index 000000000..5e13d07b4--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/VendorModelMessageUnackedState.java@@ -0,0 +1,76 @@+package org.openremote.agent.protocol.bluetooth.mesh.transport;++import org.openremote.agent.protocol.bluetooth.mesh.ApplicationKey;++import java.util.UUID;+import java.util.logging.Logger;++class VendorModelMessageUnackedState extends GenericMessageState {++ public static final Logger LOG = Logger.getLogger(VendorModelMessageUnackedState.class.getName());++ /**+ * Constructs {@link VendorModelMessageAckedState}+ *+ * @param src Source address+ * @param dst Destination address to which the message must be sent to+ * @param vendorModelMessageUnacked Wrapper class {@link VendorModelMessageStatus} containing the+ * opcode and parameters for {@link VendorModelMessageStatus} message+ * @param callbacks {@link InternalMeshMsgHandlerCallbacks} for internal callbacks+ * @throws IllegalArgumentException exception for invalid arguments+ */+ VendorModelMessageUnackedState(final int src,+ final int dst,+ final VendorModelMessageUnacked vendorModelMessageUnacked,+ final MeshTransport meshTransport,+ final InternalMeshMsgHandlerCallbacks callbacks) throws IllegalArgumentException {+ this(src, dst, null, vendorModelMessageUnacked, meshTransport, callbacks);+ }++ /**+ * Constructs {@link VendorModelMessageAckedState}+ *+ * @param src Source address+ * @param dst Destination address to which the message must be sent to+ * @param label Label UUID of destination address+ * @param vendorModelMessageUnacked Wrapper class {@link VendorModelMessageStatus} containing the+ * opcode and parameters for {@link VendorModelMessageStatus} message+ * @param callbacks {@link InternalMeshMsgHandlerCallbacks} for internal callbacks+ * @throws IllegalArgumentException exception for invalid arguments+ */+ VendorModelMessageUnackedState(final int src,+ final int dst,+ /* @Nullable */ UUID label,+ final VendorModelMessageUnacked vendorModelMessageUnacked,+ final MeshTransport meshTransport,+ final InternalMeshMsgHandlerCallbacks callbacks) throws IllegalArgumentException {+ super(src, dst, vendorModelMessageUnacked, meshTransport, callbacks);+ }++ @Override+ public synchronized MeshMessageState.MessageState getState() {+ return MessageState.VENDOR_MODEL_UNACKNOWLEDGED_STATE;+ }++ @Override+ protected synchronized final void createAccessMessage() {+ final VendorModelMessageUnacked message = (VendorModelMessageUnacked) mMeshMessage;+ final ApplicationKey key = message.getAppKey();+ final int akf = message.getAkf();+ final int aid = message.getAid();+ final int aszmic = message.getAszmic();+ final int opCode = message.getOpCode();+ final byte[] parameters = message.getParameters();+ final int companyIdentifier = message.getCompanyIdentifier();+ this.message = mMeshTransport.createVendorMeshMessage(companyIdentifier, mSrc, mDst, mLabel, message.messageTtl,+ key, akf, aid, aszmic, opCode, parameters);+ message.setMessage(this.message);+ }++ @Override+ public synchronized void executeSend() {+ LOG.info("Sending acknowledged vendor model message");+ super.executeSend();+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/AddressArray.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/AddressArray.javanew file mode 100644index 000000000..3c7bdbe85--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/AddressArray.java@@ -0,0 +1,27 @@+package org.openremote.agent.protocol.bluetooth.mesh.utils;++/**+ * Wrapper class for addresses+ */+public class AddressArray {++ final byte[] address = new byte[2];++ /**+ * Constructs the AddressArray+ *+ * @param b1 address byte1+ * @param b2 address byte2+ */+ public AddressArray(final byte b1, final byte b2) {+ address[0] = b1;+ address[1] = b2;+ }++ /**+ * Returns address used in the filter message+ */+ public byte[] getAddress() {+ return address;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/AddressType.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/AddressType.javanew file mode 100644index 000000000..ee3414421--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/AddressType.java@@ -0,0 +1,88 @@+package org.openremote.agent.protocol.bluetooth.mesh.utils;++/**+ * Address types+ */+public enum AddressType {++ UNASSIGNED_ADDRESS(0),+ UNICAST_ADDRESS(1),+ GROUP_ADDRESS(2),+ ALL_PROXIES(3),+ ALL_FRIENDS(4),+ ALL_RELAYS(5),+ ALL_NODES(6),+ VIRTUAL_ADDRESS(7);++ private final int type;++ /**+ * Constructs address type+ *+ * @param type Address type+ */+ AddressType(final int type) {+ this.type = type;+ }++ /**+ * Returns the address type+ */+ public int getType() {+ return type;+ }++ /**+ * Returns the oob method used for authentication+ *+ * @param method auth method used+ */+ public static AddressType fromValue(final int method) {+ switch (method) {+ default:+ case 0:+ return UNASSIGNED_ADDRESS;+ case 1:+ return UNICAST_ADDRESS;+ case 2:+ return GROUP_ADDRESS;+ case 3:+ return ALL_PROXIES;+ case 4:+ return ALL_FRIENDS;+ case 5:+ return ALL_RELAYS;+ case 6:+ return ALL_NODES;+ case 7:+ return VIRTUAL_ADDRESS;+ }+ }++ /**+ * Returns the address type name+ *+ * @param type Address type+ */+ public static String getTypeName(final AddressType type) {+ switch (type) {+ default:+ case UNASSIGNED_ADDRESS:+ return "Unassigned Address";+ case UNICAST_ADDRESS:+ return "Unicast Address";+ case GROUP_ADDRESS:+ return "Group Address";+ case ALL_PROXIES:+ return "All Proxies";+ case ALL_FRIENDS:+ return "All Friends";+ case ALL_RELAYS:+ return "All Relays";+ case ALL_NODES:+ return "All Nodes";+ case VIRTUAL_ADDRESS:+ return "Virtual Address";+ }+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/AlgorithmType.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/AlgorithmType.javanew file mode 100644index 000000000..3dd983f79--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/AlgorithmType.java@@ -0,0 +1,86 @@+package org.openremote.agent.protocol.bluetooth.mesh.utils;++import java.util.ArrayList;+import java.util.logging.Logger;++public enum AlgorithmType {+++ /**+ * Static OOB Type+ */+ NONE((short) 0x0000),+ FIPS_P_256_ELLIPTIC_CURVE((short) 0x0001);++ private static final Logger LOG = java.util.logging.Logger.getLogger(AlgorithmType.class.getName());+ private short algorithmType;++ AlgorithmType(final short algorithmType) {+ this.algorithmType = algorithmType;+ }++ /**+ * Returns the algorithm oob type value+ */+ public short getAlgorithmType() {+ return algorithmType;+ }+++ /**+ * Returns the oob method used for authentication+ *+ * @param method auth method used+ */+ public static AlgorithmType fromValue(final short method) {+ switch (method) {+ default:+ case 0x0000:+ return NONE;+ case 0x0001:+ return FIPS_P_256_ELLIPTIC_CURVE;+ }+ }++ /**+ * Parses the output oob action value+ *+ * @param algorithmTypeValue algorithm type+ * @return selected output action type+ */+ public static ArrayList<AlgorithmType> getAlgorithmTypeFromBitMask(final short algorithmTypeValue) {+ final AlgorithmType[] algorithmTypes = {FIPS_P_256_ELLIPTIC_CURVE};+ final ArrayList<AlgorithmType> supportedAlgorithms = new ArrayList<>();+ for (AlgorithmType algorithmType : algorithmTypes) {+ if ((algorithmTypeValue & algorithmType.ordinal()) == algorithmType.ordinal()) {+ supportedAlgorithms.add(algorithmType);+ LOG.info("Supported output oob action type: " + getAlgorithmTypeDescription(algorithmType));+ }+ }+ return supportedAlgorithms;+ }++ /**+ * Returns the algorithm description+ *+ * @param type {@link AlgorithmType} type+ * @return Input OOB type description+ */+ public static String getAlgorithmTypeDescription(final AlgorithmType type) {+ switch (type) {+ case FIPS_P_256_ELLIPTIC_CURVE:+ return "FIPS P-256 Elliptic Curve";+ default:+ return "Unknown";+ }+ }++ public static byte getAlgorithmValue(final short type) {+ switch (fromValue(type)) {+ case FIPS_P_256_ELLIPTIC_CURVE:+ return 0;+ default:+ return 1;+ }+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/AuthenticationOOBMethods.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/AuthenticationOOBMethods.javanew file mode 100644index 000000000..64c2f596f--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/AuthenticationOOBMethods.java@@ -0,0 +1,65 @@+package org.openremote.agent.protocol.bluetooth.mesh.utils;++public enum AuthenticationOOBMethods {+ //Selecting one of the authentication methods defined below during the provisioning process will require the user to,++ // - Nothing+ NO_OOB_AUTHENTICATION((short) 0),+ // - enter a 16-bit value provided by the device manufacturer to be entered during hte provisioning process+ STATIC_OOB_AUTHENTICATION((short) 1),+ // - enter the number of times the device blinked, beeped, vibrated, displayed or an alphanumeric value displayed by the device+ OUTPUT_OOB_AUTHENTICATION((short) 2),+ // - push, twist, input a number or an alpha numeric value displayed on the provisioner app+ INPUT_OOB_AUTHENTICATION((short) 3);++ private short authenticationMethod;++ AuthenticationOOBMethods(final short authenticationMethod) {+ this.authenticationMethod = authenticationMethod;+ }++ /**+ * Returns the authentication method+ */+ public short getAuthenticationMethod() {+ return authenticationMethod;+ }++ /**+ * Returns the oob method used for authentication+ *+ * @param method auth method used+ */+ public static AuthenticationOOBMethods fromValue(final int method) {+ switch (method) {+ case 0:+ return NO_OOB_AUTHENTICATION;+ case 1:+ return STATIC_OOB_AUTHENTICATION;+ case 2:+ return OUTPUT_OOB_AUTHENTICATION;+ case 3:+ return INPUT_OOB_AUTHENTICATION;+ default:+ return null;+ }+ }++ /**+ * Parses the authentication method used.+ */+ public static String getAuthenticationMethodName(final AuthenticationOOBMethods type) {+ switch (type) {+ case NO_OOB_AUTHENTICATION:+ return "No OOB";+ case STATIC_OOB_AUTHENTICATION:+ return "Static OOB";+ case OUTPUT_OOB_AUTHENTICATION:+ return "Output OOB";+ case INPUT_OOB_AUTHENTICATION:+ return "Input OOB";+ default:+ return "Prohibited";+ }+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/CompanyIdentifiers.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/CompanyIdentifiers.javanew file mode 100644index 000000000..22fe11fff--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/CompanyIdentifiers.java@@ -0,0 +1,1890 @@+package org.openremote.agent.protocol.bluetooth.mesh.utils;++import java.util.HashMap;+import java.util.Map;++public class CompanyIdentifiers {++ private static final Map<Integer, String> vendorModels = new HashMap<>();++ static {+ initVendorModels();+ }++ /**+ * Initializes company identifier and names with the given key/values+ */+ private static void initVendorModels() {+ vendorModels.put(0x0000, "Ericsson Technology Licensing");+ vendorModels.put(0x0001, "Nokia Mobile Phones");+ vendorModels.put(0x0002, "Intel Corp.");+ vendorModels.put(0x0003, "IBM Corp.");+ vendorModels.put(0x0004, "Toshiba Corp.");+ vendorModels.put(0x0005, "3Com");+ vendorModels.put(0x0006, "Microsoft");+ vendorModels.put(0x0007, "Lucent");+ vendorModels.put(0x0008, "Motorola");+ vendorModels.put(0x0009, "Infineon Technologies AG");+ vendorModels.put(0x000A, "Cambridge Silicon Radio");+ vendorModels.put(0x000B, "Silicon Wave");+ vendorModels.put(0x000C, "Digianswer A/S");+ vendorModels.put(0x000D, "Texas Instruments Inc.");+ vendorModels.put(0x000E, "Parthus Technologies Inc.");+ vendorModels.put(0x000F, "Broadcom Corporation");+ vendorModels.put(0x0010, "Mitel Semiconductor");+ vendorModels.put(0x0011, "Widcomm, Inc.");+ vendorModels.put(0x0012, "Zeevo, Inc.");+ vendorModels.put(0x0013, "Atmel Corporation");+ vendorModels.put(0x0014, "Mitsubishi Electric Corporation");+ vendorModels.put(0x0015, "RTX Telecom A/S");+ vendorModels.put(0x0016, "KC Technology Inc.");+ vendorModels.put(0x0017, "Newlogic");+ vendorModels.put(0x0018, "Transilica, Inc.");+ vendorModels.put(0x0019, "Rohde & Schwarz GmbH & Co. KG");+ vendorModels.put(0x001A, "TTPCom Limited");+ vendorModels.put(0x001B, "Signia Technologies, Inc.");+ vendorModels.put(0x001C, "Conexant Systems Inc.");+ vendorModels.put(0x001D, "Qualcomm");+ vendorModels.put(0x001E, "Inventel");+ vendorModels.put(0x001F, "AVM Berlin");+ vendorModels.put(0x0020, "BandSpeed, Inc.");+ vendorModels.put(0x0021, "Mansella Ltd");+ vendorModels.put(0x0022, "NEC Corporation");+ vendorModels.put(0x0023, "WavePlus Technology Co.,Ltd.");+ vendorModels.put(0x0024, "Alcatel");+ vendorModels.put(0x0025, "NXP Semiconductors (formerly Philips Semiconductors);");+ vendorModels.put(0x0026, "C Technologies");+ vendorModels.put(0x0027, "Open Interface");+ vendorModels.put(0x0028, "R F Micro Devices");+ vendorModels.put(0x0029, "Hitachi Ltd");+ vendorModels.put(0x002A, "Symbol Technologies, Inc.");+ vendorModels.put(0x002B, "Tenovis");+ vendorModels.put(0x002C, "Macronix International Co. Ltd.");+ vendorModels.put(0x002D, "GCT Semiconductor");+ vendorModels.put(0x002E, "Norwood Systems");+ vendorModels.put(0x002F, "MewTel Technology Inc.");+ vendorModels.put(0x0030, "ST Microelectronics");+ vendorModels.put(0x0031, "Synopsys, Inc.");+ vendorModels.put(0x0032, "Red-M (Communications,Ltd");+ vendorModels.put(0x0033, "Commil Ltd");+ vendorModels.put(0x0034, "Computer Access Technology Corporation (CATC);");+ vendorModels.put(0x0035, "Eclipse (HQ Espana,S.L.");+ vendorModels.put(0x0036, "Renesas Electronics Corporation");+ vendorModels.put(0x0037, "Mobilian Corporation");+ vendorModels.put(0x0038, "Syntronix Corporation");+ vendorModels.put(0x0039, "Integrated System Solution Corp.");+ vendorModels.put(0x003A, "Matsushita Electric Industrial Co.,Ltd.");+ vendorModels.put(0x003B, "Gennum Corporation");+ vendorModels.put(0x003C, "BlackBerry Limited (formerly Research In Motion);");+ vendorModels.put(0x003D, "IPextreme, Inc.");+ vendorModels.put(0x003E, "Systems and Chips, Inc");+ vendorModels.put(0x003F, "Bluetooth SIG, Inc");+ vendorModels.put(0x0040, "Seiko Epson Corporation");+ vendorModels.put(0x0041, "Integrated Silicon Solution Taiwan, Inc.");+ vendorModels.put(0x0042, "CONWISE Technology Corporation Ltd");+ vendorModels.put(0x0043, "PARROT AUTOMOTIVE SAS");+ vendorModels.put(0x0044, "Socket Mobile");+ vendorModels.put(0x0045, "Atheros Communications, Inc.");+ vendorModels.put(0x0046, "MediaTek, Inc.");+ vendorModels.put(0x0047, "Bluegiga");+ vendorModels.put(0x0048, "Marvell Technology Group Ltd.");+ vendorModels.put(0x0049, "3DSP Corporation");+ vendorModels.put(0x004A, "Accel Semiconductor Ltd.");+ vendorModels.put(0x004B, "Continental Automotive Systems");+ vendorModels.put(0x004C, "Apple, Inc.");+ vendorModels.put(0x004D, "Staccato Communications, Inc.");+ vendorModels.put(0x004E, "Avago Technologies");+ vendorModels.put(0x004F, "APT Ltd.");+ vendorModels.put(0x0050, "SiRF Technology, Inc.");+ vendorModels.put(0x0051, "Tzero Technologies, Inc.");+ vendorModels.put(0x0052, "J&M Corporation");+ vendorModels.put(0x0053, "Free2move AB");+ vendorModels.put(0x0054, "3DiJoy Corporation");+ vendorModels.put(0x0055, "Plantronics, Inc.");+ vendorModels.put(0x0056, "Sony Ericsson Mobile Communications");+ vendorModels.put(0x0057, "Harman International Industries, Inc.");+ vendorModels.put(0x0058, "Vizio, Inc.");+ vendorModels.put(0x0059, "Nordic Semiconductor ASA");+ vendorModels.put(0x005A, "EM Microelectronic-Marin SA");+ vendorModels.put(0x005B, "Ralink Technology Corporation");+ vendorModels.put(0x005C, "Belkin International, Inc.");+ vendorModels.put(0x005D, "Realtek Semiconductor Corporation");+ vendorModels.put(0x005E, "Stonestreet One,LLC");+ vendorModels.put(0x005F, "Wicentric, Inc.");+ vendorModels.put(0x0060, "RivieraWaves S.A.S");+ vendorModels.put(0x0061, "RDA Microelectronics");+ vendorModels.put(0x0062, "Gibson Guitars");+ vendorModels.put(0x0063, "MiCommand Inc.");+ vendorModels.put(0x0064, "Band XI International,LLC");+ vendorModels.put(0x0065, "Hewlett-Packard Company");+ vendorModels.put(0x0066, "9Solutions Oy");+ vendorModels.put(0x0067, "GN Netcom A/S");+ vendorModels.put(0x0068, "General Motors");+ vendorModels.put(0x0069, "A&D Engineering, Inc.");+ vendorModels.put(0x006A, "MindTree Ltd.");+ vendorModels.put(0x006B, "Polar Electro OY");+ vendorModels.put(0x006C, "Beautiful Enterprise Co.,Ltd.");+ vendorModels.put(0x006D, "BriarTek, Inc");+ vendorModels.put(0x006E, "Summit Data Communications, Inc.");+ vendorModels.put(0x006F, "Sound ID");+ vendorModels.put(0x0070, "Monster,LLC");+ vendorModels.put(0x0071, "connectBlue AB");+ vendorModels.put(0x0072, "ShangHai Super Smart Electronics Co. Ltd.");+ vendorModels.put(0x0073, "Group Sense Ltd.");+ vendorModels.put(0x0074, "Zomm,LLC");+ vendorModels.put(0x0075, "Samsung Electronics Co. Ltd.");+ vendorModels.put(0x0076, "Creative Technology Ltd.");+ vendorModels.put(0x0077, "Laird Technologies");+ vendorModels.put(0x0078, "Nike, Inc.");+ vendorModels.put(0x0079, "lesswire AG");+ vendorModels.put(0x007A, "MStar Semiconductor, Inc.");+ vendorModels.put(0x007B, "Hanlynn Technologies");+ vendorModels.put(0x007C, "A & R Cambridge");+ vendorModels.put(0x007D, "Seers Technology Co.,Ltd.");+ vendorModels.put(0x007E, "Sports Tracking Technologies Ltd.");+ vendorModels.put(0x007F, "Autonet Mobile");+ vendorModels.put(0x0080, "DeLorme Publishing Company, Inc.");+ vendorModels.put(0x0081, "WuXi Vimicro");+ vendorModels.put(0x0082, "Sennheiser Communications A/S");+ vendorModels.put(0x0083, "TimeKeeping Systems, Inc.");+ vendorModels.put(0x0084, "Ludus Helsinki Ltd.");+ vendorModels.put(0x0085, "BlueRadios, Inc.");+ vendorModels.put(0x0086, "Equinux AG");+ vendorModels.put(0x0087, "Garmin International, Inc.");+ vendorModels.put(0x0088, "Ecotest");+ vendorModels.put(0x0089, "GN ReSound A/S");+ vendorModels.put(0x008A, "Jawbone");+ vendorModels.put(0x008B, "Topcon Positioning Systems,LLC");+ vendorModels.put(0x008C, "Gimbal Inc. (formerly Qualcomm Labs, Inc. and Qualcomm Retail Solutions, Inc.);");+ vendorModels.put(0x008D, "Zscan Software");+ vendorModels.put(0x008E, "Quintic Corp");+ vendorModels.put(0x008F, "Telit Wireless Solutions GmbH (formerly Stollmann E+V GmbH);");+ vendorModels.put(0x0090, "Funai Electric Co.,Ltd.");+ vendorModels.put(0x0091, "Advanced PANMOBIL systems GmbH & Co. KG");+ vendorModels.put(0x0092, "ThinkOptics, Inc.");+ vendorModels.put(0x0093, "Universal Electronics, Inc.");+ vendorModels.put(0x0094, "Airoha Technology Corp.");+ vendorModels.put(0x0095, "NEC Lighting,Ltd.");+ vendorModels.put(0x0096, "ODM Technology, Inc.");+ vendorModels.put(0x0097, "ConnecteDevice Ltd.");+ vendorModels.put(0x0098, "zero1.tv GmbH");+ vendorModels.put(0x0099, "i.Tech Dynamic Global Distribution Ltd.");+ vendorModels.put(0x009A, "Alpwise");+ vendorModels.put(0x009B, "Jiangsu Toppower Automotive Electronics Co.,Ltd.");+ vendorModels.put(0x009C, "Colorfy, Inc.");+ vendorModels.put(0x009D, "Geoforce Inc.");+ vendorModels.put(0x009E, "Bose Corporation");+ vendorModels.put(0x009F, "Suunto Oy");+ vendorModels.put(0x00A0, "Kensington Computer Products Group");+ vendorModels.put(0x00A1, "SR-Medizinelektronik");+ vendorModels.put(0x00A2, "Vertu Corporation Limited");+ vendorModels.put(0x00A3, "Meta Watch Ltd.");+ vendorModels.put(0x00A4, "LINAK A/S");+ vendorModels.put(0x00A5, "OTL Dynamics LLC");+ vendorModels.put(0x00A6, "Panda Ocean Inc.");+ vendorModels.put(0x00A7, "Visteon Corporation");+ vendorModels.put(0x00A8, "ARP Devices Limited");+ vendorModels.put(0x00A9, "Magneti Marelli S.p.A");+ vendorModels.put(0x00AA, "CAEN RFID srl");+ vendorModels.put(0x00AB, "Ingenieur-Systemgruppe Zahn GmbH");+ vendorModels.put(0x00AC, "Green Throttle Games");+ vendorModels.put(0x00AD, "Peter Systemtechnik GmbH");+ vendorModels.put(0x00AE, "Omegawave Oy");+ vendorModels.put(0x00AF, "Cinetix");+ vendorModels.put(0x00B0, "Passif Semiconductor Corp");+ vendorModels.put(0x00B1, "Saris Cycling Group, Inc");+ vendorModels.put(0x00B2, "Bekey A/S");+ vendorModels.put(0x00B3, "Clarinox Technologies Pty. Ltd.");+ vendorModels.put(0x00B4, "BDE Technology Co.,Ltd.");+ vendorModels.put(0x00B5, "Swirl Networks");+ vendorModels.put(0x00B6, "Meso international");+ vendorModels.put(0x00B7, "TreLab Ltd");+ vendorModels.put(0x00B8, "Qualcomm Innovation Center, Inc. (QuIC);");+ vendorModels.put(0x00B9, "Johnson Controls, Inc.");+ vendorModels.put(0x00BA, "Starkey Laboratories Inc.");+ vendorModels.put(0x00BB, "S-Power Electronics Limited");+ vendorModels.put(0x00BC, "Ace Sensor Inc");+ vendorModels.put(0x00BD, "Aplix Corporation");+ vendorModels.put(0x00BE, "AAMP of America");+ vendorModels.put(0x00BF, "Stalmart Technology Limited");+ vendorModels.put(0x00C0, "AMICCOM Electronics Corporation");+ vendorModels.put(0x00C1, "Shenzhen Excelsecu Data Technology Co.);Ltd");+ vendorModels.put(0x00C2, "Geneq Inc.");+ vendorModels.put(0x00C3, "adidas AG");+ vendorModels.put(0x00C4, "LG Electronics");+ vendorModels.put(0x00C5, "Onset Computer Corporation");+ vendorModels.put(0x00C6, "Selfly BV");+ vendorModels.put(0x00C7, "Quuppa Oy.");+ vendorModels.put(0x00C8, "GeLo Inc");+ vendorModels.put(0x00C9, "Evluma");+ vendorModels.put(0x00CA, "MC10");+ vendorModels.put(0x00CB, "Binauric SE");+ vendorModels.put(0x00CC, "Beats Electronics");+ vendorModels.put(0x00CD, "Microchip Technology Inc.");+ vendorModels.put(0x00CE, "Elgato Systems GmbH");+ vendorModels.put(0x00CF, "ARCHOS SA");+ vendorModels.put(0x00D0, "Dexcom, Inc.");+ vendorModels.put(0x00D1, "Polar Electro Europe B.V.");+ vendorModels.put(0x00D2, "Dialog Semiconductor B.V.");+ vendorModels.put(0x00D3, "Taixingbang Technology (HK,Co);. LTD.");+ vendorModels.put(0x00D4, "Kawantech");+ vendorModels.put(0x00D5, "Austco Communication Systems");+ vendorModels.put(0x00D6, "Timex Group USA, Inc.");+ vendorModels.put(0x00D7, "Qualcomm Technologies, Inc.");+ vendorModels.put(0x00D8, "Qualcomm Connected Experiences, Inc.");+ vendorModels.put(0x00D9, "Voyetra Turtle Beach");+ vendorModels.put(0x00DA, "txtr GmbH");+ vendorModels.put(0x00DB, "Biosentronics");+ vendorModels.put(0x00DC, "Procter & Gamble");+ vendorModels.put(0x00DD, "Hosiden Corporation");+ vendorModels.put(0x00DE, "Muzik LLC");+ vendorModels.put(0x00DF, "Misfit Wearables Corp");+ vendorModels.put(0x00E0, "Google");+ vendorModels.put(0x00E1, "Danlers Ltd");+ vendorModels.put(0x00E2, "Semilink Inc");+ vendorModels.put(0x00E3, "inMusic Brands, Inc");+ vendorModels.put(0x00E4, "L.S. Research Inc.");+ vendorModels.put(0x00E5, "Eden Software Consultants Ltd.");+ vendorModels.put(0x00E6, "Freshtemp");+ vendorModels.put(0x00E7, "KS Technologies");+ vendorModels.put(0x00E8, "ACTS Technologies");+ vendorModels.put(0x00E9, "Vtrack Systems");+ vendorModels.put(0x00EA, "Nielsen-Kellerman Company");+ vendorModels.put(0x00EB, "Server Technology Inc.");+ vendorModels.put(0x00EC, "BioResearch Associates");+ vendorModels.put(0x00ED, "Jolly Logic,LLC");+ vendorModels.put(0x00EE, "Above Average Outcomes, Inc.");+ vendorModels.put(0x00EF, "Bitsplitters GmbH");+ vendorModels.put(0x00F0, "PayPal, Inc.");+ vendorModels.put(0x00F1, "Witron Technology Limited");+ vendorModels.put(0x00F2, "Morse Project Inc.");+ vendorModels.put(0x00F3, "Kent Displays Inc.");+ vendorModels.put(0x00F4, "Nautilus Inc.");+ vendorModels.put(0x00F5, "Smartifier Oy");+ vendorModels.put(0x00F6, "Elcometer Limited");+ vendorModels.put(0x00F7, "VSN Technologies, Inc.");+ vendorModels.put(0x00F8, "AceUni Corp.,Ltd.");+ vendorModels.put(0x00F9, "StickNFind");+ vendorModels.put(0x00FA, "Crystal Code AB");+ vendorModels.put(0x00FB, "KOUKAAM a.s.");+ vendorModels.put(0x00FC, "Delphi Corporation");+ vendorModels.put(0x00FD, "ValenceTech Limited");+ vendorModels.put(0x00FE, "Stanley Black and Decker");+ vendorModels.put(0x00FF, "Typo Products,LLC");+ vendorModels.put(0x0100, "TomTom International BV");+ vendorModels.put(0x0101, "Fugoo, Inc.");+ vendorModels.put(0x0102, "Keiser Corporation");+ vendorModels.put(0x0103, "Bang & Olufsen A/S");+ vendorModels.put(0x0104, "PLUS Location Systems Pty Ltd");+ vendorModels.put(0x0105, "Ubiquitous Computing Technology Corporation");+ vendorModels.put(0x0106, "Innovative Yachtter Solutions");+ vendorModels.put(0x0107, "William Demant Holding A/S");+ vendorModels.put(0x0108, "Chicony Electronics Co.,Ltd.");+ vendorModels.put(0x0109, "Atus BV");+ vendorModels.put(0x010A, "Codegate Ltd");+ vendorModels.put(0x010B, "ERi, Inc");+ vendorModels.put(0x010C, "Transducers Direct,LLC");+ vendorModels.put(0x010D, "Fujitsu Ten LImited");+ vendorModels.put(0x010E, "Audi AG");+ vendorModels.put(0x010F, "HiSilicon Technologies Col,Ltd.");+ vendorModels.put(0x0110, "Nippon Seiki Co.,Ltd.");+ vendorModels.put(0x0111, "Steelseries ApS");+ vendorModels.put(0x0112, "Visybl Inc.");+ vendorModels.put(0x0113, "Openbrain Technologies,Co.,Ltd.");+ vendorModels.put(0x0114, "Xensr");+ vendorModels.put(0x0115, "e.solutions");+ vendorModels.put(0x0116, "10AK Technologies");+ vendorModels.put(0x0117, "Wimoto Technologies Inc");+ vendorModels.put(0x0118, "Radius Networks, Inc.");+ vendorModels.put(0x0119, "Wize Technology Co.,Ltd.");+ vendorModels.put(0x011A, "Qualcomm Labs, Inc.");+ vendorModels.put(0x011B, "Hewlett Packard Enterprise");+ vendorModels.put(0x011C, "Baidu");+ vendorModels.put(0x011D, "Arendi AG");+ vendorModels.put(0x011E, "Skoda Auto a.s.");+ vendorModels.put(0x011F, "Volkswagen AG");+ vendorModels.put(0x0120, "Porsche AG");+ vendorModels.put(0x0121, "Sino Wealth Electronic Ltd.");+ vendorModels.put(0x0122, "AirTurn, Inc.");+ vendorModels.put(0x0123, "Kinsa, Inc");+ vendorModels.put(0x0124, "HID Global");+ vendorModels.put(0x0125, "SEAT es");+ vendorModels.put(0x0126, "Promethean Ltd.");+ vendorModels.put(0x0127, "Salutica Allied Solutions");+ vendorModels.put(0x0128, "GPSI Group Pty Ltd");+ vendorModels.put(0x0129, "Nimble Devices Oy");+ vendorModels.put(0x012A, "Changzhou Yongse Infotech Co.,Ltd.");+ vendorModels.put(0x012B, "SportIQ");+ vendorModels.put(0x012C, "TEMEC Instruments B.V.");+ vendorModels.put(0x012D, "Sony Corporation");+ vendorModels.put(0x012E, "ASSA ABLOY");+ vendorModels.put(0x012F, "Clarion Co. Inc.");+ vendorModels.put(0x0130, "Warehouse Innovations");+ vendorModels.put(0x0131, "Cypress Semiconductor");+ vendorModels.put(0x0132, "MADS Inc");+ vendorModels.put(0x0133, "Blue Maestro Limited");+ vendorModels.put(0x0134, "Resolution Products,Ltd.");+ vendorModels.put(0x0135, "Aireware LLC");+ vendorModels.put(0x0136, "Silvair, Inc.");+ vendorModels.put(0x0137, "Prestigio Plaza Ltd.");+ vendorModels.put(0x0138, "NTEO Inc.");+ vendorModels.put(0x0139, "Focus Systems Corporation");+ vendorModels.put(0x013A, "Tencent Holdings Ltd.");+ vendorModels.put(0x013B, "Allegion");+ vendorModels.put(0x013C, "Murata Manufacturing Co.,Ltd.");+ vendorModels.put(0x013D, "WirelessWERX");+ vendorModels.put(0x013E, "Nod, Inc.");+ vendorModels.put(0x013F, "B&B Manufacturing Company");+ vendorModels.put(0x0140, "Alpine Electronics (China,Co.,Ltd");+ vendorModels.put(0x0141, "FedEx Services");+ vendorModels.put(0x0142, "Grape Systems Inc.");+ vendorModels.put(0x0143, "Bkon Connect");+ vendorModels.put(0x0144, "Lintech GmbH");+ vendorModels.put(0x0145, "Novatel Wireless");+ vendorModels.put(0x0146, "Ciright");+ vendorModels.put(0x0147, "Mighty Cast, Inc.");+ vendorModels.put(0x0148, "Ambimat Electronics");+ vendorModels.put(0x0149, "Perytons Ltd.");+ vendorModels.put(0x014A, "Tivoli Audio,LLC");+ vendorModels.put(0x014B, "Master Lock");+ vendorModels.put(0x014C, "Mesh-Net Ltd");+ vendorModels.put(0x014D, "HUIZHOU DESAY SV AUTOMOTIVE CO.,LTD.");+ vendorModels.put(0x014E, "Tangerine, Inc.");+ vendorModels.put(0x014F, "B&W Group Ltd.");+ vendorModels.put(0x0150, "Pioneer Corporation");+ vendorModels.put(0x0151, "OnBeep");+ vendorModels.put(0x0152, "Vernier Software & Technology");+ vendorModels.put(0x0153, "ROL Ergo");+ vendorModels.put(0x0154, "Pebble Technology");+ vendorModels.put(0x0155, "NETATMO");+ vendorModels.put(0x0156, "Accumulate AB");+ vendorModels.put(0x0157, "Anhui Huami Information Technology Co.,Ltd.");+ vendorModels.put(0x0158, "Inmite s.r.o.");+ vendorModels.put(0x0159, "ChefSteps, Inc.");+ vendorModels.put(0x015A, "micas AG");+ vendorModels.put(0x015B, "Biomedical Research Ltd.");+ vendorModels.put(0x015C, "Pitius Tec S.L.");+ vendorModels.put(0x015D, "Estimote, Inc.");+ vendorModels.put(0x015E, "Unikey Technologies, Inc.");+ vendorModels.put(0x015F, "Timer Cap Co.");+ vendorModels.put(0x0160, "AwoX");+ vendorModels.put(0x0161, "yikes");+ vendorModels.put(0x0162, "MADSGlobalNZ Ltd.");+ vendorModels.put(0x0163, "PCH International");+ vendorModels.put(0x0164, "Qingdao Yeelink Information Technology Co.,Ltd.");+ vendorModels.put(0x0165, "Milwaukee Tool (Formally Milwaukee Electric Tools);");+ vendorModels.put(0x0166, "MISHIK Pte Ltd");+ vendorModels.put(0x0167, "Ascensia Diabetes Care US Inc.");+ vendorModels.put(0x0168, "Spicebox LLC");+ vendorModels.put(0x0169, "emberlight");+ vendorModels.put(0x016A, "Cooper-Atkins Corporation");+ vendorModels.put(0x016B, "Qblinks");+ vendorModels.put(0x016C, "MYSPHERA");+ vendorModels.put(0x016D, "LifeScan Inc");+ vendorModels.put(0x016E, "Volantic AB");+ vendorModels.put(0x016F, "Podo Labs, Inc");+ vendorModels.put(0x0170, "Roche Diabetes Care AG");+ vendorModels.put(0x0171, "Amazon Fulfillment Service");+ vendorModels.put(0x0172, "Connovate Technology Private Limited");+ vendorModels.put(0x0173, "Kocomojo,LLC");+ vendorModels.put(0x0174, "Everykey Inc.");+ vendorModels.put(0x0175, "Dynamic Controls");+ vendorModels.put(0x0176, "SentriLock");+ vendorModels.put(0x0177, "I-SYST inc.");+ vendorModels.put(0x0178, "CASIO COMPUTER CO.,LTD.");+ vendorModels.put(0x0179, "LAPIS Semiconductor Co.,Ltd.");+ vendorModels.put(0x017A, "Telemonitor, Inc.");+ vendorModels.put(0x017B, "taskit GmbH");+ vendorModels.put(0x017C, "Daimler AG");+ vendorModels.put(0x017D, "BatAndCat");+ vendorModels.put(0x017E, "BluDotz Ltd");+ vendorModels.put(0x017F, "XTel Wireless ApS");+ vendorModels.put(0x0180, "Gigaset Communications GmbH");+ vendorModels.put(0x0181, "Gecko Health Innovations, Inc.");+ vendorModels.put(0x0182, "HOP Ubiquitous");+ vendorModels.put(0x0183, "Walt Disney");+ vendorModels.put(0x0184, "Nectar");+ vendorModels.put(0x0185, "bel'apps LLC");+ vendorModels.put(0x0186, "CORE Lighting Ltd");+ vendorModels.put(0x0187, "Seraphim Sense Ltd");+ vendorModels.put(0x0188, "Unico RBC");+ vendorModels.put(0x0189, "Physical Enterprises Inc.");+ vendorModels.put(0x018A, "Able Trend Technology Limited");+ vendorModels.put(0x018B, "Konica Minolta, Inc.");+ vendorModels.put(0x018C, "Wilo SE");+ vendorModels.put(0x018D, "Extron Design Services");+ vendorModels.put(0x018E, "Fitbit, Inc.");+ vendorModels.put(0x018F, "Fireflies Systems");+ vendorModels.put(0x0190, "Intelletto Technologies Inc.");+ vendorModels.put(0x0191, "FDK CORPORATION");+ vendorModels.put(0x0192, "Cloudleaf, Inc");+ vendorModels.put(0x0193, "Maveric Automation LLC");+ vendorModels.put(0x0194, "Acoustic Stream Corporation");+ vendorModels.put(0x0195, "Zuli");+ vendorModels.put(0x0196, "Paxton Access Ltd");+ vendorModels.put(0x0197, "WiSilica Inc.");+ vendorModels.put(0x0198, "VENGIT Korlatolt Felelossegu Tarsasag");+ vendorModels.put(0x0199, "SALTO SYSTEMS S.L.");+ vendorModels.put(0x019A, "TRON Forum (formerly T-Engine Forum);");+ vendorModels.put(0x019B, "CUBETECH s.r.o.");+ vendorModels.put(0x019C, "Cokiya Incorporated");+ vendorModels.put(0x019D, "CVS Health");+ vendorModels.put(0x019E, "Ceruus");+ vendorModels.put(0x019F, "Strainstall Ltd");+ vendorModels.put(0x01A0, "Channel Enterprises (HK,Ltd.");+ vendorModels.put(0x01A1, "FIAMM");+ vendorModels.put(0x01A2, "GIGALANE.CO.);LTD");+ vendorModels.put(0x01A3, "EROAD");+ vendorModels.put(0x01A4, "Mine Safety Appliances");+ vendorModels.put(0x01A5, "Icon Health and Fitness");+ vendorModels.put(0x01A6, "Asandoo GmbH");+ vendorModels.put(0x01A7, "ENERGOUS CORPORATION");+ vendorModels.put(0x01A8, "Taobao");+ vendorModels.put(0x01A9, "Canon Inc.");+ vendorModels.put(0x01AA, "Geophysical Technology Inc.");+ vendorModels.put(0x01AB, "Facebook, Inc.");+ vendorModels.put(0x01AC, "Trividia Health, Inc.");+ vendorModels.put(0x01AD, "FlightSafety International");+ vendorModels.put(0x01AE, "Earlens Corporation");+ vendorModels.put(0x01AF, "Sunrise Micro Devices, Inc.");+ vendorModels.put(0x01B0, "Star Micronics Co.,Ltd.");+ vendorModels.put(0x01B1, "Netizens Sp. z o.o.");+ vendorModels.put(0x01B2, "Nymi Inc.");+ vendorModels.put(0x01B3, "Nytec, Inc.");+ vendorModels.put(0x01B4, "Trineo Sp. z o.o.");+ vendorModels.put(0x01B5, "Nest Labs Inc.");+ vendorModels.put(0x01B6, "LM Technologies Ltd");+ vendorModels.put(0x01B7, "General Electric Company");+ vendorModels.put(0x01B8, "i+D3 S.L.");+ vendorModels.put(0x01B9, "HANA Micron");+ vendorModels.put(0x01BA, "Stages Cycling LLC");+ vendorModels.put(0x01BB, "Cochlear Bone Anchored Solutions AB");+ vendorModels.put(0x01BC, "SenionLab AB");+ vendorModels.put(0x01BD, "Syszone Co.,Ltd");+ vendorModels.put(0x01BE, "Pulsate Mobile Ltd.");+ vendorModels.put(0x01BF, "Hong Kong HunterSun Electronic Limited");+ vendorModels.put(0x01C0, "pironex GmbH");+ vendorModels.put(0x01C1, "BRADATECH Corp.");+ vendorModels.put(0x01C2, "Transenergooil AG");+ vendorModels.put(0x01C3, "Bunch");+ vendorModels.put(0x01C4, "DME Microelectronics");+ vendorModels.put(0x01C5, "Bitcraze AB");+ vendorModels.put(0x01C6, "HASWARE Inc.");+ vendorModels.put(0x01C7, "Abiogenix Inc.");+ vendorModels.put(0x01C8, "Poly-Control ApS");+ vendorModels.put(0x01C9, "Avi-on");+ vendorModels.put(0x01CA, "Laerdal Medical AS");+ vendorModels.put(0x01CB, "Fetch My Pet");+ vendorModels.put(0x01CC, "Sam Labs Ltd.");+ vendorModels.put(0x01CD, "Chengdu Synwing Technology Ltd");+ vendorModels.put(0x01CE, "HOUWA SYSTEM DESIGN,k.k.");+ vendorModels.put(0x01CF, "BSH");+ vendorModels.put(0x01D0, "Primus Inter Pares Ltd");+ vendorModels.put(0x01D1, "August Home, Inc");+ vendorModels.put(0x01D2, "Gill Electronics");+ vendorModels.put(0x01D3, "Sky Wave Design");+ vendorModels.put(0x01D4, "Newlab S.r.l.");+ vendorModels.put(0x01D5, "ELAD srl");+ vendorModels.put(0x01D6, "G-wearables inc.");+ vendorModels.put(0x01D7, "Squadrone Systems Inc.");+ vendorModels.put(0x01D8, "Code Corporation");+ vendorModels.put(0x01D9, "Savant Systems LLC");+ vendorModels.put(0x01DA, "Logitech International SA");+ vendorModels.put(0x01DB, "Innblue Consulting");+ vendorModels.put(0x01DC, "iParking Ltd.");+ vendorModels.put(0x01DD, "Koninklijke Philips Electronics N.V.");+ vendorModels.put(0x01DE, "Minelab Electronics Pty Limited");+ vendorModels.put(0x01DF, "Bison Group Ltd.");+ vendorModels.put(0x01E0, "Widex A/S");+ vendorModels.put(0x01E1, "Jolla Ltd");+ vendorModels.put(0x01E2, "Lectronix, Inc.");+ vendorModels.put(0x01E3, "Caterpillar Inc");+ vendorModels.put(0x01E4, "Freedom Innovations");+ vendorModels.put(0x01E5, "Dynamic Devices Ltd");+ vendorModels.put(0x01E6, "Technology Solutions (UK,Ltd");+ vendorModels.put(0x01E7, "IPS Group Inc.");+ vendorModels.put(0x01E8, "STIR");+ vendorModels.put(0x01E9, "Sano, Inc.");+ vendorModels.put(0x01EA, "Advanced Application Design, Inc.");+ vendorModels.put(0x01EB, "AutoMap LLC");+ vendorModels.put(0x01EC, "Spreadtrum Communications Shanghai Ltd");+ vendorModels.put(0x01ED, "CuteCircuit LTD");+ vendorModels.put(0x01EE, "Valeo Service");+ vendorModels.put(0x01EF, "Fullpower Technologies, Inc.");+ vendorModels.put(0x01F0, "KloudNation");+ vendorModels.put(0x01F1, "Zebra Technologies Corporation");+ vendorModels.put(0x01F2, "Itron, Inc.");+ vendorModels.put(0x01F3, "The University of Tokyo");+ vendorModels.put(0x01F4, "UTC Fire and Security");+ vendorModels.put(0x01F5, "Cool Webthings Limited");+ vendorModels.put(0x01F6, "DJO Global");+ vendorModels.put(0x01F7, "Gelliner Limited");+ vendorModels.put(0x01F8, "Anyka (Guangzhou,Microelectronics Technology Co,LTD");+ vendorModels.put(0x01F9, "Medtronic Inc.");+ vendorModels.put(0x01FA, "Gozio Inc.");+ vendorModels.put(0x01FB, "Form Lifting,LLC");+ vendorModels.put(0x01FC, "Wahoo Fitness,LLC");+ vendorModels.put(0x01FD, "Kontakt Micro-Location Sp. z o.o.");+ vendorModels.put(0x01FE, "Radio Systems Corporation");+ vendorModels.put(0x01FF, "Freescale Semiconductor, Inc.");+ vendorModels.put(0x0200, "Verifone Systems Pte Ltd. Taiwan Branch");+ vendorModels.put(0x0201, "AR Timing");+ vendorModels.put(0x0202, "Rigado LLC");+ vendorModels.put(0x0203, "Kemppi Oy");+ vendorModels.put(0x0204, "Tapcentive Inc.");+ vendorModels.put(0x0205, "Smartbotics Inc.");+ vendorModels.put(0x0206, "Otter Products,LLC");+ vendorModels.put(0x0207, "STEMP Inc.");+ vendorModels.put(0x0208, "LumiGeek LLC");+ vendorModels.put(0x0209, "InvisionHeart Inc.");+ vendorModels.put(0x020A, "Macnica Inc.");+ vendorModels.put(0x020B, "Jaguar Land Rover Limited");+ vendorModels.put(0x020C, "CoroWare Technologies, Inc");+ vendorModels.put(0x020D, "Simplo Technology Co.,LTD");+ vendorModels.put(0x020E, "Omron Healthcare Co.,LTD");+ vendorModels.put(0x020F, "Comodule GMBH");+ vendorModels.put(0x0210, "ikeGPS");+ vendorModels.put(0x0211, "Telink Semiconductor Co. Ltd");+ vendorModels.put(0x0212, "Interplan Co.,Ltd");+ vendorModels.put(0x0213, "Wyler AG");+ vendorModels.put(0x0214, "IK Multimedia Production srl");+ vendorModels.put(0x0215, "Lukoton Experience Oy");+ vendorModels.put(0x0216, "MTI Ltd");+ vendorModels.put(0x0217, "Tech4home,Lda");+ vendorModels.put(0x0218, "Hiotech AB");+ vendorModels.put(0x0219, "DOTT Limited");+ vendorModels.put(0x021A, "Blue Speck Labs,LLC");+ vendorModels.put(0x021B, "Cisco Systems, Inc");+ vendorModels.put(0x021C, "Mobicomm Inc");+ vendorModels.put(0x021D, "Edamic");+ vendorModels.put(0x021E, "Goodnet,Ltd");+ vendorModels.put(0x021F, "Luster Leaf Products Inc");+ vendorModels.put(0x0220, "Manus Machina BV");+ vendorModels.put(0x0221, "Mobiquity Networks Inc");+ vendorModels.put(0x0222, "Praxis Dynamics");+ vendorModels.put(0x0223, "Philip Morris Products S.A.");+ vendorModels.put(0x0224, "Comarch SA");+ vendorModels.put(0x0225, "Nestl Nespresso S.A.");+ vendorModels.put(0x0226, "Merlinia A/S");+ vendorModels.put(0x0227, "LifeBEAM Technologies");+ vendorModels.put(0x0228, "Twocanoes Labs,LLC");+ vendorModels.put(0x0229, "Muoverti Limited");+ vendorModels.put(0x022A, "Stamer Musikanlagen GMBH");+ vendorModels.put(0x022B, "Tesla Motors");+ vendorModels.put(0x022C, "Pharynks Corporation");+ vendorModels.put(0x022D, "Lupine");+ vendorModels.put(0x022E, "Siemens AG");+ vendorModels.put(0x022F, "Huami (Shanghai,Culture Communication CO.,LTD");+ vendorModels.put(0x0230, "Foster Electric Company,Ltd");+ vendorModels.put(0x0231, "ETA SA");+ vendorModels.put(0x0232, "x-Senso Solutions Kft");+ vendorModels.put(0x0233, "Shenzhen SuLong Communication Ltd");+ vendorModels.put(0x0234, "FengFan (BeiJing,Technology Co,Ltd");+ vendorModels.put(0x0235, "Qrio Inc");+ vendorModels.put(0x0236, "Pitpatpet Ltd");+ vendorModels.put(0x0237, "MSHeli s.r.l.");+ vendorModels.put(0x0238, "Trakm8 Ltd");+ vendorModels.put(0x0239, "JIN CO,Ltd");+ vendorModels.put(0x023A, "Alatech Tehnology");+ vendorModels.put(0x023B, "Beijing CarePulse Electronic Technology Co,Ltd");+ vendorModels.put(0x023C, "Awarepoint");+ vendorModels.put(0x023D, "ViCentra B.V.");+ vendorModels.put(0x023E, "Raven Industries");+ vendorModels.put(0x023F, "WaveWare Technologies Inc.");+ vendorModels.put(0x0240, "Argenox Technologies");+ vendorModels.put(0x0241, "Bragi GmbH");+ vendorModels.put(0x0242, "16Lab Inc");+ vendorModels.put(0x0243, "Masimo Corp");+ vendorModels.put(0x0244, "Iotera Inc");+ vendorModels.put(0x0245, "Endress+Hauser");+ vendorModels.put(0x0246, "ACKme Networks, Inc.");+ vendorModels.put(0x0247, "FiftyThree Inc.");+ vendorModels.put(0x0248, "Parker Hannifin Corp");+ vendorModels.put(0x0249, "Transcranial Ltd");+ vendorModels.put(0x024A, "Uwatec AG");+ vendorModels.put(0x024B, "Orlan LLC");+ vendorModels.put(0x024C, "Blue Clover Devices");+ vendorModels.put(0x024D, "M-Way Solutions GmbH");+ vendorModels.put(0x024E, "Microtronics Engineering GmbH");+ vendorModels.put(0x024F, "Schneider Schreibgerte GmbH");+ vendorModels.put(0x0250, "Sapphire Circuits LLC");+ vendorModels.put(0x0251, "Lumo Bodytech Inc.");+ vendorModels.put(0x0252, "UKC Technosolution");+ vendorModels.put(0x0253, "Xicato Inc.");+ vendorModels.put(0x0254, "Playbrush");+ vendorModels.put(0x0255, "Dai Nippon Printing Co.,Ltd.");+ vendorModels.put(0x0256, "G24 Power Limited");+ vendorModels.put(0x0257, "AdBabble Local Commerce Inc.");+ vendorModels.put(0x0258, "Devialet SA");+ vendorModels.put(0x0259, "ALTYOR");+ vendorModels.put(0x025A, "University of Applied Sciences Valais/Haute Ecole Valaisanne");+ vendorModels.put(0x025B, "Five Interactive,LLC dba Zendo");+ vendorModels.put(0x025C, "NetEaseHangzhouNetwork co.Ltd.");+ vendorModels.put(0x025D, "Lexmark International Inc.");+ vendorModels.put(0x025E, "Fluke Corporation");+ vendorModels.put(0x025F, "Yardarm Technologies");+ vendorModels.put(0x0260, "SensaRx");+ vendorModels.put(0x0261, "SECVRE GmbH");+ vendorModels.put(0x0262, "Glacial Ridge Technologies");+ vendorModels.put(0x0263, "Identiv, Inc.");+ vendorModels.put(0x0264, "DDS, Inc.");+ vendorModels.put(0x0265, "SMK Corporation");+ vendorModels.put(0x0266, "Schawbel Technologies LLC");+ vendorModels.put(0x0267, "XMI Systems SA");+ vendorModels.put(0x0268, "Cerevo");+ vendorModels.put(0x0269, "Torrox GmbH & Co KG");+ vendorModels.put(0x026A, "Gemalto");+ vendorModels.put(0x026B, "DEKA Research & Development Corp.");+ vendorModels.put(0x026C, "Domster Tadeusz Szydlowski");+ vendorModels.put(0x026D, "Technogym SPA");+ vendorModels.put(0x026E, "FLEURBAEY BVBA");+ vendorModels.put(0x026F, "Aptcode Solutions");+ vendorModels.put(0x0270, "LSI ADL Technology");+ vendorModels.put(0x0271, "Animas Corp");+ vendorModels.put(0x0272, "Alps Electric Co.,Ltd.");+ vendorModels.put(0x0273, "OCEASOFT");+ vendorModels.put(0x0274, "Motsai Research");+ vendorModels.put(0x0275, "Geotab");+ vendorModels.put(0x0276, "E.G.O. Elektro-Gertebau GmbH");+ vendorModels.put(0x0277, "bewhere inc");+ vendorModels.put(0x0278, "Johnson Outdoors Inc");+ vendorModels.put(0x0279, "steute Schaltgerate GmbH & Co. KG");+ vendorModels.put(0x027A, "Ekomini inc.");+ vendorModels.put(0x027B, "DEFA AS");+ vendorModels.put(0x027C, "Aseptika Ltd");+ vendorModels.put(0x027D, "HUAWEI Technologies Co.,Ltd. ( );");+ vendorModels.put(0x027E, "HabitAware,LLC");+ vendorModels.put(0x027F, "ruwido austria gmbh");+ vendorModels.put(0x0280, "ITEC corporation");+ vendorModels.put(0x0281, "StoneL");+ vendorModels.put(0x0282, "Sonova AG");+ vendorModels.put(0x0283, "Maven Machines, Inc.");+ vendorModels.put(0x0284, "Synapse Electronics");+ vendorModels.put(0x0285, "Standard Innovation Inc.");+ vendorModels.put(0x0286, "RF Code, Inc.");+ vendorModels.put(0x0287, "Wally Ventures S.L.");+ vendorModels.put(0x0288, "Willowbank Electronics Ltd");+ vendorModels.put(0x0289, "SK Telecom");+ vendorModels.put(0x028A, "Jetro AS");+ vendorModels.put(0x028B, "Code Gears LTD");+ vendorModels.put(0x028C, "NANOLINK APS");+ vendorModels.put(0x028D, "IF,LLC");+ vendorModels.put(0x028E, "RF Digital Corp");+ vendorModels.put(0x028F, "Church & Dwight Co., Inc");+ vendorModels.put(0x0290, "Multibit Oy");+ vendorModels.put(0x0291, "CliniCloud Inc");+ vendorModels.put(0x0292, "SwiftSensors");+ vendorModels.put(0x0293, "Blue Bite");+ vendorModels.put(0x0294, "ELIAS GmbH");+ vendorModels.put(0x0295, "Sivantos GmbH");+ vendorModels.put(0x0296, "Petzl");+ vendorModels.put(0x0297, "storm power ltd");+ vendorModels.put(0x0298, "EISST Ltd");+ vendorModels.put(0x0299, "Inexess Technology Simma KG");+ vendorModels.put(0x029A, "Currant, Inc.");+ vendorModels.put(0x029B, "C2 Development, Inc.");+ vendorModels.put(0x029C, "Blue Sky Scientific,LLC");+ vendorModels.put(0x029D, "ALOTTAZS LABS,LLC");+ vendorModels.put(0x029E, "Kupson spol. s r.o.");+ vendorModels.put(0x029F, "Areus Engineering GmbH");+ vendorModels.put(0x02A0, "Impossible Camera GmbH");+ vendorModels.put(0x02A1, "InventureTrack Systems");+ vendorModels.put(0x02A2, "LockedUp");+ vendorModels.put(0x02A3, "Itude");+ vendorModels.put(0x02A4, "Pacific Lock Company");+ vendorModels.put(0x02A5, "Tendyron Corporation ( );");+ vendorModels.put(0x02A6, "Robert Bosch GmbH");+ vendorModels.put(0x02A7, "Illuxtron international B.V.");+ vendorModels.put(0x02A8, "miSport Ltd.");+ vendorModels.put(0x02A9, "Chargelib");+ vendorModels.put(0x02AA, "Doppler Lab");+ vendorModels.put(0x02AB, "BBPOS Limited");+ vendorModels.put(0x02AC, "RTB Elektronik GmbH & Co. KG");+ vendorModels.put(0x02AD, "Rx Networks, Inc.");+ vendorModels.put(0x02AE, "WeatherFlow, Inc.");+ vendorModels.put(0x02AF, "Technicolor USA Inc.");+ vendorModels.put(0x02B0, "Bestechnic(Shanghai););Ltd");+ vendorModels.put(0x02B1, "Raden Inc");+ vendorModels.put(0x02B2, "JouZen Oy");+ vendorModels.put(0x02B3, "CLABER S.P.A.");+ vendorModels.put(0x02B4, "Hyginex, Inc.");+ vendorModels.put(0x02B5, "HANSHIN ELECTRIC RAILWAY CO.);LTD.");+ vendorModels.put(0x02B6, "Schneider Electric");+ vendorModels.put(0x02B7, "Oort Technologies LLC");+ vendorModels.put(0x02B8, "Chrono Therapeutics");+ vendorModels.put(0x02B9, "Rinnai Corporation");+ vendorModels.put(0x02BA, "Swissprime Technologies AG");+ vendorModels.put(0x02BB, "Koha.);Co.Ltd");+ vendorModels.put(0x02BC, "Genevac Ltd");+ vendorModels.put(0x02BD, "Chemtronics");+ vendorModels.put(0x02BE, "Seguro Technology Sp. z o.o.");+ vendorModels.put(0x02BF, "Redbird Flight Simulations");+ vendorModels.put(0x02C0, "Dash Robotics");+ vendorModels.put(0x02C1, "LINE Corporation");+ vendorModels.put(0x02C2, "Guillemot Corporation");+ vendorModels.put(0x02C3, "Techtronic Power Tools Technology Limited");+ vendorModels.put(0x02C4, "Wilson Sporting Goods");+ vendorModels.put(0x02C5, "Lenovo (Singapore,Pte Ltd. ( );");+ vendorModels.put(0x02C6, "Ayatan Sensors");+ vendorModels.put(0x02C7, "Electronics Tomorrow Limited");+ vendorModels.put(0x02C8, "VASCO Data Security International, Inc.");+ vendorModels.put(0x02C9, "PayRange Inc.");+ vendorModels.put(0x02CA, "ABOV Semiconductor");+ vendorModels.put(0x02CB, "AINA-Wireless Inc.");+ vendorModels.put(0x02CC, "Eijkelkamp Soil & Water");+ vendorModels.put(0x02CD, "BMA ergonomics b.v.");+ vendorModels.put(0x02CE, "Teva Branded Pharmaceutical Products R&D, Inc.");+ vendorModels.put(0x02CF, "Anima");+ vendorModels.put(0x02D0, "3M");+ vendorModels.put(0x02D1, "Empatica Srl");+ vendorModels.put(0x02D2, "Afero, Inc.");+ vendorModels.put(0x02D3, "Powercast Corporation");+ vendorModels.put(0x02D4, "Secuyou ApS");+ vendorModels.put(0x02D5, "OMRON Corporation");+ vendorModels.put(0x02D6, "Send Solutions");+ vendorModels.put(0x02D7, "NIPPON SYSTEMWARE CO.);LTD.");+ vendorModels.put(0x02D8, "Neosfar");+ vendorModels.put(0x02D9, "Fliegl Agrartechnik GmbH");+ vendorModels.put(0x02DA, "Gilvader");+ vendorModels.put(0x02DB, "Digi International Inc (R);");+ vendorModels.put(0x02DC, "DeWalch Technologies, Inc.");+ vendorModels.put(0x02DD, "Flint Rehabilitation Devices,LLC");+ vendorModels.put(0x02DE, "Samsung SDS Co.,Ltd.");+ vendorModels.put(0x02DF, "Blur Product Development");+ vendorModels.put(0x02E0, "University of Michigan");+ vendorModels.put(0x02E1, "Victron Energy BV");+ vendorModels.put(0x02E2, "NTT docomo");+ vendorModels.put(0x02E3, "Carmanah Technologies Corp.");+ vendorModels.put(0x02E4, "Bytestorm Ltd.");+ vendorModels.put(0x02E5, "Espressif Incorporated ( (,);");+ vendorModels.put(0x02E6, "Unwire");+ vendorModels.put(0x02E7, "Connected Yard, Inc.");+ vendorModels.put(0x02E8, "American Music Environments");+ vendorModels.put(0x02E9, "Sensogram Technologies, Inc.");+ vendorModels.put(0x02EA, "Fujitsu Limited");+ vendorModels.put(0x02EB, "Ardic Technology");+ vendorModels.put(0x02EC, "Delta Systems, Inc");+ vendorModels.put(0x02ED, "HTC Corporation");+ vendorModels.put(0x02EE, "Citizen Holdings Co.,Ltd.");+ vendorModels.put(0x02EF, "SMART-INNOVATION.inc");+ vendorModels.put(0x02F0, "Blackrat Software");+ vendorModels.put(0x02F1, "The Idea Cave,LLC");+ vendorModels.put(0x02F2, "GoPro, Inc.");+ vendorModels.put(0x02F3, "AuthAir, Inc");+ vendorModels.put(0x02F4, "Vensi, Inc.");+ vendorModels.put(0x02F5, "Indagem Tech LLC");+ vendorModels.put(0x02F6, "Intemo Technologies");+ vendorModels.put(0x02F7, "DreamVisions co.,Ltd.");+ vendorModels.put(0x02F8, "Runteq Oy Ltd");+ vendorModels.put(0x02F9, "IMAGINATION TECHNOLOGIES LTD");+ vendorModels.put(0x02FA, "CoSTAR TEchnologies");+ vendorModels.put(0x02FB, "Clarius Mobile Health Corp.");+ vendorModels.put(0x02FC, "Shanghai Frequen Microelectronics Co.,Ltd.");+ vendorModels.put(0x02FD, "Uwanna, Inc.");+ vendorModels.put(0x02FE, "Lierda Science & Technology Group Co.,Ltd.");+ vendorModels.put(0x02FF, "Silicon Laboratories");+ vendorModels.put(0x0300, "World Moto Inc.");+ vendorModels.put(0x0301, "Giatec Scientific Inc.");+ vendorModels.put(0x0302, "Loop Devices, Inc");+ vendorModels.put(0x0303, "IACA electronique");+ vendorModels.put(0x0304, "Proxy Technologies, Inc.");+ vendorModels.put(0x0305, "Swipp ApS");+ vendorModels.put(0x0306, "Life Laboratory Inc.");+ vendorModels.put(0x0307, "FUJI INDUSTRIAL CO.);LTD.");+ vendorModels.put(0x0308, "Surefire,LLC");+ vendorModels.put(0x0309, "Dolby Labs");+ vendorModels.put(0x030A, "Ellisys");+ vendorModels.put(0x030B, "Magnitude Lighting Converters");+ vendorModels.put(0x030C, "Hilti AG");+ vendorModels.put(0x030D, "Devdata S.r.l.");+ vendorModels.put(0x030E, "Deviceworx");+ vendorModels.put(0x030F, "Shortcut Labs");+ vendorModels.put(0x0310, "SGL Italia S.r.l.");+ vendorModels.put(0x0311, "PEEQ DATA");+ vendorModels.put(0x0312, "Ducere Technologies Pvt Ltd");+ vendorModels.put(0x0313, "DiveNav, Inc.");+ vendorModels.put(0x0314, "RIIG AI Sp. z o.o.");+ vendorModels.put(0x0315, "Thermo Fisher Scientific");+ vendorModels.put(0x0316, "AG Measurematics Pvt. Ltd.");+ vendorModels.put(0x0317, "CHUO Electronics CO.,LTD.");+ vendorModels.put(0x0318, "Aspenta International");+ vendorModels.put(0x0319, "Eugster Frismag AG");+ vendorModels.put(0x031A, "Amber wireless GmbH");+ vendorModels.put(0x031B, "HQ Inc");+ vendorModels.put(0x031C, "Lab Sensor Solutions");+ vendorModels.put(0x031D, "Enterlab ApS");+ vendorModels.put(0x031E, "Eyefi, Inc.");+ vendorModels.put(0x031F, "MetaSystem S.p.A.");+ vendorModels.put(0x0320, "SONO ELECTRONICS. CO.,LTD");+ vendorModels.put(0x0321, "Jewelbots");+ vendorModels.put(0x0322, "Compumedics Limited");+ vendorModels.put(0x0323, "Rotor Bike Components");+ vendorModels.put(0x0324, "Astro, Inc.");+ vendorModels.put(0x0325, "Amotus Solutions");+ vendorModels.put(0x0326, "Healthwear Technologies (Changzhou);Ltd");+ vendorModels.put(0x0327, "Essex Electronics");+ vendorModels.put(0x0328, "Grundfos A/S");+ vendorModels.put(0x0329, "Eargo, Inc.");+ vendorModels.put(0x032A, "Electronic Design Lab");+ vendorModels.put(0x032B, "ESYLUX");+ vendorModels.put(0x032C, "NIPPON SMT.CO.);Ltd");+ vendorModels.put(0x032D, "BM innovations GmbH");+ vendorModels.put(0x032E, "indoormap");+ vendorModels.put(0x032F, "OttoQ Inc");+ vendorModels.put(0x0330, "North Pole Engineering");+ vendorModels.put(0x0331, "3flares Technologies Inc.");+ vendorModels.put(0x0332, "Electrocompaniet A.S.");+ vendorModels.put(0x0333, "Mul-T-Lock");+ vendorModels.put(0x0334, "Corentium AS");+ vendorModels.put(0x0335, "Enlighted Inc");+ vendorModels.put(0x0336, "GISTIC");+ vendorModels.put(0x0337, "AJP2 Holdings,LLC");+ vendorModels.put(0x0338, "COBI GmbH");+ vendorModels.put(0x0339, "Blue Sky Scientific,LLC");+ vendorModels.put(0x033A, "Appception, Inc.");+ vendorModels.put(0x033B, "Courtney Thorne Limited");+ vendorModels.put(0x033C, "Virtuosys");+ vendorModels.put(0x033D, "TPV Technology Limited");+ vendorModels.put(0x033E, "Monitra SA");+ vendorModels.put(0x033F, "Automation Components, Inc.");+ vendorModels.put(0x0340, "Letsense s.r.l.");+ vendorModels.put(0x0341, "Etesian Technologies LLC");+ vendorModels.put(0x0342, "GERTEC BRASIL LTDA.");+ vendorModels.put(0x0343, "Drekker Development Pty. Ltd.");+ vendorModels.put(0x0344, "Whirl Inc");+ vendorModels.put(0x0345, "Locus Positioning");+ vendorModels.put(0x0346, "Acuity Brands Lighting, Inc");+ vendorModels.put(0x0347, "Prevent Biometrics");+ vendorModels.put(0x0348, "Arioneo");+ vendorModels.put(0x0349, "VersaMe");+ vendorModels.put(0x034A, "Vaddio");+ vendorModels.put(0x034B, "Libratone A/S");+ vendorModels.put(0x034C, "HM Electronics, Inc.");+ vendorModels.put(0x034D, "TASER International, Inc.");+ vendorModels.put(0x034E, "SafeTrust Inc.");+ vendorModels.put(0x034F, "Heartland Payment Systems");+ vendorModels.put(0x0350, "Bitstrata Systems Inc.");+ vendorModels.put(0x0351, "Pieps GmbH");+ vendorModels.put(0x0352, "iRiding(Xiamen);Technology Co.);Ltd.");+ vendorModels.put(0x0353, "Alpha Audiotronics, Inc.");+ vendorModels.put(0x0354, "TOPPAN FORMS CO.);LTD.");+ vendorModels.put(0x0355, "Sigma Designs, Inc.");+ vendorModels.put(0x0356, "Spectrum Brands, Inc.");+ vendorModels.put(0x0357, "Polymap Wireless");+ vendorModels.put(0x0358, "MagniWare Ltd.");+ vendorModels.put(0x0359, "Novotec Medical GmbH");+ vendorModels.put(0x035A, "Medicom Innovation Partner a/s");+ vendorModels.put(0x035B, "Matrix Inc.");+ vendorModels.put(0x035C, "Eaton Corporation");+ vendorModels.put(0x035D, "KYS");+ vendorModels.put(0x035E, "Naya Health, Inc.");+ vendorModels.put(0x035F, "Acromag");+ vendorModels.put(0x0360, "Insulet Corporation");+ vendorModels.put(0x0361, "Wellinks Inc.");+ vendorModels.put(0x0362, "ON Semiconductor");+ vendorModels.put(0x0363, "FREELAP SA");+ vendorModels.put(0x0364, "Favero Electronics Srl");+ vendorModels.put(0x0365, "BioMech Sensor LLC");+ vendorModels.put(0x0366, "BOLTT Sports technologies Private limited");+ vendorModels.put(0x0367, "Saphe International");+ vendorModels.put(0x0368, "Metormote AB");+ vendorModels.put(0x0369, "littleBits");+ vendorModels.put(0x036A, "SetPoint Medical");+ vendorModels.put(0x036B, "BRControls Products BV");+ vendorModels.put(0x036C, "Zipcar");+ vendorModels.put(0x036D, "AirBolt Pty Ltd");+ vendorModels.put(0x036E, "KeepTruckin Inc");+ vendorModels.put(0x036F, "Motiv, Inc.");+ vendorModels.put(0x0370, "Wazombi Labs O");+ vendorModels.put(0x0371, "ORBCOMM");+ vendorModels.put(0x0372, "Nixie Labs, Inc.");+ vendorModels.put(0x0373, "AppNearMe Ltd");+ vendorModels.put(0x0374, "Holman Industries");+ vendorModels.put(0x0375, "Expain AS");+ vendorModels.put(0x0376, "Electronic Temperature Instruments Ltd");+ vendorModels.put(0x0377, "Plejd AB");+ vendorModels.put(0x0378, "Propeller Health");+ vendorModels.put(0x0379, "Shenzhen iMCO Electronic Technology Co.);Ltd");+ vendorModels.put(0x037A, "Algoria");+ vendorModels.put(0x037B, "Apption Labs Inc.");+ vendorModels.put(0x037C, "Cronologics Corporation");+ vendorModels.put(0x037D, "MICRODIA Ltd.");+ vendorModels.put(0x037E, "lulabytes S.L.");+ vendorModels.put(0x037F, "Nestec S.A.");+ vendorModels.put(0x0380, "LLC \"MEGA-F service\"");+ vendorModels.put(0x0381, "Sharp Corporation");+ vendorModels.put(0x0382, "Precision Outcomes Ltd");+ vendorModels.put(0x0383, "Kronos Incorporated");+ vendorModels.put(0x0384, "OCOSMOS Co.,Ltd.");+ vendorModels.put(0x0385, "Embedded Electronic Solutions Ltd. dba e2Solutions");+ vendorModels.put(0x0386, "Aterica Inc.");+ vendorModels.put(0x0387, "BluStor PMC, Inc.");+ vendorModels.put(0x0388, "Kapsch TrafficCom AB");+ vendorModels.put(0x0389, "ActiveBlu Corporation");+ vendorModels.put(0x038A, "Kohler Mira Limited");+ vendorModels.put(0x038B, "Noke");+ vendorModels.put(0x038C, "Appion Inc.");+ vendorModels.put(0x038D, "Resmed Ltd");+ vendorModels.put(0x038E, "Crownstone B.V.");+ vendorModels.put(0x038F, "Xiaomi Inc.");+ vendorModels.put(0x0390, "INFOTECH s.r.o.");+ vendorModels.put(0x0391, "Thingsquare AB");+ vendorModels.put(0x0392, "T&D");+ vendorModels.put(0x0393, "LAVAZZA S.p.A.");+ vendorModels.put(0x0394, "Netclearance Systems, Inc.");+ vendorModels.put(0x0395, "SDATAWAY");+ vendorModels.put(0x0396, "BLOKS GmbH");+ vendorModels.put(0x0397, "LEGO System A/S");+ vendorModels.put(0x0398, "Thetatronics Ltd");+ vendorModels.put(0x0399, "Nikon Corporation");+ vendorModels.put(0x039A, "NeST");+ vendorModels.put(0x039B, "South Silicon Valley Microelectronics");+ vendorModels.put(0x039C, "ALE International");+ vendorModels.put(0x039D, "CareView Communications, Inc.");+ vendorModels.put(0x039E, "SchoolBoard Limited");+ vendorModels.put(0x039F, "Molex Corporation");+ vendorModels.put(0x03A0, "IVT Wireless Limited");+ vendorModels.put(0x03A1, "Alpine Labs LLC");+ vendorModels.put(0x03A2, "Candura Instruments");+ vendorModels.put(0x03A3, "SmartMovt Technology Co.,Ltd");+ vendorModels.put(0x03A4, "Token Zero Ltd");+ vendorModels.put(0x03A5, "ACE CAD Enterprise Co.,Ltd. (ACECAD);");+ vendorModels.put(0x03A6, "Medela, Inc");+ vendorModels.put(0x03A7, "AeroScout");+ vendorModels.put(0x03A8, "Esrille Inc.");+ vendorModels.put(0x03A9, "THINKERLY SRL");+ vendorModels.put(0x03AA, "Exon Sp. z o.o.");+ vendorModels.put(0x03AB, "Meizu Technology Co.,Ltd.");+ vendorModels.put(0x03AC, "Smablo LTD");+ vendorModels.put(0x03AD, "XiQ");+ vendorModels.put(0x03AE, "Allswell Inc.");+ vendorModels.put(0x03AF, "Comm-N-Sense Corp DBA Verigo");+ vendorModels.put(0x03B0, "VIBRADORM GmbH");+ vendorModels.put(0x03B1, "Otodata Wireless Network Inc.");+ vendorModels.put(0x03B2, "Propagation Systems Limited");+ vendorModels.put(0x03B3, "Midwest Instruments & Controls");+ vendorModels.put(0x03B4, "Alpha Nodus, Inc.");+ vendorModels.put(0x03B5, "petPOMM, Inc");+ vendorModels.put(0x03B6, "Mattel");+ vendorModels.put(0x03B7, "Airbly Inc.");+ vendorModels.put(0x03B8, "A-Safe Limited");+ vendorModels.put(0x03B9, "FREDERIQUE CONSTANT SA");+ vendorModels.put(0x03BA, "Maxscend Microelectronics Company Limited");+ vendorModels.put(0x03BB, "Abbott Diabetes Care");+ vendorModels.put(0x03BC, "ASB Bank Ltd");+ vendorModels.put(0x03BD, "amadas");+ vendorModels.put(0x03BE, "Applied Science, Inc.");+ vendorModels.put(0x03BF, "iLumi Solutions Inc.");+ vendorModels.put(0x03C0, "Arch Systems Inc.");+ vendorModels.put(0x03C1, "Ember Technologies, Inc.");+ vendorModels.put(0x03C2, "Snapchat Inc");+ vendorModels.put(0x03C3, "Casambi Technologies Oy");+ vendorModels.put(0x03C4, "Pico Technology Inc.");+ vendorModels.put(0x03C5, "St. Jude Medical, Inc.");+ vendorModels.put(0x03C6, "Intricon");+ vendorModels.put(0x03C7, "Structural Health Systems, Inc.");+ vendorModels.put(0x03C8, "Avvel International");+ vendorModels.put(0x03C9, "Gallagher Group");+ vendorModels.put(0x03CA, "In2things Automation Pvt. Ltd.");+ vendorModels.put(0x03CB, "SYSDEV Srl");+ vendorModels.put(0x03CC, "Vonkil Technologies Ltd");+ vendorModels.put(0x03CD, "Wynd Technologies, Inc.");+ vendorModels.put(0x03CE, "CONTRINEX S.A.");+ vendorModels.put(0x03CF, "MIRA, Inc.");+ vendorModels.put(0x03D0, "Watteam Ltd");+ vendorModels.put(0x03D1, "Density Inc.");+ vendorModels.put(0x03D2, "IOT Pot India Private Limited");+ vendorModels.put(0x03D3, "Sigma Connectivity AB");+ vendorModels.put(0x03D4, "PEG PEREGO SPA");+ vendorModels.put(0x03D5, "Wyzelink Systems Inc.");+ vendorModels.put(0x03D6, "Yota Devices LTD");+ vendorModels.put(0x03D7, "FINSECUR");+ vendorModels.put(0x03D8, "Zen-Me Labs Ltd");+ vendorModels.put(0x03D9, "3IWare Co.,Ltd.");+ vendorModels.put(0x03DA, "EnOcean GmbH");+ vendorModels.put(0x03DB, "Instabeat, Inc");+ vendorModels.put(0x03DC, "Nima Labs");+ vendorModels.put(0x03DD, "Andreas Stihl AG & Co. KG");+ vendorModels.put(0x03DE, "Nathan Rhoades LLC");+ vendorModels.put(0x03DF, "Grob Technologies,LLC");+ vendorModels.put(0x03E0, "Actions (Zhuhai,Technology Co.,Limited");+ vendorModels.put(0x03E1, "SPD Development Company Ltd");+ vendorModels.put(0x03E2, "Sensoan Oy");+ vendorModels.put(0x03E3, "Qualcomm Life Inc");+ vendorModels.put(0x03E4, "Chip-ing AG");+ vendorModels.put(0x03E5, "ffly4u");+ vendorModels.put(0x03E6, "IoT Instruments Oy");+ vendorModels.put(0x03E7, "TRUE Fitness Technology");+ vendorModels.put(0x03E8, "Reiner Kartengeraete GmbH & Co. KG.");+ vendorModels.put(0x03E9, "SHENZHEN LEMONJOY TECHNOLOGY CO.,LTD.");+ vendorModels.put(0x03EA, "Hello Inc.");+ vendorModels.put(0x03EB, "Evollve Inc.");+ vendorModels.put(0x03EC, "Jigowatts Inc.");+ vendorModels.put(0x03ED, "BASIC MICRO.COM);INC.");+ vendorModels.put(0x03EE, "CUBE TECHNOLOGIES");+ vendorModels.put(0x03EF, "foolography GmbH");+ vendorModels.put(0x03F0, "CLINK");+ vendorModels.put(0x03F1, "Hestan Smart Cooking Inc.");+ vendorModels.put(0x03F2, "WindowMaster A/S");+ vendorModels.put(0x03F3, "Flowscape AB");+ vendorModels.put(0x03F4, "PAL Technologies Ltd");+ vendorModels.put(0x03F5, "WHERE, Inc.");+ vendorModels.put(0x03F6, "Iton Technology Corp.");+ vendorModels.put(0x03F7, "Owl Labs Inc.");+ vendorModels.put(0x03F8, "Rockford Corp.");+ vendorModels.put(0x03F9, "Becon Technologies Co.);Ltd.");+ vendorModels.put(0x03FA, "Vyassoft Technologies Inc");+ vendorModels.put(0x03FB, "Nox Medical");+ vendorModels.put(0x03FC, "Kimberly-Clark");+ vendorModels.put(0x03FD, "Trimble Navigation Ltd.");+ vendorModels.put(0x03FE, "Littelfuse");+ vendorModels.put(0x03FF, "Withings");+ vendorModels.put(0x0400, "i-developer IT Beratung UG");+ vendorModels.put(0x0401, "Unknown");+ vendorModels.put(0x0402, "Sears Holdings Corporation");+ vendorModels.put(0x0403, "Gantner Electronic GmbH");+ vendorModels.put(0x0404, "Authomate Inc");+ vendorModels.put(0x0405, "Vertex International, Inc.");+ vendorModels.put(0x0406, "Airtago");+ vendorModels.put(0x0407, "Swiss Audio SA");+ vendorModels.put(0x0408, "ToGetHome Inc.");+ vendorModels.put(0x0409, "AXIS");+ vendorModels.put(0x040A, "Openmatics");+ vendorModels.put(0x040B, "Jana Care Inc.");+ vendorModels.put(0x040C, "Senix Corporation");+ vendorModels.put(0x040D, "NorthStar Battery Company,LLC");+ vendorModels.put(0x040E, "SKF (U.K.,Limited");+ vendorModels.put(0x040F, "CO-AX Technology, Inc.");+ vendorModels.put(0x0410, "Fender Musical Instruments");+ vendorModels.put(0x0411, "Luidia Inc");+ vendorModels.put(0x0412, "SEFAM");+ vendorModels.put(0x0413, "Wireless Cables Inc");+ vendorModels.put(0x0414, "Lightning Protection International Pty Ltd");+ vendorModels.put(0x0415, "Uber Technologies Inc");+ vendorModels.put(0x0416, "SODA GmbH");+ vendorModels.put(0x0417, "Fatigue Science");+ vendorModels.put(0x0418, "Alpine Electronics Inc.");+ vendorModels.put(0x0419, "Novalogy LTD");+ vendorModels.put(0x041A, "Friday Labs Limited");+ vendorModels.put(0x041B, "OrthoAccel Technologies");+ vendorModels.put(0x041C, "WaterGuru, Inc.");+ vendorModels.put(0x041D, "Benning Elektrotechnik und Elektronik GmbH & Co. KG");+ vendorModels.put(0x041E, "Dell Computer Corporation");+ vendorModels.put(0x041F, "Kopin Corporation");+ vendorModels.put(0x0420, "TecBakery GmbH");+ vendorModels.put(0x0421, "Backbone Labs, Inc.");+ vendorModels.put(0x0422, "DELSEY SA");+ vendorModels.put(0x0423, "Chargifi Limited");+ vendorModels.put(0x0424, "Trainesense Ltd.");+ vendorModels.put(0x0425, "Unify Software and Solutions GmbH & Co. KG");+ vendorModels.put(0x0426, "Husqvarna AB");+ vendorModels.put(0x0427, "Focus fleet and fuel management inc");+ vendorModels.put(0x0428, "SmallLoop,LLC");+ vendorModels.put(0x0429, "Prolon Inc.");+ vendorModels.put(0x042A, "BD Medical");+ vendorModels.put(0x042B, "iMicroMed Incorporated");+ vendorModels.put(0x042C, "Ticto N.V.");+ vendorModels.put(0x042D, "Meshtech AS");+ vendorModels.put(0x042E, "MemCachier Inc.");+ vendorModels.put(0x042F, "Danfoss A/S");+ vendorModels.put(0x0430, "SnapStyk Inc.");+ vendorModels.put(0x0431, "Amway Corporation");+ vendorModels.put(0x0432, "Silk Labs, Inc.");+ vendorModels.put(0x0433, "Pillsy Inc.");+ vendorModels.put(0x0434, "Hatch Baby, Inc.");+ vendorModels.put(0x0435, "Blocks Wearables Ltd.");+ vendorModels.put(0x0436, "Drayson Technologies (Europe,Limited");+ vendorModels.put(0x0437, "eBest IOT Inc.");+ vendorModels.put(0x0438, "Helvar Ltd");+ vendorModels.put(0x0439, "Radiance Technologies");+ vendorModels.put(0x043A, "Nuheara Limited");+ vendorModels.put(0x043B, "Appside co.,ltd.");+ vendorModels.put(0x043C, "DeLaval");+ vendorModels.put(0x043D, "Coiler Corporation");+ vendorModels.put(0x043E, "Thermomedics, Inc.");+ vendorModels.put(0x043F, "Tentacle Sync GmbH");+ vendorModels.put(0x0440, "Valencell, Inc.");+ vendorModels.put(0x0441, "iProtoXi Oy");+ vendorModels.put(0x0442, "SECOM CO.,LTD.");+ vendorModels.put(0x0443, "Tucker International LLC");+ vendorModels.put(0x0444, "Metanate Limited");+ vendorModels.put(0x0445, "Kobian Canada Inc.");+ vendorModels.put(0x0446, "NETGEAR, Inc.");+ vendorModels.put(0x0447, "Fabtronics Australia Pty Ltd");+ vendorModels.put(0x0448, "Grand Centrix GmbH");+ vendorModels.put(0x0449, "1UP USA.com llc");+ vendorModels.put(0x044A, "SHIMANO INC.");+ vendorModels.put(0x044B, "Nain Inc.");+ vendorModels.put(0x044C, "LifeStyle Lock,LLC");+ vendorModels.put(0x044D, "VEGA Grieshaber KG");+ vendorModels.put(0x044E, "Xtrava Inc.");+ vendorModels.put(0x044F, "TTS Tooltechnic Systems AG & Co. KG");+ vendorModels.put(0x0450, "Teenage Engineering AB");+ vendorModels.put(0x0451, "Tunstall Nordic AB");+ vendorModels.put(0x0452, "Svep Design Center AB");+ vendorModels.put(0x0453, "GreenPeak Technologies BV");+ vendorModels.put(0x0454, "Sphinx Electronics GmbH & Co KG");+ vendorModels.put(0x0455, "Atomation");+ vendorModels.put(0x0456, "Nemik Consulting Inc");+ vendorModels.put(0x0457, "RF INNOVATION");+ vendorModels.put(0x0458, "Mini Solution Co.,Ltd.");+ vendorModels.put(0x0459, "Lumenetix, Inc");+ vendorModels.put(0x045A, "2048450 Ontario Inc");+ vendorModels.put(0x045B, "SPACEEK LTD");+ vendorModels.put(0x045C, "Delta T Corporation");+ vendorModels.put(0x045D, "Boston Scientific Corporation");+ vendorModels.put(0x045E, "Nuviz, Inc.");+ vendorModels.put(0x045F, "Real Time Automation, Inc.");+ vendorModels.put(0x0460, "Kolibree");+ vendorModels.put(0x0461, "vhf elektronik GmbH");+ vendorModels.put(0x0462, "Bonsai Systems GmbH");+ vendorModels.put(0x0463, "Fathom Systems Inc.");+ vendorModels.put(0x0464, "Bellman & Symfon");+ vendorModels.put(0x0465, "International Forte Group LLC");+ vendorModels.put(0x0466, "CycleLabs Solutions inc.");+ vendorModels.put(0x0467, "Codenex Oy");+ vendorModels.put(0x0468, "Kynesim Ltd");+ vendorModels.put(0x0469, "Palago AB");+ vendorModels.put(0x046A, "INSIGMA INC.");+ vendorModels.put(0x046B, "PMD Solutions");+ vendorModels.put(0x046C, "Qingdao Realtime Technology Co.,Ltd.");+ vendorModels.put(0x046D, "BEGA Gantenbrink-Leuchten KG");+ vendorModels.put(0x046E, "Pambor Ltd.");+ vendorModels.put(0x046F, "Develco Products A/S");+ vendorModels.put(0x0470, "iDesign s.r.l.");+ vendorModels.put(0x0471, "TiVo Corp");+ vendorModels.put(0x0472, "Control-J Pty Ltd");+ vendorModels.put(0x0473, "Steelcase, Inc.");+ vendorModels.put(0x0474, "iApartment co.,ltd.");+ vendorModels.put(0x0475, "Icom inc.");+ vendorModels.put(0x0476, "Oxstren Wearable Technologies Private Limited");+ vendorModels.put(0x0477, "Blue Spark Technologies");+ vendorModels.put(0x0478, "FarSite Communications Limited");+ vendorModels.put(0x0479, "mywerk system GmbH");+ vendorModels.put(0x047A, "Sinosun Technology Co.,Ltd.");+ vendorModels.put(0x047B, "MIYOSHI ELECTRONICS CORPORATION");+ vendorModels.put(0x047C, "POWERMAT LTD");+ vendorModels.put(0x047D, "Occly LLC");+ vendorModels.put(0x047E, "OurHub Dev IvS");+ vendorModels.put(0x047F, "Pro-Mark, Inc.");+ vendorModels.put(0x0480, "Dynometrics Inc.");+ vendorModels.put(0x0481, "Quintrax Limited");+ vendorModels.put(0x0482, "POS Tuning Udo Vosshenrich GmbH & Co. KG");+ vendorModels.put(0x0483, "Multi Care Systems B.V.");+ vendorModels.put(0x0484, "Revol Technologies Inc");+ vendorModels.put(0x0485, "SKIDATA AG");+ vendorModels.put(0x0486, "DEV TECNOLOGIA INDUSTRIA,COMERCIO E MANUTENCAO DE EQUIPAMENTOS LTDA. - ME");+ vendorModels.put(0x0487, "Centrica Connected Home");+ vendorModels.put(0x0488, "Automotive Data Solutions Inc");+ vendorModels.put(0x0489, "Igarashi Engineering");+ vendorModels.put(0x048A, "Taelek Oy");+ vendorModels.put(0x048B, "CP Electronics Limited");+ vendorModels.put(0x048C, "Vectronix AG");+ vendorModels.put(0x048D, "S-Labs Sp. z o.o.");+ vendorModels.put(0x048E, "Companion Medical, Inc.");+ vendorModels.put(0x048F, "BlueKitchen GmbH");+ vendorModels.put(0x0490, "Matting AB");+ vendorModels.put(0x0491, "SOREX - Wireless Solutions GmbH");+ vendorModels.put(0x0492, "ADC Technology, Inc.");+ vendorModels.put(0x0493, "Lynxemi Pte Ltd");+ vendorModels.put(0x0494, "SENNHEISER electronic GmbH & Co. KG");+ vendorModels.put(0x0495, "LMT Mercer Group, Inc");+ vendorModels.put(0x0496, "Polymorphic Labs LLC");+ vendorModels.put(0x0497, "Cochlear Limited");+ vendorModels.put(0x0498, "METER Group, Inc. USA");+ vendorModels.put(0x0499, "Ruuvi Innovations Ltd.");+ vendorModels.put(0x049A, "Situne AS");+ vendorModels.put(0x049B, "nVisti,LLC");+ vendorModels.put(0x049C, "DyOcean");+ vendorModels.put(0x049D, "Uhlmann & Zacher GmbH");+ vendorModels.put(0x049E, "AND!XOR LLC");+ vendorModels.put(0x049F, "tictote AB");+ vendorModels.put(0x04A0, "Vypin,LLC");+ vendorModels.put(0x04A1, "PNI Sensor Corporation");+ vendorModels.put(0x04A2, "ovrEngineered,LLC");+ vendorModels.put(0x04A3, "GT-tronics HK Ltd");+ vendorModels.put(0x04A4, "Herbert Waldmann GmbH & Co. KG");+ vendorModels.put(0x04A5, "Guangzhou FiiO Electronics Technology Co.);Ltd");+ vendorModels.put(0x04A6, "Vinetech Co.,Ltd");+ vendorModels.put(0x04A7, "Dallas Logic Corporation");+ vendorModels.put(0x04A8, "BioTex, Inc.");+ vendorModels.put(0x04A9, "DISCOVERY SOUND TECHNOLOGY,LLC");+ vendorModels.put(0x04AA, "LINKIO SAS");+ vendorModels.put(0x04AB, "Harbortronics, Inc.");+ vendorModels.put(0x04AC, "Undagrid B.V.");+ vendorModels.put(0x04AD, "Shure Inc");+ vendorModels.put(0x04AE, "ERM Electronic Systems LTD");+ vendorModels.put(0x04AF, "BIOROWER Handelsagentur GmbH");+ vendorModels.put(0x04B0, "Weba Sport und Med. Artikel GmbH");+ vendorModels.put(0x04B1, "Kartographers Technologies Pvt. Ltd.");+ vendorModels.put(0x04B2, "The Shadow on the Moon");+ vendorModels.put(0x04B3, "mobike (Hong Kong,Limited");+ vendorModels.put(0x04B4, "Inuheat Group AB");+ vendorModels.put(0x04B5, "Swiftronix AB");+ vendorModels.put(0x04B6, "Diagnoptics Technologies");+ vendorModels.put(0x04B7, "Analog Devices, Inc.");+ vendorModels.put(0x04B8, "Soraa Inc.");+ vendorModels.put(0x04B9, "CSR Building Products Limited");+ vendorModels.put(0x04BA, "Crestron Electronics, Inc.");+ vendorModels.put(0x04BB, "Neatebox Ltd");+ vendorModels.put(0x04BC, "Draegerwerk AG & Co. KGaA");+ vendorModels.put(0x04BD, "AlbynMedical");+ vendorModels.put(0x04BE, "Averos FZCO");+ vendorModels.put(0x04BF, "VIT Initiative,LLC");+ vendorModels.put(0x04C0, "Statsports International");+ vendorModels.put(0x04C1, "Sospitas,s.r.o.");+ vendorModels.put(0x04C2, "Dmet Products Corp.");+ vendorModels.put(0x04C3, "Mantracourt Electronics Limited");+ vendorModels.put(0x04C4, "TeAM Hutchins AB");+ vendorModels.put(0x04C5, "Seibert Williams Glass,LLC");+ vendorModels.put(0x04C6, "Insta GmbH");+ vendorModels.put(0x04C7, "Svantek Sp. z o.o.");+ vendorModels.put(0x04C8, "Shanghai Flyco Electrical Appliance Co.,Ltd.");+ vendorModels.put(0x04C9, "Thornwave Labs Inc");+ vendorModels.put(0x04CA, "Steiner-Optik GmbH");+ vendorModels.put(0x04CB, "Novo Nordisk A/S");+ vendorModels.put(0x04CC, "Enflux Inc.");+ vendorModels.put(0x04CD, "Safetech Products LLC");+ vendorModels.put(0x04CE, "GOOOLED S.R.L.");+ vendorModels.put(0x04CF, "DOM Sicherheitstechnik GmbH & Co. KG");+ vendorModels.put(0x04D0, "Olympus Corporation");+ vendorModels.put(0x04D1, "KTS GmbH");+ vendorModels.put(0x04D2, "Anloq Technologies Inc.");+ vendorModels.put(0x04D3, "Queercon, Inc");+ vendorModels.put(0x04D4, "5th Element Ltd");+ vendorModels.put(0x04D5, "Gooee Limited");+ vendorModels.put(0x04D6, "LUGLOC LLC");+ vendorModels.put(0x04D7, "Blincam, Inc.");+ vendorModels.put(0x04D8, "FUJIFILM Corporation");+ vendorModels.put(0x04D9, "RandMcNally");+ vendorModels.put(0x04DA, "Franceschi Marina snc");+ vendorModels.put(0x04DB, "Engineered Audio,LLC.");+ vendorModels.put(0x04DC, "IOTTIVE (OPC,PRIVATE LIMITED");+ vendorModels.put(0x04DD, "4MOD Technology");+ vendorModels.put(0x04DE, "Lutron Electronics Co., Inc.");+ vendorModels.put(0x04DF, "Emerson");+ vendorModels.put(0x04E0, "Guardtec, Inc.");+ vendorModels.put(0x04E1, "REACTEC LIMITED");+ vendorModels.put(0x04E2, "EllieGrid");+ vendorModels.put(0x04E3, "Under Armour");+ vendorModels.put(0x04E4, "Woodenshark");+ vendorModels.put(0x04E5, "Avack Oy");+ vendorModels.put(0x04E6, "Smart Solution Technology, Inc.");+ vendorModels.put(0x04E7, "REHABTRONICS INC.");+ vendorModels.put(0x04E8, "STABILO International");+ vendorModels.put(0x04E9, "Busch Jaeger Elektro GmbH");+ vendorModels.put(0x04EA, "Pacific Bioscience Laboratories, Inc");+ vendorModels.put(0x04EB, "Bird Home Automation GmbH");+ vendorModels.put(0x04EC, "Motorola Solutions");+ vendorModels.put(0x04ED, "R9 Technology, Inc.");+ vendorModels.put(0x04EE, "Auxivia");+ vendorModels.put(0x04EF, "DaisyWorks, Inc");+ vendorModels.put(0x04F0, "Kosi Limited");+ vendorModels.put(0x04F1, "Theben AG");+ vendorModels.put(0x04F2, "InDreamer Techsol Private Limited");+ vendorModels.put(0x04F3, "Cerevast Medical");+ vendorModels.put(0x04F4, "ZanCompute Inc.");+ vendorModels.put(0x04F5, "Pirelli Tyre S.P.A.");+ vendorModels.put(0x04F6, "McLear Limited");+ vendorModels.put(0x04F7, "Shenzhen Huiding Technology Co.);Ltd.");+ vendorModels.put(0x04F8, "Convergence Systems Limited");+ vendorModels.put(0x04F9, "Interactio");+ vendorModels.put(0x04FA, "Androtec GmbH");+ vendorModels.put(0x04FB, "Benchmark Drives GmbH & Co. KG");+ vendorModels.put(0x04FC, "SwingLync L. L. C.");+ vendorModels.put(0x04FD, "Tapkey GmbH");+ vendorModels.put(0x04FE, "Woosim Systems Inc.");+ vendorModels.put(0x04FF, "Microsemi Corporation");+ vendorModels.put(0x0500, "Wiliot LTD.");+ vendorModels.put(0x0501, "Polaris IND");+ vendorModels.put(0x0502, "Specifi-Kali LLC");+ vendorModels.put(0x0503, "Locoroll, Inc");+ vendorModels.put(0x0504, "PHYPLUS Inc");+ vendorModels.put(0x0505, "Inplay Technologies LLC");+ vendorModels.put(0x0506, "Hager");+ vendorModels.put(0x0507, "Yellowcog");+ vendorModels.put(0x0508, "Axes System sp. z o. o.");+ vendorModels.put(0x0509, "myLIFTER Inc.");+ vendorModels.put(0x050A, "Shake-on B.V.");+ vendorModels.put(0x050B, "Vibrissa Inc.");+ vendorModels.put(0x050C, "OSRAM GmbH");+ vendorModels.put(0x050D, "TRSystems GmbH");+ vendorModels.put(0x050E, "Yichip Microelectronics (Hangzhou,Co.);Ltd.");+ vendorModels.put(0x050F, "Foundation Engineering LLC");+ vendorModels.put(0x0510, "UNI-ELECTRONICS, Inc.");+ vendorModels.put(0x0511, "Brookfield Equinox LLC");+ vendorModels.put(0x0512, "Soprod SA");+ vendorModels.put(0x0513, "9974091 Canada Inc.");+ vendorModels.put(0x0514, "FIBRO GmbH");+ vendorModels.put(0x0515, "RB Controls Co.,Ltd.");+ vendorModels.put(0x0516, "Footmarks");+ vendorModels.put(0x0517, "Amcore AB");+ vendorModels.put(0x0518, "MAMORIO.inc");+ vendorModels.put(0x0519, "Tyto Life LLC");+ vendorModels.put(0x051A, "Leica Camera AG");+ vendorModels.put(0x051B, "Angee Technologies Ltd.");+ vendorModels.put(0x051C, "EDPS");+ vendorModels.put(0x051D, "OFF Line Co.,Ltd.");+ vendorModels.put(0x051E, "Detect Blue Limited");+ vendorModels.put(0x051F, "Setec Pty Ltd");+ vendorModels.put(0x0520, "Target Corporation");+ vendorModels.put(0x0521, "IAI Corporation");+ vendorModels.put(0x0522, "NS Tech, Inc.");+ vendorModels.put(0x0523, "MTG Co.,Ltd.");+ vendorModels.put(0x0524, "Hangzhou iMagic Technology Co.,Ltd");+ vendorModels.put(0x0525, "HONGKONG NANO IC TECHNOLOGIES CO.,LIMITED");+ vendorModels.put(0x0526, "Honeywell International Inc.");+ vendorModels.put(0x0527, "Albrecht JUNG");+ vendorModels.put(0x0528, "Lunera Lighting Inc.");+ vendorModels.put(0x0529, "Lumen UAB");+ vendorModels.put(0x052A, "Keynes Controls Ltd");+ vendorModels.put(0x052B, "Novartis AG");+ vendorModels.put(0x052C, "Geosatis SA");+ vendorModels.put(0x052D, "EXFO, Inc.");+ vendorModels.put(0x052E, "LEDVANCE GmbH");+ vendorModels.put(0x052F, "Center ID Corp.");+ vendorModels.put(0x0530, "Adolene, Inc.");+ vendorModels.put(0x0531, "D&M Holdings Inc.");+ vendorModels.put(0x0532, "CRESCO Wireless, Inc.");+ vendorModels.put(0x0533, "Nura Operations Pty Ltd");+ vendorModels.put(0x0534, "Frontiergadget, Inc.");+ vendorModels.put(0x0535, "Smart Component Technologies Limited");+ vendorModels.put(0x0536, "ZTR Control Systems LLC");+ vendorModels.put(0x0537, "MetaLogics Corporation");+ vendorModels.put(0x0538, "Medela AG");+ vendorModels.put(0x0539, "OPPLE Lighting Co.,Ltd");+ vendorModels.put(0x053A, "Savitech Corp.);");+ vendorModels.put(0x053B, "prodigy");+ vendorModels.put(0x053C, "Screenovate Technologies Ltd");+ vendorModels.put(0x053D, "TESA SA");+ vendorModels.put(0x053E, "CLIM8 LIMITED");+ vendorModels.put(0x053F, "Silergy Corp");+ vendorModels.put(0x0540, "SilverPlus, Inc");+ vendorModels.put(0x0541, "Sharknet srl");+ vendorModels.put(0x0542, "Mist Systems, Inc.");+ vendorModels.put(0x0543, "MIWA LOCK CO.);Ltd");+ vendorModels.put(0x0544, "OrthoSensor, Inc.");+ vendorModels.put(0x0545, "Candy Hoover Group s.r.l");+ vendorModels.put(0x0546, "Apexar Technologies S.A.");+ vendorModels.put(0x0547, "LOGICDATA d.o.o.");+ vendorModels.put(0x0548, "Knick Elektronische Messgeraete GmbH & Co. KG");+ vendorModels.put(0x0549, "Smart Technologies and Investment Limited");+ vendorModels.put(0x054A, "Linough Inc.");+ vendorModels.put(0x054B, "Advanced Electronic Designs, Inc.");+ vendorModels.put(0x054C, "Carefree Scott Fetzer Co Inc");+ vendorModels.put(0x054D, "Sensome");+ vendorModels.put(0x054E, "FORTRONIK storitve d.o.o.");+ vendorModels.put(0x054F, "Sinnoz");+ vendorModels.put(0x0550, "Versa Networks, Inc.");+ vendorModels.put(0x0551, "Sylero");+ vendorModels.put(0x0552, "Avempace SARL");+ vendorModels.put(0x0553, "Nintendo Co.,Ltd.");+ vendorModels.put(0x0554, "National Instruments");+ vendorModels.put(0x0555, "KROHNE Messtechnik GmbH");+ vendorModels.put(0x0556, "Otodynamics Ltd");+ vendorModels.put(0x0557, "Arwin Technology Limited");+ vendorModels.put(0x0558, "benegear, Inc.");+ vendorModels.put(0x0559, "Newcon Optik");+ vendorModels.put(0x055A, "CANDY HOUSE, Inc.");+ vendorModels.put(0x055B, "FRANKLIN TECHNOLOGY INC");+ vendorModels.put(0x055C, "Lely");+ vendorModels.put(0x055D, "Valve Corporation");+ vendorModels.put(0x055E, "Hekatron Vertriebs GmbH");+ vendorModels.put(0x055F, "PROTECH S.A.S. DI GIRARDI ANDREA & C.");+ vendorModels.put(0x0560, "Sarita CareTech IVS");+ vendorModels.put(0x0561, "Finder S.p.A.");+ vendorModels.put(0x0562, "Thalmic Labs Inc.");+ vendorModels.put(0x0563, "Steinel Vertrieb GmbH");+ vendorModels.put(0x0564, "Beghelli Spa");+ vendorModels.put(0x0565, "Beijing Smartspace Technologies Inc.");+ vendorModels.put(0x0566, "CORE TRANSPORT TECHNOLOGIES NZ LIMITED");+ vendorModels.put(0x0567, "Xiamen Everesports Goods Co.,Ltd");+ vendorModels.put(0x0568, "Bodyport Inc.");+ vendorModels.put(0x0569, "Audionics System, Inc.");+ vendorModels.put(0x056A, "Flipnavi Co.);Ltd.");+ vendorModels.put(0x056B, "Rion Co.,Ltd.");+ vendorModels.put(0x056C, "Long AddressRange Systems,LLC");+ vendorModels.put(0x056D, "Redmond Industrial Group LLC");+ vendorModels.put(0x056E, "VIZPIN INC.");+ vendorModels.put(0x056F, "BikeFinder AS");+ vendorModels.put(0x0570, "Consumer Sleep Solutions LLC");+ vendorModels.put(0x0571, "PSIKICK, Inc.");+ vendorModels.put(0x0572, "AntTail.com");+ vendorModels.put(0x0573, "Lighting Science Group Corp.");+ vendorModels.put(0x0574, "AFFORDABLE ELECTRONICS INC");+ vendorModels.put(0x0575, "Integral Memroy Plc");+ vendorModels.put(0x0576, "Globalstar, Inc.");+ vendorModels.put(0x0577, "True Wearables, Inc.");+ vendorModels.put(0x0578, "Wellington Drive Technologies Ltd");+ vendorModels.put(0x0579, "Ensemble Tech Private Limited");+ vendorModels.put(0x057A, "OMNI Remotes");+ vendorModels.put(0x057B, "Duracell U.S. Operations Inc.");+ vendorModels.put(0x057C, "Toor Technologies LLC");+ vendorModels.put(0x057D, "Instinct Performance");+ vendorModels.put(0x057E, "Beco, Inc");+ vendorModels.put(0x057F, "Scuf Gaming International,LLC");+ vendorModels.put(0x0580, "ARANZ Medical Limited");+ vendorModels.put(0x0581, "LYS TECHNOLOGIES LTD");+ vendorModels.put(0x0582, "Breakwall Analytics,LLC");+ vendorModels.put(0x0583, "Code Blue Communications");+ vendorModels.put(0x0584, "Gira Giersiepen GmbH & Co. KG");+ vendorModels.put(0x0585, "Hearing Lab Technology");+ vendorModels.put(0x0586, "LEGRAND");+ vendorModels.put(0x0587, "Derichs GmbH");+ vendorModels.put(0x0588, "ALT-TEKNIK LLC");+ vendorModels.put(0x0589, "Star Technologies");+ vendorModels.put(0x058A, "START TODAY CO.);LTD.");+ vendorModels.put(0x058B, "Maxim Integrated Products");+ vendorModels.put(0x058C, "MERCK Kommanditgesellschaft auf Aktien");+ vendorModels.put(0x058D, "Jungheinrich Aktiengesellschaft");+ vendorModels.put(0x058E, "Oculus VR,LLC");+ vendorModels.put(0x058F, "HENDON SEMICONDUCTORS PTY LTD");+ vendorModels.put(0x0590, "Pur3 Ltd");+ vendorModels.put(0x0591, "Viasat Group S.p.A.");+ vendorModels.put(0x0592, "IZITHERM");+ vendorModels.put(0x0593, "Spaulding Clinical Research");+ vendorModels.put(0x0594, "Kohler Company");+ vendorModels.put(0x0595, "Inor Process AB");+ vendorModels.put(0x0596, "My Smart Blinds");+ vendorModels.put(0x0597, "RadioPulse Inc");+ vendorModels.put(0x0598, "rapitag GmbH");+ vendorModels.put(0x0599, "Lazlo326,LLC.");+ vendorModels.put(0x059A, "Teledyne Lecroy, Inc.");+ vendorModels.put(0x059B, "Dataflow Systems Limited");+ vendorModels.put(0x059C, "Macrogiga Electronics");+ vendorModels.put(0x059D, "Tandem Diabetes Care");+ vendorModels.put(0x059E, "Polycom, Inc.");+ vendorModels.put(0x059F, "Fisher & Paykel Healthcare");+ vendorModels.put(0x05A0, "RCP Software Oy");+ vendorModels.put(0x05A1, "Shanghai Xiaoyi Technology Co.);Ltd.");+ vendorModels.put(0x05A2, "ADHERIUM(NZ,LIMITED");+ vendorModels.put(0x05A3, "Axiomware Systems Incorporated");+ vendorModels.put(0x05A4, "O. E. M. Controls, Inc.");+ vendorModels.put(0x05A5, "Kiiroo BV");+ vendorModels.put(0x05A6, "Telecon Mobile Limited");+ vendorModels.put(0x05A7, "Sonos Inc");+ vendorModels.put(0x05A8, "Tom Allebrandi Consulting");+ vendorModels.put(0x05A9, "Monidor");+ vendorModels.put(0x05AA, "Tramex Limited");+ vendorModels.put(0x05AB, "Nofence AS");+ vendorModels.put(0x05AC, "GoerTek Dynaudio Co.,Ltd.");+ vendorModels.put(0x05AD, "INIA");+ vendorModels.put(0x05AE, "CARMATE MFG.CO.);LTD");+ vendorModels.put(0x05AF, "ONvocal");+ vendorModels.put(0x05B0, "NewTec GmbH");+ vendorModels.put(0x05B1, "Medallion Instrumentation Systems");+ vendorModels.put(0x05B2, "CAREL INDUSTRIES S.P.A.");+ vendorModels.put(0x05B3, "Parabit Systems, Inc.");+ vendorModels.put(0x05B4, "White Horse Scientific ltd");+ vendorModels.put(0x05B5, "verisilicon");+ vendorModels.put(0x05B6, "Elecs Industry Co.);Ltd.");+ vendorModels.put(0x05B7, "Beijing Pinecone Electronics Co.);Ltd.");+ vendorModels.put(0x05B8, "Ambystoma Labs Inc.");+ vendorModels.put(0x05B9, "Suzhou Pairlink Network Technology");+ vendorModels.put(0x05BA, "igloohome");+ vendorModels.put(0x05BB, "Oxford Metrics plc");+ vendorModels.put(0x05BC, "Leviton Mfg. Co., Inc.");+ vendorModels.put(0x05BD, "ULC Robotics Inc.");+ vendorModels.put(0x05BE, "RFID Global by Softwork SrL");+ vendorModels.put(0x05BF, "Real-World-Systems Corporation");+ vendorModels.put(0x05C0, "Nalu Medical, Inc.");+ vendorModels.put(0x05C1, "P.I.Engineering");+ vendorModels.put(0x05C2, "Grote Industries");+ vendorModels.put(0x05C3, "Runtime, Inc.");+ vendorModels.put(0x05C4, "Codecoup sp. z o.o. sp. k.");+ vendorModels.put(0x05C5, "SELVE GmbH & Co. KG");+ vendorModels.put(0x05C6, "Smart Animal Training Systems,LLC");+ vendorModels.put(0x05C7, "Lippert Components, Inc");+ vendorModels.put(0x05C8, "SOMFY SAS");+ vendorModels.put(0x05C9, "TBS Electronics B.V.");+ vendorModels.put(0x05CA, "MHL Custom Inc");+ vendorModels.put(0x05CB, "LucentWear LLC");+ vendorModels.put(0x05CC, "WATTS ELECTRONICS");+ vendorModels.put(0x05CD, "RJ Brands LLC");+ vendorModels.put(0x05CE, "V-ZUG Ltd");+ vendorModels.put(0x05CF, "Biowatch SA");+ vendorModels.put(0x05D0, "Anova Applied Electronics");+ vendorModels.put(0x05D1, "Lindab AB");+ vendorModels.put(0x05D2, "frogblue TECHNOLOGY GmbH");+ vendorModels.put(0x05D3, "Acurable Limited");+ vendorModels.put(0x05D4, "LAMPLIGHT Co.,Ltd.");+ vendorModels.put(0x05D5, "TEGAM, Inc.");+ vendorModels.put(0x05D6, "Zhuhai Jieli technology Co.);Ltd");+ vendorModels.put(0x05D7, "modum.io AG");+ vendorModels.put(0x05D8, "Farm Jenny LLC");+ vendorModels.put(0x05D9, "Toyo Electronics Corporation");+ vendorModels.put(0x05DA, "Applied Neural Research Corp");+ vendorModels.put(0x05DB, "Avid Identification Systems, Inc.");+ vendorModels.put(0x05DC, "Petronics Inc.");+ vendorModels.put(0x05DD, "essentim GmbH");+ vendorModels.put(0x05DE, "QT Medical INC.");+ vendorModels.put(0x05DF, "VIRTUALCLINIC.DIRECT LIMITED");+ vendorModels.put(0x05E0, "Viper Design LLC");+ vendorModels.put(0x05E1, "Human, Incorporated");+ vendorModels.put(0x05E2, "stAPPtronics GmbH");+ vendorModels.put(0x05E3, "Elemental Machines, Inc.");+ vendorModels.put(0x05E4, "Taiyo Yuden Co.,Ltd");+ vendorModels.put(0x05E5, "INEO ENERGY& SYSTEMS");+ vendorModels.put(0x05E6, "Motion Instruments Inc.");+ vendorModels.put(0x05E7, "PressurePro");+ vendorModels.put(0x05E8, "COWBOY");+ vendorModels.put(0x05E9, "iconmobile GmbH");+ vendorModels.put(0x05EA, "ACS-Control-System GmbH");+ vendorModels.put(0x05EB, "Bayerische Motoren Werke AG");+ vendorModels.put(0x05EC, "Gycom Svenska AB");+ vendorModels.put(0x05ED, "Fuji Xerox Co.,Ltd");+ vendorModels.put(0x05EE, "Glide Inc.");+ vendorModels.put(0x05EF, "SIKOM AS");+ vendorModels.put(0x05F0, "beken");+ vendorModels.put(0x05F1, "The Linux Foundation");+ vendorModels.put(0x05F2, "Try and E CO.);LTD.");+ vendorModels.put(0x05F3, "SeeScan");+ vendorModels.put(0x05F4, "Clearity,LLC");+ vendorModels.put(0x05F5, "GS TAG");+ vendorModels.put(0x05F6, "DPTechnics");+ vendorModels.put(0x05F7, "TRACMO, Inc.");+ vendorModels.put(0x05F8, "Anki Inc.");+ vendorModels.put(0x05F9, "Hagleitner Hygiene International GmbH");+ vendorModels.put(0x05FA, "Konami Sports Life Co.,Ltd.");+ vendorModels.put(0x05FB, "Arblet Inc.");+ vendorModels.put(0x05FC, "Masbando GmbH");+ vendorModels.put(0x05FD, "Innoseis");+ vendorModels.put(0x05FE, "Niko");+ vendorModels.put(0x05FF, "Wellnomics Ltd");+ vendorModels.put(0x0600, "iRobot Corporation");+ vendorModels.put(0x0601, "Schrader Electronics");+ vendorModels.put(0x0602, "Geberit International AG");+ vendorModels.put(0x0603, "Fourth Evolution Inc");+ vendorModels.put(0x0604, "Cell2Jack LLC");+ vendorModels.put(0x0605, "FMW electronic Futterer u. Maier-Wolf OHG");+ vendorModels.put(0x0606, "John Deere");+ vendorModels.put(0x0607, "Rookery Technology Ltd");+ vendorModels.put(0x0608, "KeySafe-Cloud");+ vendorModels.put(0x0609, "Bchi Labortechnik AG");+ vendorModels.put(0x060A, "IQAir AG");+ vendorModels.put(0x060B, "Triax Technologies Inc");+ vendorModels.put(0x060C, "Vuzix Corporation");+ vendorModels.put(0x060D, "TDK Corporation");+ vendorModels.put(0x060E, "Blueair AB");+ vendorModels.put(0x060F, "Philips Lighting B.V.");+ vendorModels.put(0x0610, "ADH GUARDIAN USA LLC");+ vendorModels.put(0x0611, "Beurer GmbH");+ vendorModels.put(0x0612, "Playfinity AS");+ vendorModels.put(0x0613, "Hans Dinslage GmbH");+ vendorModels.put(0x0614, "OnAsset Intelligence, Inc.");+ vendorModels.put(0x0615, "INTER ACTION Corporation");+ vendorModels.put(0x0616, "OS42 UG (haftungsbeschraenkt);");+ vendorModels.put(0x0617, "WIZCONNECTED COMPANY LIMITED");+ vendorModels.put(0x0618, "Audio-Technica Corporation");+ vendorModels.put(0x0619, "Six Guys Labs, s.r.o.");+ vendorModels.put(0x061A, "R.W. Beckett Corporation");+ vendorModels.put(0x061B, "silex technology, inc.");+ vendorModels.put(0x061C, "Univations Limited");+ vendorModels.put(0x061D, "SENS Innovation ApS");+ vendorModels.put(0x061E, "Diamond Kinetics, Inc.");+ vendorModels.put(0x061F, "Phrame Inc.");+ vendorModels.put(0x0620, "Forciot Oy");+ vendorModels.put(0x0621, "Noordung d.o.o.");+ vendorModels.put(0x0622, "Beam Labs, LLC");+ vendorModels.put(0x0623, "Philadelphia Scientific (U.K.) Limited");+ vendorModels.put(0x0624, "Biovotion AG");+ vendorModels.put(0x0625, "Square Panda, Inc.");+ vendorModels.put(0x0626, "Amplifico");+ vendorModels.put(0x0627, "WEG S.A.");+ vendorModels.put(0x0628, "Ensto Oy");+ vendorModels.put(0x0629, "PHONEPE PVT LTD");+ vendorModels.put(0x062A, "Lunatico Astronomia SL");+ vendorModels.put(0x062B, "MinebeaMitsumi Inc.");+ vendorModels.put(0x062C, "ASPion GmbH");+ vendorModels.put(0x062D, "Vossloh-Schwabe Deutschland GmbH");+ vendorModels.put(0x062E, "Procept");+ vendorModels.put(0x062F, "ONKYO Corporation");+ vendorModels.put(0x0630, "Asthrea D.O.O.");+ vendorModels.put(0x0631, "Fortiori Design LLC");+ vendorModels.put(0x0632, "Hugo Muller GmbH & Co KG");+ vendorModels.put(0x0633, "Wangi Lai PLT");+ vendorModels.put(0x0634, "Fanstel Corp");+ vendorModels.put(0x0635, "Crookwood");+ vendorModels.put(0x0636, "ELECTRONICA INTEGRAL DE SONIDO S.A.");+ vendorModels.put(0x0637, "GiP Innovation Tools GmbH");+ vendorModels.put(0x0638, "LX SOLUTIONS PTY LIMITED");+ vendorModels.put(0x0639, "Shenzhen Minew Technologies Co., Ltd.");+ vendorModels.put(0x063A, "Prolojik Limited");+ vendorModels.put(0x063B, "Kromek Group Plc");+ vendorModels.put(0x063C, "Contec Medical Systems Co., Ltd.");+ vendorModels.put(0x063D, "Xradio Technology Co.,Ltd.");+ vendorModels.put(0x063E, "The Indoor Lab, LLC");+ vendorModels.put(0x063F, "LDL TECHNOLOGY");+ vendorModels.put(0x0640, "Parkifi");+ vendorModels.put(0x0641, "Revenue Collection Systems FRANCE SAS");+ vendorModels.put(0x0642, "Bluetrum Technology Co.,Ltd");+ vendorModels.put(0x0643, "makita corporation");+ vendorModels.put(0x0644, "Apogee Instruments");+ vendorModels.put(0x0645, "BM3");+ vendorModels.put(0x0646, "SGV Group Holding GmbH & Co. KG");+ vendorModels.put(0x0647, "MED-EL");+ vendorModels.put(0x0648, "Ultune Technologies");+ vendorModels.put(0x0649, "Ryeex Technology Co.,Ltd.");+ vendorModels.put(0x064A, "Open Research Institute, Inc.");+ vendorModels.put(0x064B, "Scale-Tec, Ltd");+ vendorModels.put(0x064C, "Zumtobel Group AG");+ vendorModels.put(0x064D, "iLOQ Oy");+ vendorModels.put(0x064E, "KRUXWorks Technologies Private Limited");+ vendorModels.put(0x064F, "Digital Matter Pty Ltd");+ vendorModels.put(0x0650, "Coravin, Inc.");+ vendorModels.put(0x0651, "Stasis Labs, Inc.");+ vendorModels.put(0x0652, "ITZ Innovations- und Technologiezentrum GmbH");+ vendorModels.put(0x0653, "Meggitt SA");+ vendorModels.put(0x0654, "Ledlenser GmbH & Co. KG");+ vendorModels.put(0x0655, "Renishaw PLC");+ vendorModels.put(0x0656, "ZhuHai AdvanPro Technology Company Limited");+ vendorModels.put(0x0657, "Meshtronix Limited");+ vendorModels.put(0x0658, "Payex Norge AS");+ vendorModels.put(0x0659, "UnSeen Technologies Oy");+ vendorModels.put(0x065A, "Zound Industries International AB");+ vendorModels.put(0x065B, "Sesam Solutions BV");+ vendorModels.put(0x065C, "PixArt Imaging Inc.");+ vendorModels.put(0x065D, "Panduit Corp.");+ vendorModels.put(0x065E, "Alo AB");+ vendorModels.put(0x065F, "Ricoh Company Ltd");+ vendorModels.put(0x0660, "RTC Industries, Inc.");+ vendorModels.put(0x0661, "Mode Lighting Limited");+ vendorModels.put(0x0662, "Particle Industries, Inc.");+ vendorModels.put(0x0663, "Advanced Telemetry Systems, Inc.");+ vendorModels.put(0x0664, "RHA TECHNOLOGIES LTD");+ vendorModels.put(0x0665, "Pure International Limited");+ vendorModels.put(0x0666, "WTO Werkzeug-Einrichtungen GmbH");+ vendorModels.put(0x0667, "Spark Technology Labs Inc.");+ vendorModels.put(0x0668, "Bleb Technology srl");+ vendorModels.put(0x0669, "Livanova USA, Inc.");+ vendorModels.put(0x066A, "Brady Worldwide Inc.");+ vendorModels.put(0x066B, "DewertOkin GmbH");+ vendorModels.put(0x066C, "Ztove ApS");+ vendorModels.put(0x066D, "Venso EcoSolutions AB");+ vendorModels.put(0x066E, "Eurotronik Kranj d.o.o.");+ vendorModels.put(0x066F, "Hug Technology Ltd");+ vendorModels.put(0x0670, "Gema Switzerland GmbH");+ vendorModels.put(0x0671, "Buzz Products Ltd.");+ vendorModels.put(0x0672, "Kopi");+ vendorModels.put(0x0673, "Innova Ideas Limited");+ vendorModels.put(0x0674, "BeSpoon");+ vendorModels.put(0x0675, "Deco Enterprises, Inc.");+ vendorModels.put(0x0676, "Expai Solutions Private Limited");+ vendorModels.put(0x0677, "Innovation First, Inc.");+ vendorModels.put(0x0678, "SABIK Offshore GmbH");+ vendorModels.put(0x0679, "4iiii Innovations Inc.");+ vendorModels.put(0x067A, "The Energy Conservatory, Inc.");+ vendorModels.put(0x067B, "I.FARM, INC.");+ vendorModels.put(0x067C, "Tile, Inc.");+ vendorModels.put(0x067D, "Form Athletica Inc.");+ vendorModels.put(0x067E, "MbientLab Inc");+ vendorModels.put(0x067F, "NETGRID S.N.C. DI BISSOLI MATTEO, CAMPOREALE SIMONE, TOGNETTI FEDERICO");+ vendorModels.put(0x0680, "Mannkind Corporation");+ vendorModels.put(0x0681, "Trade FIDES a.s.");+ vendorModels.put(0x0682, "Photron Limited");+ vendorModels.put(0x0683, "Eltako GmbH");+ vendorModels.put(0x0684, "Dermalapps, LLC");+ vendorModels.put(0x0685, "Greenwald Industries");+ vendorModels.put(0x0686, "inQs Co., Ltd.");+ vendorModels.put(0x0687, "Cherry GmbH");+ vendorModels.put(0x0688, "Amsted Digital Solutions Inc.");+ vendorModels.put(0x0689, "Tacx b.v.");+ vendorModels.put(0x068A, "Raytac Corporation");+ vendorModels.put(0x068B, "Jiangsu Teranovo Tech Co., Ltd.");+ vendorModels.put(0x068C, "Changzhou Sound Dragon Electronics and Acoustics Co., Ltd");+ vendorModels.put(0x068D, "JetBeep Inc.");+ vendorModels.put(0x068E, "Razer Inc.");+ vendorModels.put(0x068F, "JRM Group Limited");+ vendorModels.put(0x0690, "Eccrine Systems, Inc.");+ vendorModels.put(0x0691, "Curie Point AB");+ vendorModels.put(0x0692, "Georg Fischer AG");+ vendorModels.put(0x0693, "Hach - Danaher");+ vendorModels.put(0x0694, "T&A Laboratories LLC");+ vendorModels.put(0x0695, "Koki Holdings Co., Ltd.");+ vendorModels.put(0x0696, "Gunakar Private Limited");+ vendorModels.put(0x0697, "Stemco Products Inc");+ vendorModels.put(0x0698, "Wood IT Security, LLC");+ vendorModels.put(0x0699, "RandomLab SAS");+ vendorModels.put(0x069A, "Adero, Inc. (formerly as TrackR, Inc.)");+ vendorModels.put(0x069B, "Dragonchip Limited");+ vendorModels.put(0x069C, "Noomi AB");+ vendorModels.put(0x069D, "Vakaros LLC");+ vendorModels.put(0x069E, "Delta Electronics, Inc.");+ vendorModels.put(0x069F, "FlowMotion Technologies AS");+ vendorModels.put(0x06A0, "OBIQ Location Technology Inc.");+ vendorModels.put(0x06A1, "Cardo Systems, Ltd");+ vendorModels.put(0x06A2, "Globalworx GmbH");+ vendorModels.put(0x06A3, "Nymbus, LLC");+ vendorModels.put(0x06A4, "Sanyo Techno Solutions Tottori Co., Ltd.");+ vendorModels.put(0x06A5, "TEKZITEL PTY LTD");+ vendorModels.put(0x06A6, "Roambee Corporation");+ vendorModels.put(0x06A7, "Chipsea Technologies (ShenZhen) Corp.");+ vendorModels.put(0x06A8, "GD Midea Air-Conditioning Equipment Co., Ltd.");+ vendorModels.put(0x06A9, "Soundmax Electronics Limited");+ vendorModels.put(0x06AA, "Produal Oy");+ vendorModels.put(0x06AB, "HMS Industrial Networks AB");+ vendorModels.put(0x06AC, "Ingchips Technology Co., Ltd.");+ vendorModels.put(0x06AD, "InnovaSea Systems Inc.");+ vendorModels.put(0x06AE, "SenseQ Inc.");+ vendorModels.put(0x06AF, "Shoof Technologies");+ vendorModels.put(0x06B0, "BRK Brands, Inc.");+ vendorModels.put(0x06B1, "SimpliSafe, Inc.");+ vendorModels.put(0x06B2, "Tussock Innovation 2013 Limited");+ vendorModels.put(0x06B3, "The Hablab ApS");+ vendorModels.put(0x06B4, "Sencilion Oy");+ vendorModels.put(0x06B5, "Wabilogic Ltd.");+ vendorModels.put(0x06B6, "Sociometric Solutions, Inc.");+ vendorModels.put(0x06B7, "iCOGNIZE GmbH");+ vendorModels.put(0x06B8, "ShadeCraft, Inc");+ vendorModels.put(0x06B9, "Beflex Inc.");+ vendorModels.put(0x06BA, "Beaconzone Ltd");+ vendorModels.put(0x06BB, "Leaftronix Analogic Solutions Private Limited");+ vendorModels.put(0x06BC, "TWS Srl");+ vendorModels.put(0x06BD, "ABB Oy");+ vendorModels.put(0x06BE, "HitSeed Oy");+ vendorModels.put(0x06BF, "Delcom Products Inc.");+ vendorModels.put(0x06C0, "CAME S.p.A.");+ vendorModels.put(0x06C1, "Alarm.com Holdings, Inc");+ vendorModels.put(0x06C2, "Measurlogic Inc.");+ vendorModels.put(0x06C3, "King I Electronics.Co.,Ltd");+ vendorModels.put(0x06C4, "Dream Labs GmbH");+ vendorModels.put(0x06C5, "Urban Compass, Inc");+ vendorModels.put(0x06C6, "Simm Tronic Limited");+ vendorModels.put(0x06C7, "Somatix Inc");+ vendorModels.put(0x06C8, "Storz & Bickel GmbH & Co. KG");+ vendorModels.put(0x06C9, "MYLAPS B.V.");+ vendorModels.put(0x06CA, "Shenzhen Zhongguang Infotech Technology Development Co., Ltd");+ vendorModels.put(0x06CB, "Dyeware, LLC");+ vendorModels.put(0x06CC, "Dongguan SmartAction Technology Co.,Ltd.");+ vendorModels.put(0x06CD, "DIG Corporation");+ vendorModels.put(0x06CE, "FIOR & GENTZ");+ vendorModels.put(0x06CF, "Belparts N.V.");+ vendorModels.put(0x06D0, "Etekcity Corporation");+ vendorModels.put(0x06D1, "Meyer Sound Laboratories, Incorporated");+ vendorModels.put(0x06D2, "CeoTronics AG");+ vendorModels.put(0x06D3, "TriTeq Lock and Security, LLC");+ vendorModels.put(0x06D4, "DYNAKODE TECHNOLOGY PRIVATE LIMITED");+ vendorModels.put(0x06D5, "Sensirion AG");+ vendorModels.put(0x06D6, "JCT Healthcare Pty Ltd");+ vendorModels.put(0x06D7, "FUBA Automotive Electronics GmbH");+ vendorModels.put(0x06D8, "AW Company");+ vendorModels.put(0x06D9, "Shanghai Mountain View Silicon Co.,Ltd.");+ vendorModels.put(0x06DA, "Zliide Technologies ApS");+ vendorModels.put(0x06DB, "Automatic Labs, Inc.");+ vendorModels.put(0x06DC, "Industrial Network Controls, LLC");+ vendorModels.put(0x06DD, "Intellithings Ltd.");+ vendorModels.put(0x06DE, "Navcast, Inc.");+ vendorModels.put(0x06DF, "Hubbell Lighting, Inc.");+ vendorModels.put(0x06E0, "Avaya");+ vendorModels.put(0x06E1, "Milestone AV Technologies LLC");+ vendorModels.put(0x06E2, "Alango Technologies Ltd");+ vendorModels.put(0x06E3, "Spinlock Ltd");+ vendorModels.put(0x06E4, "Aluna");+ vendorModels.put(0x06E5, "OPTEX CO.,LTD.");+ vendorModels.put(0x06E6, "NIHON DENGYO KOUSAKU");+ vendorModels.put(0x06E7, "VELUX A/S");+ vendorModels.put(0x06E8, "Almendo Technologies GmbH");+ vendorModels.put(0x06E9, "Zmartfun Electronics, Inc.");+ vendorModels.put(0x06EA, "SafeLine Sweden AB");+ vendorModels.put(0x06EB, "Houston Radar LLC");+ vendorModels.put(0x06EC, "Sigur");+ vendorModels.put(0x06ED, "J Neades Ltd");+ vendorModels.put(0x06EE, "Avantis Systems Limited");+ vendorModels.put(0x06EF, "ALCARE Co., Ltd.");+ vendorModels.put(0x06F0, "Chargy Technologies, SL");+ vendorModels.put(0x06F1, "Shibutani Co., Ltd.");+ vendorModels.put(0x06F2, "Trapper Data AB");+ vendorModels.put(0x06F3, "Alfred International Inc.");+ vendorModels.put(0x06F4, "Near Field Solutions Ltd");+ vendorModels.put(0x06F5, "Vigil Technologies Inc.");+ vendorModels.put(0x06F6, "Vitulo Plus BV");+ vendorModels.put(0x06F7, "WILKA Schliesstechnik GmbH");+ vendorModels.put(0x06F8, "BodyPlus Technology Co.,Ltd");+ vendorModels.put(0x06F9, "happybrush GmbH");+ vendorModels.put(0x06FA, "Enequi AB");+ vendorModels.put(0x06FB, "Sartorius AG");+ vendorModels.put(0x06FC, "Tom Communication Industrial Co.,Ltd.");+ vendorModels.put(0x06FD, "ESS Embedded System Solutions Inc.");+ vendorModels.put(0x06FE, "Mahr GmbH");+ vendorModels.put(0x06FF, "Redpine Signals Inc");+ vendorModels.put(0x0700, "TraqFreq LLC");+ vendorModels.put(0x0701, "PAFERS TECH");+ vendorModels.put(0x0702, "Akciju sabiedriba \"SAF TEHNIKA\"");+ vendorModels.put(0x0703, "Beijing Jingdong Century Trading Co., Ltd.");+ vendorModels.put(0x0704, "JBX Designs Inc.");+ vendorModels.put(0x0705, "AB Electrolux");+ vendorModels.put(0x0706, "Wernher von Braun Center for ASdvanced Research");+ vendorModels.put(0x0707, "Essity Hygiene and Health Aktiebolag");+ vendorModels.put(0x0708, "Be Interactive Co., Ltd");+ vendorModels.put(0x0709, "Carewear Corp.");+ vendorModels.put(0x070A, "Huf Hlsbeck & Frst GmbH & Co. KG");+ vendorModels.put(0x070B, "Element Products, Inc.");+ vendorModels.put(0x070C, "Beijing Winner Microelectronics Co.,Ltd");+ vendorModels.put(0x070D, "SmartSnugg Pty Ltd");+ vendorModels.put(0x070E, "FiveCo Sarl");+ vendorModels.put(0x070F, "California Things Inc.");+ vendorModels.put(0x0710, "Audiodo AB");+ vendorModels.put(0x0711, "ABAX AS");+ vendorModels.put(0x0712, "Bull Group Company Limited");+ vendorModels.put(0x0713, "Respiri Limited");+ vendorModels.put(0x0714, "MindPeace Safety LLC");+ vendorModels.put(0x0715, "Vgyan Solutions");+ vendorModels.put(0x0716, "Altonics");+ vendorModels.put(0x0717, "iQsquare BV");+ vendorModels.put(0x0718, "IDIBAIX enginneering");+ vendorModels.put(0x0719, "ECSG");+ vendorModels.put(0x071A, "REVSMART WEARABLE HK CO LTD");+ vendorModels.put(0x071B, "Precor");+ vendorModels.put(0x071C, "F5 Sports, Inc");+ vendorModels.put(0x071D, "exoTIC Systems");+ vendorModels.put(0x071E, "DONGGUAN HELE ELECTRONICS CO., LTD");+ vendorModels.put(0x071F, "Dongguan Liesheng Electronic Co.Ltd");+ vendorModels.put(0x0720, "Oculeve, Inc.");+ vendorModels.put(0x0721, "Clover Network, Inc.");+ vendorModels.put(0x0722, "Xiamen Eholder Electronics Co.Ltd");+ vendorModels.put(0x0723, "Ford Motor Company");+ vendorModels.put(0x0724, "Guangzhou SuperSound Information Technology Co.,Ltd");+ vendorModels.put(0x0725, "Tedee Sp. z o.o.");+ vendorModels.put(0x0726, "PHC Corporation");+ vendorModels.put(0x0727, "STALKIT AS");+ vendorModels.put(0x0728, "Eli Lilly and Company");+ vendorModels.put(0x0729, "SwaraLink Technologies");+ vendorModels.put(0x072A, "JMR embedded systems GmbH");+ vendorModels.put(0x072B, "Bitkey Inc.");+ vendorModels.put(0x072C, "GWA Hygiene GmbH");+ vendorModels.put(0x072D, "Safera Oy");+ vendorModels.put(0x072E, "Open Platform Systems LLC");+ vendorModels.put(0x072F, "OnePlus Electronics (Shenzhen) Co., Ltd.");+ vendorModels.put(0x0730, "Wildlife Acoustics, Inc.");+ vendorModels.put(0x0731, "ABLIC Inc.");+ vendorModels.put(0x0732, "Dairy Tech, Inc.");+ vendorModels.put(0x0733, "Iguanavation, Inc.");+ vendorModels.put(0x0734, "DiUS Computing Pty Ltd");+ vendorModels.put(0x0735, "UpRight Technologies LTD");+ vendorModels.put(0x0736, "FrancisFund, LLC");+ vendorModels.put(0x0737, "LLC Navitek");+ vendorModels.put(0x0738, "Glass Security Pte Ltd");+ vendorModels.put(0x0739, "Jiangsu Qinheng Co., Ltd.");+ vendorModels.put(0x073A, "Chandler Systems Inc.");+ vendorModels.put(0x073B, "Fantini Cosmi s.p.a.");+ vendorModels.put(0x073C, "Acubit ApS");+ vendorModels.put(0x073D, "Beijing Hao Heng Tian Tech Co., Ltd.");+ vendorModels.put(0x073E, "Bluepack S.R.L.");+ vendorModels.put(0x073F, "Beijing Unisoc Technologies Co., Ltd.");+ vendorModels.put(0x0740, "HITIQ LIMITED");+ vendorModels.put(0x0741, "MAC SRL");+ vendorModels.put(0x0742, "DML LLC");+ vendorModels.put(0x0743, "Sanofi");+ }++ /**+ * Returns the company name for the given company identifier+ *+ * @param companyIdentifier 16-bit company identifier+ * @return company name;+ */+ public static String getCompanyName(final short companyIdentifier) {+ final String companyName = vendorModels.get(companyIdentifier);+ return companyName == null ? "Company ID unavailable" : companyName;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/CompositionDataParser.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/CompositionDataParser.javanew file mode 100644index 000000000..5b90d77bd--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/CompositionDataParser.java@@ -0,0 +1,35 @@+package org.openremote.agent.protocol.bluetooth.mesh.utils;++import java.util.Locale;++public class CompositionDataParser {++ public static String formatCompanyIdentifier(final int companyIdentifier, final boolean add0x) {+ return add0x ? "0x" + String.format(Locale.US, "%04X", companyIdentifier) : String.format(Locale.US, "%04X", companyIdentifier);+ }++ public static String formatProductIdentifier(final int productIdentifier, final boolean add0x) {+ return add0x ? "0x" + String.format(Locale.US, "%04X", productIdentifier) : String.format(Locale.US, "%04X", productIdentifier);+ }++ public static String formatVersionIdentifier(final int versionIdentifier, final boolean add0x) {+ return add0x ? "0x" + String.format(Locale.US, "%04X", versionIdentifier) : String.format(Locale.US, "%04X", versionIdentifier);+ }++ public static String formatReplayProtectionCount(final int replayProtectionCount, final boolean add0x) {+ return add0x ? "0x" + String.format(Locale.US, "%04X", replayProtectionCount) : String.format(Locale.US, "%04X", replayProtectionCount);+ }++ public static String formatFeatures(final int features, final boolean add0x) {+ return add0x ? "0x" + String.format(Locale.US, "%04X", features) : String.format(Locale.US, "%04X", features);+ }++ public static String formatModelIdentifier(final int modelId, final boolean add0x) {+ if (modelId < Short.MIN_VALUE || modelId > Short.MAX_VALUE) {+ return add0x ? "0x" + String.format(Locale.US, "%08X", modelId) : String.format(Locale.US, "%08X", modelId);+ } else {+ return add0x ? "0x" + String.format(Locale.US, "%04X", modelId) : String.format(Locale.US, "%04X", modelId);+ }+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/DeviceFeatureUtils.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/DeviceFeatureUtils.javanew file mode 100644index 000000000..51880ccb1--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/DeviceFeatureUtils.java@@ -0,0 +1,80 @@+package org.openremote.agent.protocol.bluetooth.mesh.utils;++public class DeviceFeatureUtils {++ /**+ * Checks if relay feature is supported by node;+ *+ * @param feature 16-bit feature value+ * @return true if relay bit = 1 and false if relay bit = 0+ */+ public static boolean supportsRelayFeature(final int feature) {+ return ((feature & (1 << 0)) > 0);+ }++ /**+ * Checks if proxy feature is supported by node;+ *+ * @param feature 16-bit feature value+ * @return true if proxy bit = 1 and false if proxy bit = 0+ */+ public static boolean supportsProxyFeature(final int feature) {+ return ((feature & (1 << 1)) > 0);+ }++ /**+ * Checks if friend feature is supported by node;+ *+ * @param feature 16-bit feature value+ * @return true if friend bit = 1 and false if friend bit = 0+ */+ public static boolean supportsFriendFeature(final int feature) {+ return ((feature & (1 << 2)) > 0);+ }++ /**+ * Checks if low power feature is supported by node;+ *+ * @param feature 16-bit feature value+ * @return true if low power bit = 1 and false if low power bit = 0+ */+ public static boolean supportsLowPowerFeature(final int feature) {+ return ((feature & (1 << 3)) > 0);+ }++ /**+ * Returns the relay feature state value+ *+ * @param feature 16-bit feature value+ */+ public static int getRelayFeature(final int feature) {+ return feature & 1;+ }++ /**+ * Returns the proxy feature state value+ *+ * @param feature 16-bit feature value+ */+ public static int getProxyFeature(final int feature) {+ return (feature >> 1) & 1;+ }++ /**+ * Returns the friend feature state value+ *+ * @param feature 16-bit feature value+ */+ public static int getFriendFeature(final int feature) {+ return (feature >> 2) & 1;+ }++ /**+ * Returns the low power feature state value+ *+ * @param feature 16-bit feature value+ */+ public static int getLowPowerFeature(final int feature) {+ return (feature >> 3) & 1;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/ExtendedInvalidCipherTextException.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/ExtendedInvalidCipherTextException.javanew file mode 100644index 000000000..85a984bef--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/ExtendedInvalidCipherTextException.java@@ -0,0 +1,45 @@+package org.openremote.agent.protocol.bluetooth.mesh.utils;++import org.bouncycastle.crypto.InvalidCipherTextException;++public class ExtendedInvalidCipherTextException extends InvalidCipherTextException {++ private final String tag;+ private final String message;+ private final Throwable cause;++ /**+ * Constructs ExtendedInvalidCipherTextException+ *+ * @param message Exception message+ * @param cause Throwable cause+ * @param tag class tag name+ */+ public ExtendedInvalidCipherTextException(final String message, final Throwable cause, final String tag) {+ this.message = message;+ this.cause = cause;+ this.tag = tag;++ }++ /**+ * Returns the tag name of the class.+ * <p>+ * Using the tag we can find out on which class the exception occurred.+ * </p>+ */+ public String getTag() {+ return tag;+ }++ @Override+ public String getMessage() {+ return message;+ }++ @Override+ public Throwable getCause() {+ return cause;+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/Heartbeat.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/Heartbeat.javanew file mode 100644index 000000000..3fdc68e51--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/Heartbeat.java@@ -0,0 +1,134 @@+package org.openremote.agent.protocol.bluetooth.mesh.utils;++public abstract class Heartbeat {+ public static final int DO_NOT_SEND_PERIODICALLY = 0x00;+ public static final int PERIOD_MIN = 0x0000;+ public static final int PERIOD_MAX = 0x10000;+ public static final int PERIOD_LOG_MIN = 0x01;+ public static final int PERIOD_LOG_MAX = 0x11;+ public static final int COUNT_MIN = 0x00;+ public static final int COUNT_MAX = 0x11;+ public static final int SEND_INDEFINITELY = 0xFF;+ public static final int DEFAULT_PUBLICATION_TTL = 0x05;+++ protected int dst;+ protected byte periodLog;+ protected byte countLog;++ Heartbeat(final int dst, final byte periodLog, final byte countLog) {+ this.dst = dst;+ this.periodLog = periodLog;+ this.countLog = countLog;+ }++ /**+ * Returns true if the heartbeats are enabled.+ */+ public abstract boolean isEnabled();++ /**+ * Returns the destination address.+ */+ public int getDst() {+ return dst;+ }++ /**+ * Returns the period for processing.+ */+ public byte getPeriodLog() {+ return periodLog;+ }++ /**+ * Calculates the heart beat period interval in seconds+ *+ * @param periodLog period value+ */+ public static int calculateHeartbeatPeriod(final short periodLog) {+ return (int) Math.pow(2, periodLog - 1);+ }++ /**+ * Decodes the period and returns the period log value+ *+ * @param period period value+ */+ public static byte decodeHeartbeatPeriod(final int period) {+ switch (period) {+ case 0x0000:+ return 0x00;+ case 0xFFFF:+ return 0x11;+ default:+ return log2(period);+ }+ }++ private static byte log2(final int period) {+ return (byte) ((Math.log(period) / Math.log(2)) + 1);+ }++ /**+ * Validates heart beat period.+ *+ * @param period Heartbeat publication period.+ * @return true if valid or false otherwise.+ * @throws IllegalArgumentException if the value does not range from 0 to 17.+ */+ public static boolean isValidHeartbeatPeriod(final int period) {+ if (period >= 0x0000 && period < 0xFFFF)+ return true;+ throw new IllegalArgumentException("Period must be within the range of 0x0000 to 0xFFFF!");+ }++ /**+ * Validates heart beat period log.+ *+ * @param period Heartbeat publication period.+ * @return true if valid or false otherwise.+ * @throws IllegalArgumentException if the value does not range from 0 to 17.+ */+ public static boolean isValidHeartbeatPeriodLog(final byte period) {+ if (period >= 0x00 && period < 0x11)+ return true;+ throw new IllegalArgumentException("Period log must be within the range of 0x00 to 0x11!");+ }++ public byte getCountLog() {+ return countLog;+ }++ /**+ * Calculates the heart beat publication count which is the number of publications to be sent+ *+ * @param countLog count value+ */+ public static int calculateHeartbeatCount(final int countLog) {+ if (countLog > 0x11 && countLog < 0xFF)+ throw new IllegalArgumentException("Prohibited, count log must be a value from 0x00 to 0x11 and 0xFF");+ if (countLog == 0x11)+ return (int) Math.pow(2, countLog - 1) - 2;+ return (int) Math.pow(2, countLog - 1);+ }++ /**+ * Converts the perio to time+ *+ * @param seconds PeriodLog+ */+ public static String periodToTime(final int seconds) {+ if (seconds == 1)+ return seconds + " second";+ else if (seconds > 1 && seconds < 60) {+ return seconds + " seconds";+ } else if (seconds >= 60 && seconds < 3600) {+ return seconds / 60 + " min " + (seconds % 60) + " sec";+ } else if (seconds >= 3600 && seconds <= 65535) {+ return seconds / 3600 + " h " + ((seconds % 3600) / 60) + " min " + (seconds % 3600 % 60) + " sec";+ } else+ return seconds / 3600 + " h " + ((seconds % 3600) / 60) + " min " + ((seconds % 3600 % 60) - 1) + " sec";+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/HeartbeatPublication.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/HeartbeatPublication.javanew file mode 100644index 000000000..a1793e0d0--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/HeartbeatPublication.java@@ -0,0 +1,114 @@+package org.openremote.agent.protocol.bluetooth.mesh.utils;++import org.openremote.agent.protocol.bluetooth.mesh.Features;++import static org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress.UNASSIGNED_ADDRESS;++public class HeartbeatPublication extends Heartbeat {++ private final int ttl;+ private final Features features;+ private final int netKeyIndex;++ /**+ * Heartbeat subscription.+ *+ * @param dst Destination address identifies the Heartbeat Publication+ * destination where the address can only be an unassigned address,+ * unicast address or a group address. All other values are prohibited.+ * @param countLog Number of Heartbeat messages to be sent.+ * @param periodLog Period for sending Heartbeat messages.+ * @param ttl TTL to be used when sending Heartbeat messages.+ * @param features Bit field indicating features that trigger Heartbeat messages when changed.+ * @param netKeyIndex Net key index.+ */+ public HeartbeatPublication(final int dst,+ final byte countLog,+ final byte periodLog,+ final int ttl,+ final Features features,+ final int netKeyIndex) {+ super(dst, periodLog, countLog);+ this.ttl = ttl;+ this.features = features;+ this.netKeyIndex = netKeyIndex;+ }++ @Override+ public String toString() {+ return "Destination address: " + Integer.toHexString(dst) ++ "\nCount Log: " + Integer.toHexString(countLog) ++ "\nPeriod Log: " + Integer.toHexString(periodLog) ++ "\nTTL: " + ttl ++ "\nFeatures: " + features == null ? "null" : features.toString() ++ "\nNet key index: " + Integer.toHexString(netKeyIndex);+ }++ public int getPeriod(){+ return calculateHeartbeatPeriod(periodLog);+ }++ /**+ * Returns the publication ttl.+ */+ public int getTtl() {+ return ttl;+ }++ /**+ * Returns the features.+ */+ public Features getFeatures() {+ return features;+ }++ /**+ * Returns the Net key index.+ */+ public int getNetKeyIndex() {+ return netKeyIndex;+ }++ /**+ * Returns true if the heartbeat subscriptions are enabled.+ */+ public boolean isEnabled() {+ return dst != UNASSIGNED_ADDRESS;+ }++ public String getPeriodLogDescription() {+ if (periodLog == 0x00)+ return "Disabled";+ else if (periodLog >= 0x01 || periodLog <= 0x11)+ return (int) Math.pow(2, periodLog - 1) + " s";+ else+ return "Prohibited";+ }++ public Short getPeriodLog2Period(final int periodLog) {+ if (periodLog == 0x00)+ return 0x0000;+ else if (periodLog >= 0x01 && periodLog <= 0x10) {+ return (short) (Math.pow(2, periodLog - 1));+ } else return (short) 0xFFFF;+ }++ public String getCountLogDescription() {+ if (countLog == 0x00)+ return "Disabled";+ else if (countLog == 0xFF)+ return "Indefinite";+ else if (countLog == 0x01 || countLog == 0x02)+ return String.valueOf(countLog);+ else if (countLog == 0x11) {+ return "0x8001 ... 0xFFFE";+ } else if (countLog >= 0x03 && countLog <= 0x10) {+ final int lowerBound = (int) (Math.pow(2, countLog - 2)) + 1;+ final int upperBound = (int) Math.pow(2, countLog - 1);+ return lowerBound + " ... " + upperBound;+ } else {+ return "Invalid";+ }+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/HeartbeatSubscription.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/HeartbeatSubscription.javanew file mode 100644index 000000000..2cb8833c8--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/HeartbeatSubscription.java@@ -0,0 +1,103 @@+package org.openremote.agent.protocol.bluetooth.mesh.utils;++import static org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress.UNASSIGNED_ADDRESS;++public class HeartbeatSubscription extends Heartbeat {+++ private final int src;+ private int minHops;+ private int maxHops;++ /**+ * Heartbeat subscription.+ *+ * @param src Source address for Heartbeat messages.+ * @param dst Destination address for Heartbeat messages.+ * @param periodLog Remaining period for processing Heartbeat messages.+ * @param countLog Number of Heartbeat messages received.+ * @param minHops Minimum hops when receiving Heartbeat messages.+ * @param maxHops Maximum hops when receiving Heartbeat messages.+ */+ public HeartbeatSubscription(final int src, final int dst, final byte periodLog, final byte countLog, final int minHops, final int maxHops) {+ super(dst, periodLog, countLog);+ this.src = src;+ this.minHops = minHops;+ this.maxHops = maxHops;+ }++ @Override+ public String toString() {+ return "Source address: " + Integer.toHexString(src) ++ "\nDestination address: " + Integer.toHexString(dst) ++ "\nPeriod Log: " + Integer.toHexString(periodLog) ++ "\nCount Log: " + Integer.toHexString(countLog) ++ "\nMin Hops: " + minHops ++ "\n Max Hops: " + maxHops;+ }++ /**+ * Returns the source address.+ */+ public int getSrc() {+ return src;+ }++ /**+ * Returns the minimum number of hopes when receiving heartbeat messages.+ */+ public int getMinHops() {+ return minHops;+ }++ /**+ * Returns the maximum number of hopes when receiving heartbeat messages.+ */+ public int getMaxHops() {+ return maxHops;+ }++ /**+ * Returns true if the heartbeat subscriptions are enabled.+ */+ public boolean isEnabled() {+ return src != UNASSIGNED_ADDRESS && dst != UNASSIGNED_ADDRESS;+ }++ public String getCountLogDescription() {+ if (countLog == 0x00 || countLog == 0x01)+ return String.valueOf(countLog);+ else if (countLog >= 0x02 && countLog <= 0x10) {+ final int lowerBound = (int) (Math.pow(2, countLog - 1));+ final int upperBound = Math.min(0xFFFE, (int) (Math.pow(2, countLog)) - 1);+ return lowerBound + " ... " + upperBound;+ } else {+ return "More than 65534"; //0xFFFE+ }+ }++ public String getPeriodLogDescription() {+ if (periodLog == 0x00)+ return "Disabled";+ else if (periodLog == 0x01)+ return "1";+ else if (periodLog >= 0x02 && periodLog < 0x11) {+ final int lowerBound = (int) (Math.pow(2, periodLog - 1));+ final int upperBound = (int) (Math.pow(2, periodLog) - 1);+ return periodToTime(lowerBound) + " ... " + periodToTime(upperBound);+ } else if (periodLog == 0x11)+ return "65535";+ else return "Invalid";+ }++ public Short getPeriodLog2Period() {+ if (periodLog == 0x00)+ return 0x0000;+ else if (periodLog >= 0x01 && periodLog <= 0x10) {+ return (short) (Math.pow(2, periodLog - 1));+ } else if (periodLog == 0x11)+ return (short) 0xFFFF;+ else throw new IllegalArgumentException("Period Log out of range");+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/InputOOBAction.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/InputOOBAction.javanew file mode 100644index 000000000..e8310dda6--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/InputOOBAction.java@@ -0,0 +1,175 @@+package org.openremote.agent.protocol.bluetooth.mesh.utils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.ArrayList;+import java.util.logging.Logger;++public enum InputOOBAction {++ /**+ * Input OOB Actions+ */+ NO_INPUT((short) 0x0000),+ PUSH((short) 0x0001),+ TWIST((short) 0x0002),+ INPUT_NUMERIC((short) 0x0004),+ INPUT_ALPHA_NUMERIC((short) 0x0008);++ private static final Logger LOG = java.util.logging.Logger.getLogger(InputOOBAction.class.getName());+ private short inputOOBAction;++ InputOOBAction(final short outputOOBAction) {+ this.inputOOBAction = outputOOBAction;+ }++ public short getInputOOBAction() {+ return inputOOBAction;+ }++ /**+ * Returns the oob method used for authentication+ *+ * @param method auth method used+ */+ public static InputOOBAction fromValue(final short method) {+ switch (method) {+ default:+ case 0x0000:+ return NO_INPUT;+ case 0x0001:+ return PUSH;+ case 0x0002:+ return TWIST;+ case 0x0004:+ return INPUT_NUMERIC;+ case 0x0008:+ return INPUT_ALPHA_NUMERIC;+ }+ }++ /**+ * Returns the Input OOB Action description+ *+ * @param type Input OOB type+ * @return Input OOB type descrption+ */+ public static String getInputOOBActionDescription(final InputOOBAction type) {+ switch (type) {+ case NO_INPUT:+ return "Not supported";+ case PUSH:+ return "Push";+ case TWIST:+ return "Twist";+ case INPUT_NUMERIC:+ return "Input Number";+ case INPUT_ALPHA_NUMERIC:+ return "Input Alpha Numeric";+ default:+ return "Unknown";+ }+ }++ public static ArrayList<InputOOBAction> parseInputActionsFromBitMask(final int inputAction) {+ final InputOOBAction[] inputActions = {PUSH, TWIST, INPUT_NUMERIC, INPUT_ALPHA_NUMERIC};+ final ArrayList<InputOOBAction> supportedActionValues = new ArrayList<>();+ for (InputOOBAction action : inputActions) {+ if ((inputAction & action.inputOOBAction) == action.inputOOBAction) {+ supportedActionValues.add(action);+ LOG.info("Input oob action type value: " + getInputOOBActionDescription(action));+ }+ }+ return supportedActionValues;+ }++ /**+ * Returns the Input OOB Action value+ *+ * @param type input OOB type+ */+ public static int getInputOOBActionValue(final InputOOBAction type) {+ switch (type) {+ case PUSH:+ return 0;+ case TWIST:+ return 1;+ case INPUT_NUMERIC:+ return 2;+ case INPUT_ALPHA_NUMERIC:+ return 3;+ case NO_INPUT:+ default:+ return -1;+ }+ }++ /**+ * Returns the Input OOB Action value+ *+ * @param type input OOB type+ */+ public static int getInputOOBActionValue(final short type) {+ switch (fromValue(type)) {+ case PUSH:+ return 0;+ case TWIST:+ return 1;+ case INPUT_NUMERIC:+ return 2;+ case INPUT_ALPHA_NUMERIC:+ return 3;+ case NO_INPUT:+ default:+ return -1;+ }+ }++ /**+ * Generates the Input OOB Authentication value+ *+ * @param inputOOBAction selected {@link InputOOBAction}+ * @param input Input authentication+ * @return 128-bit authentication value+ */+ public static byte[] generateInputOOBAuthenticationValue(final InputOOBAction inputOOBAction, final byte[] input) {+ final int authLength = 16;+ final ByteBuffer buffer = ByteBuffer.allocate(authLength).order(ByteOrder.BIG_ENDIAN);+ switch (inputOOBAction) {+ case PUSH:+ case TWIST:+ case INPUT_NUMERIC:+ buffer.position(8);+ final long longValue = Long.valueOf(MeshParserUtils.bytesToHex(input, false), 16);+ buffer.putLong(longValue);+ return buffer.array();+ case INPUT_ALPHA_NUMERIC:+ buffer.put(input);+ return buffer.array();+ default:+ return null;+ }+ }++ /**+ * Returns a randomly generated Input OOB Authentication value to be input by the user+ *+ * @param inputOOBAction selected {@link InputOOBAction}+ * @param size oob size+ */+ public static byte[] getInputOOOBAuthenticationValue(final short inputOOBAction, final byte size) {+ switch (fromValue(inputOOBAction)) {+ case PUSH:+ case TWIST:+ //We override the value here to 1 so we generate a 1 digit value for presses.+ return MeshParserUtils.generateOOBCount(1);+ case INPUT_NUMERIC:+ return MeshParserUtils.generateOOBNumeric(size);+ case INPUT_ALPHA_NUMERIC:+ return MeshParserUtils.generateOOBAlphaNumeric(size);+ default:+ return null;+ }+ }+}+diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/MeshAddress.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/MeshAddress.javanew file mode 100644index 000000000..e1095ac3f--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/MeshAddress.java@@ -0,0 +1,386 @@+package org.openremote.agent.protocol.bluetooth.mesh.utils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.nio.charset.Charset;+import java.util.List;+import java.util.Locale;+import java.util.UUID;++public class MeshAddress {+ private static final byte[] VTAD = "vtad".getBytes(Charset.forName("US-ASCII"));++ //Unassigned addresses+ public static final int UNASSIGNED_ADDRESS = 0x0000;++ //Unicast addresses+ public static final int START_UNICAST_ADDRESS = 0x0001;+ public static final int END_UNICAST_ADDRESS = 0x7FFF;++ //Group address start and end defines the address range that can be used to create groups+ public static final int START_GROUP_ADDRESS = 0xC000;+ public static final int END_GROUP_ADDRESS = 0xFEFF;++ //Fixed group addresses+ public static final int ALL_PROXIES_ADDRESS = 0xFFFC;+ public static final int ALL_FRIENDS_ADDRESS = 0xFFFD;+ public static final int ALL_RELAYS_ADDRESS = 0xFFFE;+ public static final int ALL_NODES_ADDRESS = 0xFFFF;++ //Virtual addresses+ private static final byte B1_VIRTUAL_ADDRESS = (byte) 0x80;+ public static final int START_VIRTUAL_ADDRESS = 0x8000;+ public static final int END_VIRTUAL_ADDRESS = 0xBFFF;+ public static final int UUID_HASH_BIT_MASK = 0x3FFF;++ public static String formatAddress(final int address, final boolean add0x) {+ return add0x ?+ "0x" + String.format(Locale.US, "%04X", address) :+ String.format(Locale.US, "%04X", address);+ }++ public static boolean isAddressInRange(final byte[] address) {+ return address.length == 2 && isAddressInRange((address[0] & 0xFF) << 8 | address[1] & 0xFF);+ }++ /**+ * Checks if the address is in range+ *+ * @param address address+ * @return true if is in range or false otherwise+ */+ public static boolean isAddressInRange(final int address) {+ return address == (address & 0xFFFF);+ }++ /**+ * Validates an unassigned address+ *+ * @param address 16-bit address+ * @return true if the address is a valid unassigned address or false otherwise+ */+ public static boolean isValidUnassignedAddress(final byte[] address) {+ if (!isAddressInRange(address)) {+ return false;+ }+ return isValidUnassignedAddress(MeshParserUtils.unsignedBytesToInt(address[0], address[1]));+ }++ /**+ * Validates a unassigned address+ *+ * @param address 16-bit address+ * @return true if the address is a valid unassigned address or false otherwise+ */+ public static boolean isValidUnassignedAddress(final int address) {+ return isAddressInRange(address) && (address == UNASSIGNED_ADDRESS);+ }++ /**+ * Validates a unicast address+ *+ * @param address Address in bytes+ * @return true if the address is a valid unicast address or false otherwise+ */+ public static boolean isValidUnicastAddress(final byte[] address) {+ if (!isAddressInRange(address)) {+ return false;+ }++ return isValidUnicastAddress(MeshParserUtils.unsignedBytesToInt(address[1], address[0]));+ }++ /**+ * Validates a unicast address+ *+ * @param address 16-bit address+ * @return true if the address is a valid unicast address or false otherwise+ */+ public static boolean isValidUnicastAddress(final int address) {+ return isAddressInRange(address) && (address >= START_UNICAST_ADDRESS && address <= END_UNICAST_ADDRESS);+ }++ /**+ * Validates a virtual address+ *+ * @param address Address in bytes+ * @return true if the address is a valid virtual address or false otherwise+ */+ public static boolean isValidVirtualAddress(final byte[] address) {+ if (!isAddressInRange(address)) {+ return false;+ }+ return isValidVirtualAddress(MeshParserUtils.unsignedBytesToInt(address[1], address[0]));+ }++ /**+ * Validates a unicast address+ *+ * @param address 16-bit address+ * @return true if the address is a valid virtual address or false otherwise+ */+ public static boolean isValidVirtualAddress(final int address) {+ if (isAddressInRange(address)) {+ return address >= START_VIRTUAL_ADDRESS && address <= END_VIRTUAL_ADDRESS;+ }+ return false;+ }++ public static boolean isValidGroupAddress(final byte[] address) {+ if (!isAddressInRange(address))+ return false;+ return isValidGroupAddress(MeshParserUtils.unsignedBytesToInt(address[1], address[0]));+ }++ /**+ * Returns true if the its a valid group address+ *+ * @param address 16-bit address+ * @return true if the address is valid and false otherwise+ */+ public static boolean isValidGroupAddress(final int address) {+ if (!isAddressInRange(address))+ return false;++ final int b0 = address >> 8 & 0xFF;+ final int b1 = address & 0xFF;++ final boolean groupRange = b0 >= 0xC0 && b0 <= 0xFF;+ final boolean rfu = b0 == 0xFF && b1 >= 0x00 && b1 <= 0xFB;+ final boolean allNodes = b0 == 0xFF && b1 == 0xFF;++ return groupRange && !rfu && !allNodes;+ }++ /**+ * Returns true if the its a valid fixed group address. Fixed group addresses include all proxies, all friends, all relays and all nodes address.+ *+ * @param address 16-bit address+ * @return true if the address is valid and false otherwise+ */+ public static boolean isValidFixedGroupAddress(final int address) {+ if (!isAddressInRange(address))+ return false;++ final int b0 = address >> 8 & 0xFF;+ final int b1 = address & 0xFF;++ final boolean rfu = b0 == 0xFF && b1 >= 0x00 && b1 <= 0xFB;+ final boolean allNodes = b0 == 0xFF && b1 > 0xFB && b1 <= 0xFF;++ return !rfu && allNodes;+ }++ /**+ * Returns true if the address is a valid subscription address+ *+ * @param address 16-bit address+ * @return true if the address is valid and false otherwise+ */+ public static boolean isValidSubscriptionAddress(final int address) {++ if (isValidUnassignedAddress(address) || isValidUnicastAddress(address) || isValidVirtualAddress(address) || address == 0xFFFF) {+ throw new IllegalArgumentException("The value of the Address field shall not be an unassigned address, unicast address, " ++ "all-nodes address or virtual address.");+ }++ final int b0 = address >> 8 & 0xFF;+ final int b1 = address & 0xFF;++ final boolean groupRange = b0 >= 0xC0;+ final boolean rfu = b0 == 0xFF && b1 <= 0xFB;+ final boolean allNodes = b0 == 0xFF && b1 == 0xFF;+ return groupRange && !rfu && !allNodes;+ }++ /**+ * Validates a given address for subscriptions+ *+ * @param address group address+ * @return true if is valid and false otherwise+ */+ public static boolean isValidSubscriptionAddress(final byte[] address) {+ if (!isAddressInRange(address))+ return false;+ return isValidSubscriptionAddress((address[0] & 0xFF) << 8 | address[1] & 0xFF);+ }++ /**+ * Validates if the given address is a valid address that can be used as a proxy filter+ *+ * @param address Unicast/Virtual or Group address+ * @return true if is valid and false otherwise+ */+ public static boolean isValidProxyFilterAddress(final int address) {+ if (!isAddressInRange(address))+ return false;+ final int b0 = address >> 8 & 0xFF;+ final int b1 = address & 0xFF;++ final boolean groupRange = b0 >= 0xC0;+ final boolean rfu = b0 == 0xFF && b1 <= 0xFB;+ final boolean unicast = isValidUnicastAddress(address);+ final boolean virtual = isValidVirtualAddress(address);+ return unicast || virtual || (groupRange && !rfu);+ }++ /**+ * Validates if the given address is a valid address that can be used as a proxy filter+ *+ * @param address Unicast/Virtual or Group address+ * @return true if is valid and false otherwise+ */+ public static boolean isValidProxyFilterAddress(final byte[] address) {+ if (!isAddressInRange(address))+ return false;+ return isValidProxyFilterAddress((address[0] & 0xFF) << 8 | address[1] & 0xFF);+ }++ /**+ * Returns the {@link AddressType}+ *+ * @param address 16-bit mesh address+ */+ public static AddressType getAddressType(final int address) {+ if (isAddressInRange(address)) {+ if (isValidUnassignedAddress(address)) {+ return AddressType.UNASSIGNED_ADDRESS;+ } else if (isValidUnicastAddress(address)) {+ return AddressType.UNICAST_ADDRESS;+ } else if (isValidGroupAddress(address) || isValidFixedGroupAddress(address)) {+ return AddressType.GROUP_ADDRESS;+ } else {+ return AddressType.VIRTUAL_ADDRESS;+ }+ }+ return null;+ }++ /**+ * Generates a random uuid+ */+ public static UUID generateRandomLabelUUID() {+ return UUID.randomUUID();+ }++ /**+ * Generates a virtual address from a given Lable UUID+ *+ * @param uuid Type 4 UUID+ */+ public static Integer generateVirtualAddress(final UUID uuid) {+ final byte[] uuidBytes = MeshParserUtils.uuidToBytes(uuid);+ final byte[] salt = SecureUtils.calculateSalt(VTAD);+ final byte[] encryptedUuid = SecureUtils.calculateCMAC(MeshParserUtils.uuidToBytes(uuid), salt);+ ByteBuffer buffer = ByteBuffer.wrap(encryptedUuid);+ buffer.position(12); //Move the position to 12+ return START_VIRTUAL_ADDRESS | (buffer.getInt() & UUID_HASH_BIT_MASK);+ }++ /**+ * Returns the label UUID for a given virtual address+ *+ * @param address 16-bit virtual address+ */+ public static UUID getLabelUuid(final List<UUID> uuids, final int address) {+ if (MeshAddress.isValidVirtualAddress(address)) {+ for (UUID uuid : uuids) {+ final byte[] salt = SecureUtils.calculateSalt(VTAD);+ //Encrypt the label uuid with the salt as the key+ final byte[] encryptedUuid = SecureUtils.calculateCMAC(MeshParserUtils.uuidToBytes(uuid), salt);+ ByteBuffer buffer = ByteBuffer.wrap(encryptedUuid);+ buffer.position(12); //Move the position to 12+ final int hash = buffer.getInt() & UUID_HASH_BIT_MASK;+ if (hash == getHash(address)) {+ return uuid;+ }+ }+ }+ return null;+ }++ /**+ * Returns the value of the hash from a virtual address+ * <p>+ * The hash stored in a virtual address is derived from the label UUID.+ * In a virtual address bits 13 to 0 are set to the value of a hash of the corresponding Label UUID.+ * </p>+ *+ * @param address virtual address+ */+ public static int getHash(final int address) {+ if (isValidVirtualAddress(address)) {+ return address & 0x3FFF;+ }+ return 0;+ }++ /**+ * Returns the unicast address as int+ *+ * @param unicastAddress unicast address+ * @return unicast address+ */+ public static byte[] addressIntToBytes(final int unicastAddress) {+ return new byte[]{(byte) ((unicastAddress >> 8) & 0xFF), (byte) (unicastAddress & 0xFF)};+ }++ /**+ * Returns the unicast address as int+ *+ * @param unicastAddress unicast address+ * @return unicast address+ */+ public static short addressBytesToInt(final byte[] unicastAddress) {+ return ByteBuffer.wrap(unicastAddress).order(ByteOrder.BIG_ENDIAN).getShort();+ }++ /**+ * Validates if the address is a valid Heartbeat publicaiton destination.+ * A valid address shall be an unassigned address, a unicast address, or a group address,+ * all other values are Prohibited.+ *+ * @param address address+ * @return true if valid or false otherwise.+ */+ public static boolean isValidHeartbeatPublicationDestination(final int address) {+ return isValidUnassignedAddress(address) ||+ isValidUnicastAddress(address) ||+ isValidGroupAddress(address) ||+ isValidFixedGroupAddress(address);+ }++ /**+ * Validates if the address is a valid Heartbeat subscription source.+ * A valid address shall be an unassigned address, a unicast address.+ * All other values are Prohibited.+ *+ * @param address address+ * @return true if valid or false otherwise.+ * @throws IllegalArgumentException if the address is not the unassigned address or a unicast address.+ */+ public static boolean isValidHeartbeatSubscriptionSource(final int address) {+ if (isValidUnassignedAddress(address) || isValidUnicastAddress(address))+ return true;+ else+ throw new IllegalArgumentException("Source address must be an unassigned address or a unicast address!");+ }++ /**+ * Validates if the address is a valid Heartbeat subscription source.+ * A valid address shall be an unassigned address, a primary unicast address of the node, or a group address,+ * All other values are Prohibited.+ *+ * @param address address+ * @return true if valid or false otherwise.+ */+ public static boolean isValidHeartbeatSubscriptionDestination(final int address) {+ if (isValidUnassignedAddress(address) ||+ isValidUnicastAddress(address) ||+ isValidGroupAddress(address))+ return true;+ else+ throw new IllegalArgumentException("Destination address must be an unassigned address, " ++ "a primary unicast address, or a group address!");+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/MeshParserUtils.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/MeshParserUtils.javanew file mode 100644index 000000000..6ccbbbe83--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/MeshParserUtils.java@@ -0,0 +1,788 @@+package org.openremote.agent.protocol.bluetooth.mesh.utils;++import javax.validation.constraints.NotNull;+import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.text.SimpleDateFormat;+import java.util.Date;+import java.util.List;+import java.util.Locale;+import java.util.Map;+import java.util.Objects;+import java.util.Random;+import java.util.TreeMap;+import java.util.UUID;+import java.util.logging.Logger;++import org.openremote.agent.protocol.bluetooth.mesh.NodeKey;+import org.openremote.model.syslog.SyslogCategory;+import org.openremote.model.util.TextUtil;++import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;++public class MeshParserUtils {++ public static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, MeshParserUtils.class);++ private static final String TAG = MeshParserUtils.class.getSimpleName();+ private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US);+ private static final String PATTERN_KEY = "[0-9a-fA-F]{32}";+ private static final String PATTERN_UUID_HEX = "[0-9a-fA-F]{32}";++ private static final int PROHIBITED_DEFAULT_TTL_STATE_MIN = 0x01;+ private static final int PROHIBITED_DEFAULT_TTL_STATE_MID = 0x80;+ private static final int PROHIBITED_DEFAULT_TTL_STATE_MAX = 0xFF;+ public static final int USE_DEFAULT_TTL = 0xFF;++ private static final int MIN_TTL = 0x00;+ private static final int MAX_TTL = 0x7F;+ private static final int PROHIBITED_PUBLISH_TTL_MIN = 0x80;+ private static final int PROHIBITED_PUBLISH_TTL_MAX = 0xFE;++ private static final int IV_ADDRESS_MIN = 0;+ private static final int IV_ADDRESS_MAX = 4096;+ private static final int UNICAST_ADDRESS_MIN = 0;+ private static final char[] HEX_ARRAY = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};+ private static final byte[] ALPHANUMERIC = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F',+ 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};++ private static final int[] M_NUMERIC_MAX = {0, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000};++ public static final int RESOLUTION_100_MS = 0b00;+ public static final int RESOLUTION_1_S = 0b01;+ public static final int RESOLUTION_10_S = 0b10;+ public static final int RESOLUTION_10_M = 0b11;++ public static final int GENERIC_ON_OFF_5_MS = 5;++ public static String bytesToHex(final byte[] bytes, final boolean add0x) {+ if (bytes == null)+ return "";+ return bytesToHex(bytes, 0, bytes.length, add0x);+ }++ public static String bytesToHex(final byte[] bytes, final int start, final int length, final boolean add0x) {+ if (bytes == null || bytes.length <= start || length <= 0)+ return "";++ final int maxLength = Math.min(length, bytes.length - start);+ final char[] hexChars = new char[maxLength * 2];+ for (int j = 0; j < maxLength; j++) {+ final int v = bytes[start + j] & 0xFF;+ hexChars[j * 2] = HEX_ARRAY[v >>> 4];+ hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];+ }+ if (!add0x)+ return new String(hexChars);+ return "0x" + new String(hexChars);+ }++ public static byte[] toByteArray(String hexString) {+ int len = hexString.length();+ byte[] bytes = new byte[len / 2];+ for (int i = 0; i < len; i += 2) {+ bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)+ + Character.digit(hexString.charAt(i + 1), 16));+ }+ return bytes;+ }++ private static boolean isValidKeyIndex(final Integer value) {+ return value == null || value != (value & 0xFFF);+ }++ /**+ * Checks if the IV Index is valid.+ *+ * <p>+ * The IV Index is a 32-bit value that is a shared network resource+ * (i.e., all nodes in a mesh network share the same value of the IV Index+ * and use it for all subnets they belong to). The IV Index starts at 0x00000000+ * </p>+ *+ * @param ivIndex IV Index value+ */+ private static boolean isValidIvIndex(@NotNull final Integer ivIndex) {+ Objects.requireNonNull(ivIndex);+ return ivIndex == 0 || ivIndex > 0;+ }++ public static byte parseUpdateFlags(final int keyRefreshFlag, final int ivUpdateFlag) {+ byte flags = 0;+ if (keyRefreshFlag == 1) {+ flags |= 0b01;+ } else {+ flags &= ~0b01;+ }++ if (ivUpdateFlag == 1) {+ flags |= 0b10;+ } else {+ flags &= ~0b01;+ }+ return flags;+ }++ public static int getBitValue(final int value, final int position) {+ return (value >> position) & 1;+ }++ public static byte[] addKeyIndexPadding(final Integer keyIndex) {+ return ByteBuffer.allocate(2).order(ByteOrder.BIG_ENDIAN).putShort((short) (keyIndex & 0x0FFF)).array();+ }++ public static int removeKeyIndexPadding(final byte[] keyIndex) {+ return keyIndex[0] & 0x0F | keyIndex[1];+ }++ /**+ * Validates the network key input+ *+ * @param networkKey Network Key input+ * @return true if the Network Key is a valid value+ * @throws IllegalArgumentException in case of an invalid was entered as an input and the message containing the error+ */+ public static boolean validateNetworkKeyInput(@NotNull final String networkKey) throws IllegalArgumentException {++ if (TextUtil.isNullOrEmpty(networkKey)) {+ throw new IllegalArgumentException("Network key cannot be empty!");+ } else if (!networkKey.matches(PATTERN_KEY)) {+ throw new IllegalArgumentException("Network key must be 16 bytes long!");+ }++ return true;+ }++ /**+ * Validates the Key Index input+ *+ * @param input Key Index input+ * @return true if the Key Index is a valid value+ * @throws IllegalArgumentException in case of an invalid was entered as an input and the message containing the error+ */+ public static boolean validateKeyIndexInput(final String input) throws IllegalArgumentException {++ if (TextUtil.isNullOrEmpty(input)) {+ throw new IllegalArgumentException("Key index cannot be empty!");+ }++ final int keyIndex;++ try {+ keyIndex = Integer.parseInt(input);+ } catch (NumberFormatException ex) {+ throw new IllegalArgumentException("Key index must be 0 to 4095!");+ }+ if (isValidKeyIndex(keyIndex)) {+ throw new IllegalArgumentException("Key index must be 0 to 4095!");+ }++ return true;+ }++ /**+ * Validates the IV Index input+ *+ * @param input IV Index input+ * @return true if the the value is valid+ * @throws IllegalArgumentException in case of an invalid was entered as an input and the message containing the error+ */+ public static boolean validateIvIndexInput(final String input) throws IllegalArgumentException {++ if (TextUtil.isNullOrEmpty(input)) {+ throw new IllegalArgumentException("IV Index cannot be empty!");+ }++ final int ivIndex;+ try {+ ivIndex = Integer.parseInt(input, 16);+ } catch (NumberFormatException ex) {+ throw new IllegalArgumentException("IV Index must be 0 to 4294967295!");+ }++ if (!isValidIvIndex(ivIndex)) {+ throw new IllegalArgumentException("IV Index must be 0 to 4294967295!");+ }++ return true;+ }++ /**+ * Validates the IV Index input+ *+ * @param ivIndex IV Index input+ * @return true if the the value is valid+ * @throws IllegalArgumentException in case of an invalid was entered as an input and the message containing the error+ */+ public static boolean validateIvIndexInput(final Integer ivIndex) throws IllegalArgumentException {+ if (ivIndex == null) {+ throw new IllegalArgumentException("IV Index cannot be empty!");+ }++ if (!isValidIvIndex(ivIndex)) {+ throw new IllegalArgumentException("IV Index must be 0 to 4294967295!");+ }++ return true;+ }++ /**+ * Validates the key input+ *+ * @param key key+ * @return true if the Key is a valid value+ * @throws IllegalArgumentException in case of an invalid was entered as an input and the message containing the error+ */+ public static boolean validateKeyInput(@NotNull final String key) throws IllegalArgumentException {+ if (TextUtil.isNullOrEmpty(key)) {+ throw new IllegalArgumentException("Key cannot be empty!");+ } else if (!key.matches(PATTERN_KEY)) {+ throw new IllegalArgumentException("key must be a 32-character hexadecimal string!");+ }++ return true;+ }++ public static boolean isValidSequenceNumber(final int sequenceNumber) {++ boolean flag = sequenceNumber == (sequenceNumber & 0xFFFFFF);++ if (sequenceNumber == 0xFFFFFF) {+ flag = false;+ }+ return flag;+ }++ public static byte[] getSequenceNumberBytes(int sequenceNumber) {+ if (MeshParserUtils.isValidSequenceNumber(sequenceNumber)) {+ return new byte[]{(byte) ((sequenceNumber >> 16) & 0xFF), (byte) ((sequenceNumber >> 8) & 0xFF), (byte) (sequenceNumber & 0xFF)};+ }+ return null;+ }++ public static int convert24BitsToInt(@NotNull final byte[] byteArray) {+ Objects.requireNonNull(byteArray);+ if (byteArray.length != 3)+ throw new IllegalArgumentException("Invalid length, byte array must be 3-bytes long.");+ return (((byteArray[0] & 0xFF) << 16) | ((byteArray[1] & 0xFF) << 8) | (byteArray[2] & 0xFF));+ }++ public static int getSequenceNumberFromPDU(final byte[] pdu) {+ return convert24BitsToInt(new byte[]{pdu[3], pdu[4], pdu[5]}); // get sequence number array from pdu+ }++ public static int calculateSeqZero(final byte[] sequenceNumber) {+ return ((sequenceNumber[1] & 0x1F) << 8) | (sequenceNumber[2] & 0xFF); // 13 least significant bits+ }++ public static byte[] getSrcAddress(final byte[] pdu) {+ return ByteBuffer.allocate(2).put(pdu, 6, 2).array(); // get src address from pdu+ }++ public static byte[] getDstAddress(final byte[] pdu) {+ return ByteBuffer.allocate(2).put(pdu, 8, 2).array(); // get mDst address from pdu+ }++ /*+ private static int getSegmentedMessageLength(final SparseArray<byte[]> segmentedMessageMap) {+ int length = 0;+ for (int i = 0; i < segmentedMessageMap.size(); i++) {+ length += segmentedMessageMap.get(i).length;+ }+ return length;+ }+ */+ private static int getSegmentedMessageLength(final Map<Integer, byte[]> segmentedMessages) {+ int length = 0;+ for (byte[] curSegment : segmentedMessages.values()) {+ length += curSegment.length;+ }+ return length;+ }++ /*+ public static byte[] concatenateSegmentedMessages(final SparseArray<byte[]> segmentedMessages) {+ final int length = getSegmentedMessageLength(segmentedMessages);+ final ByteBuffer completeBuffer = ByteBuffer.allocate(length);+ completeBuffer.order(ByteOrder.BIG_ENDIAN);+ for (int i = 0; i < segmentedMessages.size(); i++) {+ completeBuffer.put(segmentedMessages.get(i));+ }+ return completeBuffer.array();+ }+ */++ public static byte[] concatenateSegmentedMessages(final Map<Integer, byte[]> segmentedMessages) {+ final int length = getSegmentedMessageLength(segmentedMessages);+ final ByteBuffer completeBuffer = ByteBuffer.allocate(length);+ completeBuffer.order(ByteOrder.BIG_ENDIAN);+ //for (int i = 0; i < segmentedMessages.size(); i++) {+ // completeBuffer.put(segmentedMessages.get(i));+ //}+ TreeMap<Integer, byte[]> sortedMap = new TreeMap<>(segmentedMessages);+ for (Integer index : sortedMap.keySet()) {+ completeBuffer.put(sortedMap.get(index));+ }+ return completeBuffer.array();+ }++ /**+ * Returns the opcode within the access payload+ *+ * @param accessPayload payload+ * @return array of opcodes+ */+ public static int getOpCode(final byte[] accessPayload, final int opCodeCount) {+ switch (opCodeCount) {+ case 1:+ return accessPayload[0];+ case 2:+ return unsignedBytesToInt(accessPayload[1], accessPayload[0]);+ default:+ return unsignedByteToInt(accessPayload[1]) << 8+ | unsignedByteToInt(accessPayload[0]) << 16+ | unsignedByteToInt(accessPayload[2]);+ }+ }++ /**+ * Returns an array of opcodes.+ * If the MSB = 0 then the length is 1+ * If the MSB = 1 then the length is 2+ * If the MSB = 2 then the length is 3+ *+ * @param opCode operation code+ */+ public static byte[] getOpCode(final int opCode) {+ if (opCode < 0x80) {+ return new byte[]{(byte) (opCode & 0xFF)};+ } else if (opCode < 0x4000 || (opCode & 0xFFFC00) == 0x8000) {+ return new byte[]{(byte) (0x80 | ((opCode >> 8) & 0x3F)), (byte) (opCode & 0xFF)};+ } else {+ return new byte[]{(byte) (0xC0 | ((opCode >> 16) & 0x3F)),+ (byte) ((opCode >> 8) & 0xFF),+ (byte) (opCode & 0xFF)};+ }+ }++ /**+ * Returns the length of the opcode.+ * If the MSB = 0 then the length is 1+ * If the MSB = 1 then the length is 2+ * If the MSB = 2 then the length is 3+ *+ * @param mostSignificantOpcodeByte operation code+ * @return length of opcodes+ */+ public static int getOpCodeLength(final int mostSignificantOpcodeByte) {+ if (mostSignificantOpcodeByte < 0x80) {+ return 1;+ } else if (/*mostSignificantOpcodeByte >= 0x80 &&*/ mostSignificantOpcodeByte <= 0xBF) {+ return 2;+ } else {+ return 3;+ }+ }++ /**+ * Returns the vendor opcode packed with company identifier+ * If the MSB = 0 then the length is 1+ * If the MSB = 1 then the length is 2+ * If the MSB = 2 then the length is 3+ *+ * @param opCode operation code+ * @return length of opcodes+ */+ public static byte[] createVendorOpCode(final int opCode, final int companyIdentifier) {+ final byte[] opCodes = new byte[3];+ opCodes[0] = (byte) (opCode | 0xC0);+ opCodes[1] = (byte) (companyIdentifier & 0xFF);+ opCodes[2] = (byte) ((companyIdentifier >> 8) & 0xFF);+ return opCodes;+ }++ /**+ * Checks if the opcode is valid+ *+ * @param opCode opCode of mesh message+ * @return if the opcode is valid+ */+ public static boolean isValidOpcode(final int opCode) throws IllegalArgumentException {+ if (opCode != (opCode & 0xFFFFFF))+ throw new IllegalArgumentException("Invalid opcode, opcode must be 1-3 octets");++ return true;+ }++ /**+ * Checks if the parameters are within the valid range+ *+ * @param parameters opCode of mesh message+ * @return if the opcode is valid+ */+ public static boolean isValidParameters(final byte[] parameters) throws IllegalArgumentException {+ if (parameters != null && parameters.length > 379)+ throw new IllegalArgumentException("Invalid parameters, parameters must be 0-379 octets");++ return true;+ }++ /**+ * Checks if the Publication ttl value is within the allowed range where the range is 0x00 - 0x7F.+ *+ * @param ttl ttl+ * @return true if valid and false otherwise+ */+ public static boolean isValidTtl(final int ttl) {+ return ttl >= MIN_TTL && ttl <= MAX_TTL;+ }++ /**+ * Checks if the ttl value is within the allowed range.+ *+ * <p>+ * 0x00, 0x02 - 0x7F are the Default TTL states.+ * 0x01, 0x80 and 0xFF are Prohibited.+ * </p>+ *+ * @param ttl ttl+ * @return true if valid and false otherwise+ */+ public static boolean isValidDefaultTtl(final int ttl) {+ return (ttl == MIN_TTL || (ttl >= 0x02 && ttl <= MAX_TTL));+ }++ /**+ * Checks if the default publish ttl is used for publication+ *+ * @param publishTtl publish ttl+ * @return true if valid and false otherwise+ */+ public static boolean isDefaultPublishTtl(final int publishTtl) {+ return publishTtl == USE_DEFAULT_TTL;+ }++ /**+ * Checks if the retransmit count is within the allowed range+ *+ * @param retransmitCount publish ttl+ * @return true if valid and false otherwise+ */+ public static boolean validateRetransmitCount(final int retransmitCount) {+ return retransmitCount == (retransmitCount & 0b111);+ }++ /**+ * Checks if the publish retransmit interval steps is within the allowed range+ *+ * @param intervalSteps publish ttl+ * @return true if valid and false otherwise+ */+ public static boolean validatePublishRetransmitIntervalSteps(final int intervalSteps) {+ return intervalSteps == (intervalSteps & 0b11111);+ }++ /**+ * Returns the remaining time as a string+ *+ * @param remainingTime remaining time that for the transition to finish+ * @return remaining time as string.+ */+ public static String getRemainingTime(final int remainingTime) {+ final int stepResolution = remainingTime >> 6;+ final int numberOfSteps = remainingTime & 0x3F;+ switch (stepResolution) {+ case RESOLUTION_100_MS:+ return (numberOfSteps * 100) + " milliseconds";+ case RESOLUTION_1_S:+ return numberOfSteps + " seconds";+ case RESOLUTION_10_S:+ return (numberOfSteps * 10) + " seconds";+ case RESOLUTION_10_M:+ return (numberOfSteps * 10) + " minutes";+ default:+ return "Unknown";+ }+ }++ /**+ * Returns the remaining time as a string+ *+ * @return remaining time as string.+ */+ public static String getRemainingTransitionTime(final int stepResolution, final int numberOfSteps) {+ switch (stepResolution) {+ case RESOLUTION_100_MS:+ return (numberOfSteps * 100) + " ms";+ case RESOLUTION_1_S:+ return numberOfSteps + " s";+ case RESOLUTION_10_S:+ return (numberOfSteps * 10) + " s";+ case RESOLUTION_10_M:+ return (numberOfSteps * 10) + " min.";+ default:+ return "Unknown";+ }+ }++ /**+ * Returns the remaining time in milliseconds+ *+ * @param resolution time resolution+ * @param steps number of steps+ * @return time in milliseconds+ */+ public static int getRemainingTime(final int resolution, final int steps) {+ switch (resolution) {+ case RESOLUTION_100_MS:+ return (steps * 100);+ case RESOLUTION_1_S:+ return steps * 1000;+ case RESOLUTION_10_S:+ return (steps * 10) * 1000;+ case RESOLUTION_10_M:+ return (steps * 10) * 1000 * 60;+ }+ return 0;+ }++ public static int getValue(final byte[] bytes) {+ if (bytes == null || bytes.length != 2)+ return 0;+ return unsignedToSigned(unsignedBytesToInt(bytes[0], bytes[1]), 16);+ }++ /**+ * Convert a signed byte to an unsigned int.+ */+ public static int unsignedByteToInt(byte b) {+ return b & 0xFF;+ }++ /**+ * Convert signed bytes to a 16-bit unsigned int.+ */+ public static int unsignedBytesToInt(byte b0, byte b1) {+ return (unsignedByteToInt(b0) + (unsignedByteToInt(b1) << 8));+ }++ public static int bytesToInt(@NotNull byte[] b) {+ Objects.requireNonNull(b);+ return b.length == 4 ? ByteBuffer.wrap(b).order(ByteOrder.BIG_ENDIAN).getInt() : ByteBuffer.wrap(b).order(ByteOrder.BIG_ENDIAN).getShort();+ }++ public static int hexToInt(String hex) {+ return MeshParserUtils.bytesToInt(MeshParserUtils.toByteArray(hex));+ }++ public static byte[] intToBytes(int i) {+ return ByteBuffer.allocate(4).putInt(i).array();+ }++ /**+ * Convert an unsigned integer value to a two's-complement encoded signed value.+ */+ private static int unsignedToSigned(int unsigned, int size) {+ if ((unsigned & (1 << size - 1)) != 0) {+ unsigned = -1 * ((1 << size - 1) - (unsigned & ((1 << size - 1) - 1)));+ }+ return unsigned;+ }++ /**+ * Returns if the model id is a vendor model+ *+ * @param modelId model identifier+ */+ public static boolean isVendorModel(final int modelId) {+ return modelId < Short.MIN_VALUE || modelId > Short.MAX_VALUE;+ }++ public static int getCompanyIdentifier(final int modelId) {+ if (modelId >= Short.MIN_VALUE && modelId <= Short.MAX_VALUE) {+ throw new IllegalArgumentException("Not a valid vendor model ID");+ }+ final ByteBuffer buffer = ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN);+ buffer.putInt(modelId);+ return buffer.getShort(0);+ }++ /**+ * Generates an oob count to be entered on the device when blink,beep,vibrate,push or twist action is selected+ *+ * <p>+ * Based on mesh profile specification v1.0.1 section 5.4.2.4 page 254+ * </p>+ *+ * @param oobSize oob size+ */+ static byte[] generateOOBCount(final int oobSize) {+ final Random random = new Random();+ final int bound = (int) Math.pow(10, oobSize) - 1;+ final byte randomByte = (byte) (random.nextInt(bound) + 1);+ LOG.info("Random OOB count: " + randomByte);+ return new byte[]{randomByte};+ }++ /**+ * Generates a random number to be entered on the device+ *+ * <p>+ * Based on mesh profile specification v1.0.1 section 5.4.2.4 page 254+ * </p>+ *+ * @param oobSize oob size+ */+ static byte[] generateOOBNumeric(final int oobSize) {+ final Random random = new Random();+ final int value = random.nextInt((int) Math.pow(10, oobSize));+ LOG.info("Random OOB numeric: " + value);+ return intToBytes(value);+ }++ /**+ * Generates a random alphanumeric code to be entered on the device+ *+ * <p>+ * Based on mesh profile specification v1.0.1 section 5.4.2.4 page 254+ * </p>+ *+ * @param oobSize oob size+ */+ static byte[] generateOOBAlphaNumeric(final int oobSize) {+ final Random random = new Random();+ final byte[] value = new byte[oobSize];+ for (int i = 0; i < oobSize; i++) {+ final int index = random.nextInt(ALPHANUMERIC.length);+ value[i] = ALPHANUMERIC[index];+ }+ LOG.info("Random OOB alpha numeric: " + new String(value));++ return value;+ }++ /**+ * Returns UUID as a hex+ *+ * @param uuid UUID+ */+ public static String uuidToHex(@NotNull final UUID uuid) {+ Objects.requireNonNull(uuid);+ return uuid.toString().replace("-", "").toUpperCase(Locale.US);+ }++ /**+ * Returns UUID as a hex+ *+ * @param uuid UUID+ */+ public static String uuidToHex(@NotNull final String uuid) {+ Objects.requireNonNull(uuid);+ return uuid.replace("-", "").toUpperCase(Locale.US);+ }++ /**+ * Returns UUID in bytes+ *+ * @param uuid UUID+ */+ public static byte[] uuidToBytes(@NotNull final UUID uuid) {+ Objects.requireNonNull(uuid);+ return toByteArray(uuid.toString().replace("-", ""));+ }++ /**+ * Formats a hex string without dashes to a uuid string+ *+ * @param uuidHex Hex string+ */+ public static String formatUuid(@NotNull final String uuidHex) {+ Objects.requireNonNull(uuidHex);+ if (isUuidPattern(uuidHex)) {+ return new StringBuffer(uuidHex)+ .insert(8, "-")+ .insert(13, "-")+ .insert(18, "-")+ .insert(23, "-")+ .toString()+ .toUpperCase(Locale.US);+ }+ return uuidHex;+ }++ public static boolean isUuidPattern(@NotNull final String uuidHex) {+ Objects.requireNonNull(uuidHex);+ return uuidHex.matches(PATTERN_UUID_HEX);+ }++ /**+ * Returns a type4 UUID from a uuid string without dashes+ *+ * @param uuidHex Hex string+ */+ public static UUID getUuid(@NotNull final String uuidHex) {+ Objects.requireNonNull(uuidHex);+ if (uuidHex.matches(PATTERN_UUID_HEX))+ return UUID.fromString(new StringBuffer(uuidHex)+ .insert(8, "-")+ .insert(4, "-")+ .insert(4, "-")+ .insert(4, "-")+ .toString());++ return null;+ }++ /**+ * Formats the timestamp+ *+ * @param timestamp timestamp+ */+ public static String formatTimeStamp(final long timestamp) {+ return SDF.format(new Date(timestamp));+ }++ public static boolean isNodeKeyExists(@NotNull final List<NodeKey> keys, final int index) {+ Objects.requireNonNull(keys);+ for (NodeKey key : keys) {+ if (key.getIndex() == index) {+ return true;+ }+ }+ return false;+ }++ public static NodeKey getNodeKey(@NotNull final List<NodeKey> keys, final int index) {+ Objects.requireNonNull(keys);+ for (NodeKey key : keys) {+ if (key.getIndex() == index) {+ return key;+ }+ }+ return null;+ }++ /**+ * Validates heart beat count log.+ *+ * @param countLog Heartbeat publication count.+ * @return true if valid.+ * @throws IllegalArgumentException if the countLog value is not a value from 0 to 17 or 255+ */+ public static boolean isValidHeartbeatCountLog(final int countLog) {+ if ((countLog >= 0x00 && countLog < 0x12) || countLog == 0xFF)+ return true;+ throw new IllegalArgumentException("Count log must be 0 to 17 or 255!");+ }++ /**+ * Validates heart beat publication ttl.+ *+ * @param ttl Heartbeat publication ttl.+ * @return true if valid or false otherwise.+ */+ public static boolean isValidHeartbeatPublicationTtl(final int ttl) {+ return ttl <= 0x7F;+ }++}\ No newline at end of filediff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/NetworkTransmitSettings.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/NetworkTransmitSettings.javanew file mode 100644index 000000000..abcfd9b88--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/NetworkTransmitSettings.java@@ -0,0 +1,65 @@+package org.openremote.agent.protocol.bluetooth.mesh.utils;++import org.openremote.agent.protocol.bluetooth.mesh.transport.ProvisionedMeshNode;++/**+ * Class containing Network Transmit values in a {@link ProvisionedMeshNode}+ */+public class NetworkTransmitSettings {+ private final int networkTransmitCount;+ private final int networkIntervalSteps;++ /**+ * Constructs {@link NetworkTransmitSettings}+ *+ * @param networkTransmitCount Number of transmissions for each Network PDU originating from the node+ * @param networkIntervalSteps Number of 10-millisecond steps between transmissions+ */+ public NetworkTransmitSettings(final int networkTransmitCount, final int networkIntervalSteps) {+ if (networkTransmitCount < 1 || networkTransmitCount > 8) {+ throw new IllegalArgumentException("Network Transmit count must be in range 1-8.");+ }+ this.networkTransmitCount = networkTransmitCount;+ this.networkIntervalSteps = networkIntervalSteps;+ }++ /**+ * Returns the network transmit count+ */+ public int getNetworkTransmitCount() {+ return networkTransmitCount;+ }++ /**+ * Returns the number of transmissions.+ */+ public int getTransmissionCount() {+ return networkTransmitCount + 1;+ }++ /**+ * Returns the network interval steps+ */+ public int getNetworkIntervalSteps() {+ return networkIntervalSteps;+ }++ /**+ * Returns the Network transmission interval.+ */+ public int getNetworkTransmissionInterval() {+ return (networkIntervalSteps + 1) * 10;+ }++ /**+ * Decodes the Network Transmission Interval steps+ * @param interval Interval between 10-320 ms with a step of 10 ms+ * @return the interval as steps+ * @throws IllegalArgumentException if the Network Transmission Interval is not 10-320 ms with a step of 10 ms+ */+ public static int decodeNetworkTransmissionInterval(final int interval) {+ if ((interval >= 10 && interval <= 320) && (interval % 10 != 0))+ throw new IllegalArgumentException("Network Transmission Interval must be 10-320 ms with a step of 10 ms");+ return (interval / 10) - 1;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/OutputOOBAction.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/OutputOOBAction.javanew file mode 100644index 000000000..ee0ba5deb--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/OutputOOBAction.java@@ -0,0 +1,169 @@+package org.openremote.agent.protocol.bluetooth.mesh.utils;++import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.ArrayList;+import java.util.Locale;+import java.util.logging.Logger;++public enum OutputOOBAction {++ /**+ * Output OOB Actions+ */+ NO_OUTPUT((short) 0x0000),+ BLINK((short) 0x0001),+ BEEP((short) 0x0002),+ VIBRATE((short) 0x0004),+ OUTPUT_NUMERIC((short) 0x0008),+ OUTPUT_ALPHA_NUMERIC((short) 0x0010);++ private static final Logger LOG = java.util.logging.Logger.getLogger(OutputOOBAction.class.getName());+ private short outputOOBAction;++ OutputOOBAction(final short outputOOBAction) {+ this.outputOOBAction = outputOOBAction;+ }++ public short getOutputOOBAction() {+ return outputOOBAction;+ }++ /**+ * Returns the oob method used for authentication+ *+ * @param method auth method used+ */+ public static OutputOOBAction fromValue(final short method) {+ switch (method) {+ default:+ case 0x0000:+ return NO_OUTPUT;+ case 0x0001:+ return BLINK;+ case 0x0002:+ return VIBRATE;+ case 0x0004:+ return VIBRATE;+ case 0x0008:+ return OUTPUT_NUMERIC;+ case 0x0010:+ return OUTPUT_ALPHA_NUMERIC;+ }+ }++ /**+ * Returns the Output OOB Action description+ *+ * @param type Output OOB type+ * @return Input OOB type descrption+ */+ public static String getOutputOOBActionDescription(final OutputOOBAction type) {+ switch (type) {+ case NO_OUTPUT:+ return "Not Supported";+ case BLINK:+ return "Blink";+ case BEEP:+ return "Beep";+ case VIBRATE:+ return "Vibrate";+ case OUTPUT_NUMERIC:+ return "Output Numeric";+ case OUTPUT_ALPHA_NUMERIC:+ return "Output Alpha Numeric";+ default:+ return "Unknown";+ }+ }++ /**+ * Parses the output oob action value+ *+ * @param outputAction type of output action+ * @return selected output action type+ */+ public static ArrayList<OutputOOBAction> parseOutputActionsFromBitMask(final int outputAction) {+ final OutputOOBAction[] outputActions = {BLINK, BEEP, VIBRATE, OUTPUT_NUMERIC, OUTPUT_ALPHA_NUMERIC};+ final ArrayList<OutputOOBAction> supportedActionValues = new ArrayList<>();+ for (OutputOOBAction action : outputActions) {+ if ((outputAction & action.outputOOBAction) == action.outputOOBAction) {+ supportedActionValues.add(action);+ LOG.info("Supported output oob action type: " + getOutputOOBActionDescription(action));+ }+ }+ return supportedActionValues;+ }++ /**+ * Returns the Output OOB Action value+ *+ * @param type output OOB type+ */+ public static int getOutputOOBActionValue(final OutputOOBAction type) {+ switch (type) {+ case BLINK:+ return 0;+ case BEEP:+ return 1;+ case VIBRATE:+ return 2;+ case OUTPUT_NUMERIC:+ return 3;+ case OUTPUT_ALPHA_NUMERIC:+ return 4;+ case NO_OUTPUT:+ default:+ return 0;+ }+ }++ /**+ * Returns the Output OOB Action value+ *+ * @param actionType output OOB action type+ */+ public static int getOutputOOBActionValue(final short actionType) {+ switch (fromValue(actionType)) {+ case BLINK:+ return 0;+ case BEEP:+ return 1;+ case VIBRATE:+ return 2;+ case OUTPUT_NUMERIC:+ return 3;+ case OUTPUT_ALPHA_NUMERIC:+ return 4;+ case NO_OUTPUT:+ default:+ return 0;+ }+ }++ /**+ * Creates 128-bit authentication value+ *+ * @param outputActionType selected {@link OutputOOBAction}+ * @param input input+ */+ public static byte[] generateOutputOOBAuthenticationValue(final OutputOOBAction outputActionType, final String input) {+ final int authLength = 16;+ final ByteBuffer buffer = ByteBuffer.allocate(authLength).order(ByteOrder.BIG_ENDIAN);+ switch (outputActionType) {+ case BLINK:+ case BEEP:+ case VIBRATE:+ case OUTPUT_NUMERIC:+ buffer.position(8);+ final long intValue = Long.valueOf(input);+ buffer.putLong(intValue);+ return buffer.array();+ case OUTPUT_ALPHA_NUMERIC:+ buffer.put(input.toUpperCase(Locale.US).getBytes());+ return buffer.array();+ default:+ return null;+ }+ }+}\ No newline at end of filediff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/ProxyFilter.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/ProxyFilter.javanew file mode 100644index 000000000..909bf24c7--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/ProxyFilter.java@@ -0,0 +1,92 @@+package org.openremote.agent.protocol.bluetooth.mesh.utils;++import java.util.ArrayList;+import java.util.Arrays;+import java.util.Collections;+import java.util.List;++/**+ * Contains the proxy filter configuration set to a node+ */+public class ProxyFilter {+ private final ProxyFilterType filterType;+ private final List<AddressArray> addresses = new ArrayList<>();++ /**+ * Constructs the proxy filter+ *+ * @param filterType Filter type based on+ */+ public ProxyFilter(final ProxyFilterType filterType) {+ this.filterType = filterType;+ }++ /**+ * Returns the {@link ProxyFilterType} that was set+ */+ public ProxyFilterType getFilterType() {+ return filterType;+ }++ /**+ * Returns the list of addresses containing {@link AddressArray} added to the proxy filter+ */+ public List<AddressArray> getAddresses() {+ return Collections.unmodifiableList(addresses);+ }++ /**+ * Adds an address to the ProxyFilter+ *+ * @param addressArray address to be added+ */+ public void addAddress(final AddressArray addressArray) {+ if (!contains(addressArray)) {+ addresses.add(addressArray);+ }+ }++ /**+ * Checks is the address exists within the list of proxy filter addresses.+ *+ * @param addressArray address+ */+ private boolean contains(final AddressArray addressArray) {+ for (AddressArray arr : addresses) {+ if (Arrays.equals(addressArray.getAddress(), arr.getAddress())) {+ return true;+ }+ }+ return false;+ }++ /**+ * Checks is the address exists within the list of proxy filter addresses.+ * <p>+ * Currently does not support virtual addresses.+ * </p>+ *+ * @param address Unicast, Group address+ */+ public final boolean contains(final byte[] address) {+ if (MeshAddress.isValidUnicastAddress(address) || MeshAddress.isValidSubscriptionAddress(address)) {+ final AddressArray addressArray = new AddressArray(address[0], address[1]);+ for (AddressArray arr : addresses) {+ if (Arrays.equals(addressArray.getAddress(), arr.getAddress())) {+ return true;+ }+ }+ }+ return false;+ }++ /**+ * Removes an address from the ProxyFilter+ *+ * @param addressArray address to be removed+ */+ public void removeAddress(final AddressArray addressArray) {+ addresses.remove(addressArray);+ }++}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/ProxyFilterType.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/ProxyFilterType.javanew file mode 100644index 000000000..08589eae6--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/ProxyFilterType.java@@ -0,0 +1,58 @@+package org.openremote.agent.protocol.bluetooth.mesh.utils;++/**+ * Wrapper class for proxy filter types+ */+public class ProxyFilterType {++ // @IntDef({INCLUSION_LIST_FILTER, EXCLUSION_LIST_FILTER})+ // public @interface FilterTypes {+ // }++ /**+ * A inclusion list filter has an associated inclusion list, which is a list of destination addresses+ * that are of interest for the Proxy Client. The inclusion list filter blocks all destination addresses+ * except those that have been added to the inclusion list.+ */+ public static final int INCLUSION_LIST_FILTER = 0x00; //inclusion list filter type++ /**+ * A exclusion list filter has an associated exclusion list, which is a list of destination addresses+ * that the Proxy Client does not want to receive. The exclusion list filter accepts all destination addresses+ * except those that have been added to the exclusion list.+ */+ public static final int EXCLUSION_LIST_FILTER = 0x01; //The node supports Relay feature that is enabled++ /**+ * Filter type+ */+ private final int filterType;++ /**+ * Constructs the filter type to bet set to a proxy+ *+ * @param filterType filter type supported by the proxy+ */+ public ProxyFilterType(/*@FilterTypes*/ final int filterType) {+ this.filterType = filterType;+ }++ /**+ * Returns the filter type+ */+ /* @FilterTypes */+ public int getType() {+ return filterType;+ }++ /**+ * Returns the filter type name+ */+ public String getFilterTypeName() {+ if (filterType == INCLUSION_LIST_FILTER) {+ return "Inclusion List";+ } else {+ return "Exclusion List";+ }+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/RelaySettings.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/RelaySettings.javanew file mode 100644index 000000000..9be7e492a--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/RelaySettings.java@@ -0,0 +1,93 @@+package org.openremote.agent.protocol.bluetooth.mesh.utils;++import org.openremote.agent.protocol.bluetooth.mesh.transport.ProvisionedMeshNode;++import java.lang.annotation.Retention;+import java.lang.annotation.RetentionPolicy;++/**+ * Class containing Relay Settings values in a {@link ProvisionedMeshNode}+ */+public class RelaySettings {++ // @IntDef({RELAY_FEATURE_DISABLED, RELAY_FEATURE_ENABLED, RELAY_FEATURE_NOT_SUPPORTED})+ // public @interface RelayState {+ // }++ public static final int RELAY_FEATURE_DISABLED = 0x00; //The node support Relay feature that is disabled+ public static final int RELAY_FEATURE_ENABLED = 0x01; //The node supports Relay feature that is enabled+ public static final int RELAY_FEATURE_NOT_SUPPORTED = 0x02; //Relay feature is not supported++ private final int relayTransmitCount;+ private final int relayIntervalSteps;++ /**+ * Constructs {@link RelaySettings}+ *+ * @param relayTransmitCount Number of retransmissions on advertising bearer for each Network PDU relayed by the node+ * @param relayIntervalSteps Number of 10-millisecond steps between retransmissions+ */+ public RelaySettings(final int relayTransmitCount, final int relayIntervalSteps) {+ this.relayTransmitCount = relayTransmitCount;+ this.relayIntervalSteps = relayIntervalSteps;+ }++ //+ // Returns if relaying is supported by the node+ //+ // @param relay {@link RelayState}+ // @return true if supported and false otherwise+ //+ public static boolean isRelaySupported(/*@RelayState*/ final int relay) {+ switch (relay) {+ case RELAY_FEATURE_DISABLED:+ case RELAY_FEATURE_ENABLED:+ return true;+ case RELAY_FEATURE_NOT_SUPPORTED:+ default:+ return false;+ }+ }++ /**+ * Returns the number of retransmissions on advertising bearer for each Network PDU relayed by the node+ */+ public int getRelayTransmitCount() {+ return relayTransmitCount;+ }++ /**+ * Returns the number of total retransmissions.+ */+ public int getTotalTransmissionsCount() {+ return relayTransmitCount + 1;+ }++ /**+ * Returns the number of 10-millisecond steps between retransmissions+ */+ public int getRelayIntervalSteps() {+ return relayIntervalSteps;+ }++ /**+ * Returns the interval interval set by the relayState settings+ */+ public int getRetransmissionIntervals() {+ return (relayIntervalSteps + 1) * 10;+ }+++ /**+ * Decodes the Relay Retransmit Interval as steps+ *+ * @param interval Interval between 10-320 ms+ * @return the interval as steps+ * @throws IllegalArgumentException if the Relay Retransmit Interval is not in range of 10-320 ms+ */+ public static int decodeRelayRetransmitInterval(final int interval) {+ if ((interval >= 10 && interval <= 320) && (interval % 10 != 0))+ throw new IllegalArgumentException("Relay Retransmit Interval must be in range of 10-320 ms.");+ return (interval / 10) - 1;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/SecureUtils.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/SecureUtils.javanew file mode 100644index 000000000..701c2c62f--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/SecureUtils.java@@ -0,0 +1,495 @@+package org.openremote.agent.protocol.bluetooth.mesh.utils;++import org.bouncycastle.crypto.BlockCipher;+import org.bouncycastle.crypto.CipherParameters;+import org.bouncycastle.crypto.InvalidCipherTextException;+import org.bouncycastle.crypto.engines.AESEngine;+import org.bouncycastle.crypto.engines.AESLightEngine;+import org.bouncycastle.crypto.macs.CMac;+import org.bouncycastle.crypto.modes.CCMBlockCipher;+import org.bouncycastle.crypto.params.AEADParameters;+import org.bouncycastle.crypto.params.KeyParameter;+import org.openremote.agent.protocol.bluetooth.mesh.SecureNetworkBeacon;+import org.openremote.model.syslog.SyslogCategory;++import javax.validation.constraints.NotNull;+import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.nio.charset.Charset;+import java.security.SecureRandom;+import java.util.Objects;+import java.util.logging.Level;+import java.util.logging.Logger;++import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;+++public class SecureUtils {++ public static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, SecureUtils.class);++ /**+ * Used to calculate the confirmation key+ */+ public static final byte[] PRCK = "prck".getBytes(Charset.forName("US-ASCII"));++ /**+ * Used to calculate the session key+ */+ public static final byte[] PRSK = "prsk".getBytes(Charset.forName("US-ASCII"));+ /**+ * Used to calculate the session nonce+ */+ public static final byte[] PRSN = "prsn".getBytes(Charset.forName("US-ASCII"));+ /**+ * Used to calculate the device key+ */+ public static final byte[] PRDK = "prdk".getBytes(Charset.forName("US-ASCII"));++ /**+ * K2 Master input+ */+ public static final byte[] K2_MASTER_INPUT = {0x00};+ /**+ * Salt input for K2+ */+ public static final byte[] SMK2 = "smk2".getBytes(Charset.forName("US-ASCII"));+ /**+ * Salt input for K3+ */+ public static final byte[] SMK3 = "smk3".getBytes(Charset.forName("US-ASCII"));+ /**+ * Input for K3 data+ */+ public static final byte[] SMK3_DATA = "id64".getBytes(Charset.forName("US-ASCII"));+ /**+ * Salt input for K4+ */+ public static final byte[] SMK4 = "smk4".getBytes(Charset.forName("US-ASCII"));+ /**+ * Input for K4 data+ */+ public static final byte[] SMK4_DATA = "id6".getBytes(Charset.forName("US-ASCII"));+ /**+ * Output mask for K4+ */+ public static final int ENC_K4_OUTPUT_MASK = 0x3f;+ //For S1, the key is constant+ protected static final byte[] SALT_KEY = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};+ //Padding for the random nonce+ protected static final byte[] NONCE_PADDING = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};+ private static final String TAG = SecureUtils.class.getSimpleName();+ /**+ * Salt input for identity key+ */+ private static final byte[] NKIK = "nkik".getBytes(Charset.forName("US-ASCII"));++ /**+ * Salt input for beacon key+ */+ private static final byte[] NKBK = "nkbk".getBytes(Charset.forName("US-ASCII"));+ /**+ * Salt input for identity key+ */+ private static final byte[] ID128 = "id128".getBytes(Charset.forName("US-ASCII"));+ //Padding for the random nonce+ private static final byte[] HASH_PADDING = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};+ private static final int HASH_LENGTH = 8;+ public static int NRF_MESH_KEY_SIZE = 16;++ public static byte[] generateRandomNumber() {+ final SecureRandom random = new SecureRandom();+ final byte[] randomBytes = new byte[16];+ random.nextBytes(randomBytes);++ return randomBytes;+ }++ public static String generateRandomNetworkKey() {+ final byte[] networkKey = generateRandomNumber();+ return MeshParserUtils.bytesToHex(networkKey, false);+ }++ public static String generateRandomApplicationKey() {+ return MeshParserUtils.bytesToHex(generateRandomNumber(), false);+ }++ public static byte[] calculateSalt(final byte[] data) {+ return calculateCMAC(data, SALT_KEY);+ }++ public static byte[] calculateCMAC(final byte[] data, final byte[] key) {+ final byte[] cmac = new byte[16];++ CipherParameters cipherParameters = new KeyParameter(key);+ BlockCipher blockCipher = new AESEngine();+ CMac mac = new CMac(blockCipher);++ mac.init(cipherParameters);+ mac.update(data, 0, data.length);+ mac.doFinal(cmac, 0);+ return cmac;+ }++ public static byte[] encryptCCM(@NotNull final byte[] data,+ @NotNull final byte[] key,+ @NotNull final byte[] nonce,+ final int micSize) {+ Objects.requireNonNull(data);+ Objects.requireNonNull(key);+ Objects.requireNonNull(nonce);++ final byte[] ccm = new byte[data.length + micSize];++ final CCMBlockCipher ccmBlockCipher = new CCMBlockCipher(new AESEngine());+ final AEADParameters aeadParameters = new AEADParameters(new KeyParameter(key), micSize * 8, nonce);+ ccmBlockCipher.init(true, aeadParameters);+ ccmBlockCipher.processBytes(data, 0, data.length, ccm, data.length);+ try {+ ccmBlockCipher.doFinal(ccm, 0);+ return ccm;+ } catch (InvalidCipherTextException e) {+ LOG.log(Level.SEVERE, "Error while encrypting: " + e.getMessage(), e);+ return null;+ }+ }++ public static byte[] encryptCCM(@NotNull final byte[] data,+ @NotNull final byte[] key,+ @NotNull final byte[] nonce,+ @NotNull final byte[] additionalData,+ final int micSize) {+ Objects.requireNonNull(data);+ Objects.requireNonNull(key);+ Objects.requireNonNull(nonce);+ Objects.requireNonNull(additionalData);++ final byte[] ccm = new byte[data.length + micSize];++ final CCMBlockCipher ccmBlockCipher = new CCMBlockCipher(new AESEngine());+ final AEADParameters aeadParameters = new AEADParameters(new KeyParameter(key), micSize * 8, nonce, additionalData);+ ccmBlockCipher.init(true, aeadParameters);+ ccmBlockCipher.processBytes(data, 0, data.length, ccm, data.length);+ try {+ ccmBlockCipher.doFinal(ccm, 0);+ return ccm;+ } catch (InvalidCipherTextException e) {+ LOG.log(Level.SEVERE, "Error while encrypting: " + e.getMessage(), e);+ return null;+ }+ }++ public static byte[] decryptCCM(@NotNull final byte[] data,+ @NotNull final byte[] key,+ @NotNull final byte[] nonce,+ final int micSize) throws InvalidCipherTextException {+ Objects.requireNonNull(data);+ Objects.requireNonNull(key);+ Objects.requireNonNull(nonce);++ final byte[] ccm = new byte[data.length - micSize];++ final CCMBlockCipher ccmBlockCipher = new CCMBlockCipher(new AESEngine());+ final AEADParameters aeadParameters = new AEADParameters(new KeyParameter(key), micSize * 8, nonce);+ ccmBlockCipher.init(false, aeadParameters);+ ccmBlockCipher.processBytes(data, 0, data.length, ccm, 0);+ ccmBlockCipher.doFinal(ccm, 0);+ return ccm;+ }++ public static byte[] decryptCCM(@NotNull final byte[] data,+ @NotNull final byte[] key,+ @NotNull final byte[] nonce,+ @NotNull final byte[] additionalData,+ final int micSize) throws InvalidCipherTextException {+ Objects.requireNonNull(data);+ Objects.requireNonNull(key);+ Objects.requireNonNull(nonce);+ Objects.requireNonNull(additionalData);++ final byte[] ccm = new byte[data.length - micSize];++ final CCMBlockCipher ccmBlockCipher = new CCMBlockCipher(new AESEngine());+ final AEADParameters aeadParameters = new AEADParameters(new KeyParameter(key), micSize * 8, nonce, additionalData);+ ccmBlockCipher.init(false, aeadParameters);+ ccmBlockCipher.processBytes(data, 0, data.length, ccm, 0);+ ccmBlockCipher.doFinal(ccm, 0);+ return ccm;+ }++ public static byte[] calculateK1(final byte[] ecdh, final byte[] confirmationSalt, final byte[] text) {+ return calculateCMAC(text, calculateCMAC(ecdh, confirmationSalt));+ }++ /**+ * Calculate k2+ *+ * @param data network key+ * @param p master input+ */+ public static K2Output calculateK2(final byte[] data, final byte[] p) {+ if (data == null || p == null)+ return null;++ final byte[] salt = calculateSalt(SMK2);+ final byte[] t = calculateCMAC(data, salt);++ final byte[] t0 = {};+ final ByteBuffer inputBufferT0 = ByteBuffer.allocate(t0.length + p.length + 1);+ inputBufferT0.put(t0);+ inputBufferT0.put(p);+ inputBufferT0.put((byte) 0x01);+ final byte[] t1 = calculateCMAC(inputBufferT0.array(), t);+ final byte nid = (byte) (t1[15] & 0x7F);++ final ByteBuffer inputBufferT1 = ByteBuffer.allocate(t1.length + p.length + 1);+ inputBufferT1.put(t1);+ inputBufferT1.put(p);+ inputBufferT1.put((byte) 0x02);+ final byte[] encryptionKey = calculateCMAC(inputBufferT1.array(), t);++ final ByteBuffer inputBufferT2 = ByteBuffer.allocate(encryptionKey.length + p.length + 1);+ inputBufferT2.put(encryptionKey);+ inputBufferT2.put(p);+ inputBufferT2.put((byte) 0x03);+ final byte[] privacyKey = calculateCMAC(inputBufferT2.array(), t);++ return new K2Output(nid, encryptionKey, privacyKey);+ }++ /**+ * Calculate k3+ *+ * @param n network key+ */+ public static byte[] calculateK3(final byte[] n) {+ if (n == null)+ return null;++ final byte[] salt = calculateSalt(SMK3);++ final byte[] t = calculateCMAC(n, salt);++ ByteBuffer buffer = ByteBuffer.allocate(SMK3_DATA.length + 1);+ buffer.put(SMK3_DATA);+ buffer.put((byte) 0x01);+ final byte[] cmacInput = buffer.array();++ final byte[] result = calculateCMAC(cmacInput, t);++ //Only the least significant 8 bytes are returned+ final byte[] networkId = new byte[8];+ final int srcOffset = result.length - networkId.length;++ System.arraycopy(result, srcOffset, networkId, 0, networkId.length);+ return networkId;+ }++ /**+ * Calculate k4+ *+ * @param n key+ */+ public static byte calculateK4(final byte[] n) {+ if (n == null || n.length != 16)+ throw new IllegalArgumentException("Key cannot be empty and must be 16-bytes long.");++ byte[] salt = calculateSalt(SMK4);++ final byte[] t = calculateCMAC(n, salt);++ ByteBuffer buffer = ByteBuffer.allocate(SMK4_DATA.length + 1);+ buffer.put(SMK4_DATA);+ buffer.put((byte) 0x01);+ final byte[] cmacInput = buffer.array();++ final byte[] result = calculateCMAC(cmacInput, t);++ //Only the least siginificant 6 bytes are returned+ return (byte) ((result[15]) & 0x3F);+ }++ /**+ * Calculates the identity key+ *+ * @param n network key+ * @return hash value+ */+ public static byte[] calculateIdentityKey(final byte[] n) {+ if (n == null)+ return null;+ final byte[] salt = calculateSalt(NKIK);+ ByteBuffer buffer = ByteBuffer.allocate(ID128.length + 1);+ buffer.put(ID128);+ buffer.put((byte) 0x01);+ final byte[] p = buffer.array();+ return calculateK1(n, salt, p);+ }++ /**+ * Calculates the beacon key+ *+ * @param n network key+ * @return hash value+ */+ public static byte[] calculateBeaconKey(final byte[] n) {+ final byte[] salt = calculateSalt(NKBK);+ ByteBuffer buffer = ByteBuffer.allocate(ID128.length + 1);+ buffer.put(ID128);+ buffer.put((byte) 0x01);+ final byte[] p = buffer.array();+ return calculateK1(n, salt, p);+ }++ /**+ * Calculates the authentication value of secure network beacon+ *+ * @param n network key+ * @param flags flags+ * @param networkId network id of the network+ * @param ivIndex ivindex of the network+ */+ public static byte[] calculateAuthValueSecureNetBeacon(final byte[] n,+ final int flags,+ final byte[] networkId,+ final int ivIndex) {+ final int inputLength = 1 + networkId.length + 4;+ final ByteBuffer pBuffer = ByteBuffer.allocate(inputLength);+ pBuffer.put((byte) flags);+ pBuffer.put(networkId);+ pBuffer.putInt(ivIndex);+ final byte[] beaconKey = calculateBeaconKey(n);+ return calculateCMAC(pBuffer.array(), beaconKey);+ }++ /**+ * Creates the secure network beacon+ *+ * @param n network key+ * @param flags network flags, this represents the current state of hte network if key refresh/iv update is ongoing or complete+ * @param networkId unique id of the network+ * @param ivIndex iv index of the network+ */+ public static SecureNetworkBeacon createSecureNetworkBeacon(final byte[] n,+ final int flags,+ final byte[] networkId,+ final int ivIndex) {+ final byte[] authentication = calculateAuthValueSecureNetBeacon(n, flags, networkId, ivIndex);++ final int inputLength = 1 + networkId.length + 4;+ final ByteBuffer pBuffer = ByteBuffer.allocate(inputLength);+ pBuffer.put((byte) flags);+ pBuffer.put(networkId);+ pBuffer.putInt(ivIndex);+ final ByteBuffer secNetBeaconBuffer = ByteBuffer.allocate(1 + inputLength + 8);+ secNetBeaconBuffer.put((byte) 0x01);+ secNetBeaconBuffer.put(pBuffer.array());+ secNetBeaconBuffer.put(authentication, 0, 8);+ return new SecureNetworkBeacon(secNetBeaconBuffer.array());+ }++ /**+ * Calculates the secure network beacon+ *+ * @param n network key+ * @param flags network flags, this represents the current state of hte network if key refresh/iv update is ongoing or complete+ * @param networkId unique id of the network+ * @param ivIndex iv index of the network+ */+ public static byte[] calculateSecureNetworkBeacon(final byte[] n,+ final int beaconType,+ final int flags,+ final byte[] networkId,+ final int ivIndex) {+ final byte[] authentication = calculateAuthValueSecureNetBeacon(n, flags, networkId, ivIndex);++ final int inputLength = 1 + networkId.length + 4;+ final ByteBuffer pBuffer = ByteBuffer.allocate(inputLength);+ pBuffer.put((byte) flags);+ pBuffer.put(networkId);+ pBuffer.putInt(ivIndex);+ final ByteBuffer secNetBeaconBuffer = ByteBuffer.allocate(1 + inputLength + 8);+ secNetBeaconBuffer.put((byte) beaconType);+ secNetBeaconBuffer.put(pBuffer.array());+ secNetBeaconBuffer.put(authentication, 0, 8);+ return secNetBeaconBuffer.array();+ }++ /**+ * Calculates hash value for advertising with node id+ *+ * @param identityKey resolving identity key+ * @param random 64-bit random value+ * @param src unicast address of the node+ * @return hash value+ */+ public static byte[] calculateHash(final byte[] identityKey, final byte[] random, final byte[] src) {+ final int length = HASH_PADDING.length + random.length + src.length;+ final ByteBuffer bufferHashInput = ByteBuffer.allocate(length).order(ByteOrder.BIG_ENDIAN);+ bufferHashInput.put(HASH_PADDING);+ bufferHashInput.put(random);+ bufferHashInput.put(src);+ final byte[] hashInput = bufferHashInput.array();+ final byte[] hash = SecureUtils.encryptWithAES(hashInput, identityKey);++ final ByteBuffer buffer = ByteBuffer.allocate(HASH_LENGTH).order(ByteOrder.BIG_ENDIAN);+ buffer.put(hash, 8, HASH_LENGTH);++ return buffer.array();+ }++ public static byte[] encryptWithAES(final byte[] data, final byte[] key) {+ final byte[] encrypted = new byte[data.length];+ final CipherParameters cipherParameters = new KeyParameter(key);+ final AESLightEngine engine = new AESLightEngine();+ engine.init(true, cipherParameters);+ engine.processBlock(data, 0, encrypted, 0);++ return encrypted;+ }++ public static int getNetMicLength(final int ctl) {+ if (ctl == 0) {+ return 4; //length;+ } else {+ return 8; //length+ }+ }++ /**+ * Gets the transport MIC length based on the aszmic value+ *+ * @param aszmic application size message integrity check+ */+ public static int getTransMicLength(final int aszmic) {+ if (aszmic == 0) {+ return 4; //length;+ } else {+ return 8; //length+ }+ }++ public static class K2Output {+ private byte nid;+ private byte[] encryptionKey;+ private byte[] privacyKey;++ private K2Output(final byte nid, final byte[] encryptionKey, final byte[] privacyKey) {+ this.nid = nid;+ this.encryptionKey = encryptionKey;+ this.privacyKey = privacyKey;+ }++ public byte getNid() {+ return nid;+ }++ public byte[] getEncryptionKey() {+ return encryptionKey;+ }++ public byte[] getPrivacyKey() {+ return privacyKey;+ }+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/StaticOOBType.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/StaticOOBType.javanew file mode 100644index 000000000..b66235774--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/utils/StaticOOBType.java@@ -0,0 +1,32 @@+package org.openremote.agent.protocol.bluetooth.mesh.utils;++public enum StaticOOBType {++ /**+ * Static OOB Type+ */+ STATIC_OOB_AVAILABLE((short) 0x0001);++ private static final String TAG = StaticOOBType.class.getSimpleName();+ private short staticOobType;++ StaticOOBType(final short staticOobType) {+ this.staticOobType = staticOobType;+ }++ public static String parseStaticOOBActionInformation(final StaticOOBType type) {+ switch (type) {+ case STATIC_OOB_AVAILABLE:+ return "Static OOB Actions available";+ default:+ return "Static OOB Actions unavailable";+ }+ }++ /**+ * Returns the static oob type value+ */+ public short getStaticOobType() {+ return staticOobType;+ }+}diff --git a/docker-compose.yml b/docker-compose.ymlindex d5fe5d0ce..95215a710 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -13,6 +13,7 @@ version: '2.4'volumes:temp-data:postgresql-data:+ btmesh-data:services:@@ -45,6 +46,7 @@ services:KEYCLOAK_PASSWORD: ${SETUP_ADMIN_PASSWORD:-secret}manager:+ privileged: truerestart: alwaysimage: openremote/manager:${MANAGER_VERSION:-latest}depends_on:@@ -55,6 +57,8 @@ services:SETUP_ADMIN_PASSWORD: ${SETUP_ADMIN_PASSWORD:-secret}volumes:- temp-data:/tmp+ - /var/run/dbus:/var/run/dbus+ - btmesh-data:/btmesh# devices:# - /dev/ttyACM0:/dev/ttyS0diff --git a/gradle.properties b/gradle.propertiesindex 2825c0101..aefb198aa 100644--- a/gradle.properties+++ b/gradle.properties@@ -54,3 +54,4 @@ reflectionsVersion=0.9.12swaggerVersion=2.1.9jsonSchemaVersion=4.18.0hiveMQClientVersion=1.2.2+bluetoothVersion = 0.39diff --git a/project.gradle b/project.gradleindex b89789e12..f308ac8a4 100644--- a/project.gradle+++ b/project.gradle@@ -102,6 +102,9 @@ repositories {maven {url "https://pkgs.dev.azure.com/OpenRemote/OpenRemote/_packaging/OpenRemote/maven/v1"}+ maven {+ url "https://jitpack.io"+ }}// Eclipse needs help