Search in sources :

Example 51 with SerialMessage

use of org.openhab.binding.zwave.internal.protocol.SerialMessage in project openhab1-addons by openhab.

the class ZWaveAssociationCommandClass method removeAssociationMessage.

/**
     * Gets a SerialMessage with the ASSOCIATIONCMD_REMOVE command
     *
     * @param group
     *            the association group
     * @param node
     *            the node to add to the specified group
     * @return the serial message
     */
public SerialMessage removeAssociationMessage(int group, int node) {
    logger.debug("NODE {}: Creating new message for application command ASSOCIATIONCMD_REMOVE", this.getNode().getNodeId());
    SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.SendData, SerialMessagePriority.Config);
    byte[] newPayload = { (byte) this.getNode().getNodeId(), 4, (byte) getCommandClass().getKey(), (byte) ASSOCIATIONCMD_REMOVE, (byte) (group & 0xff), (byte) (node & 0xff) };
    result.setMessagePayload(newPayload);
    return result;
}
Also used : SerialMessage(org.openhab.binding.zwave.internal.protocol.SerialMessage)

Example 52 with SerialMessage

use of org.openhab.binding.zwave.internal.protocol.SerialMessage in project openhab1-addons by openhab.

the class ZWaveNodeStageAdvancer method advanceNodeStage.

/**
     * Advances the initialization stage for this node. This method is called
     * after a response is received. We don't necessarily know if the response
     * is to the frame we requested though, so to be sure the initialisation
     * gets all the information it needs, the command class itself gets queried.
     * This method also handles the sending of frames. Since the initialisation
     * phase is a busy one we try and only have one outstanding request. Again
     * though, we can't be sure that a response is aligned with the node
     * advancer request so it is possible that more than one packet can be
     * released at once, but it will constrain things.
     */
public void advanceNodeStage(SerialMessageClass eventClass) {
    // handler when we're done, but just to be sure...
    if (currentStage == ZWaveNodeInitStage.DONE) {
        return;
    }
    logger.debug("NODE {}: Node advancer - {}: queue length({}), free to send({})", node.getNodeId(), currentStage.toString(), msgQueue.size(), freeToSend);
    // the stage, then reset.
    if (wakeupCount >= 3) {
        msgQueue.clear();
        wakeupCount = 0;
    }
    // Start the retry timer
    startIdleTimer();
    // again.
    if (eventClass == null) {
        freeToSend = true;
    }
    // If the queue is not empty, then we can't advance any further.
    if (sendMessage() == true) {
        // We're still sending messages, so we're not ready to proceed.
        return;
    }
    // The stageAdvanced flag is used to tell command classes that this
    // is the first iteration.
    // During the first iteration all messages are queued. After this,
    // only outstanding requests are returned.
    // This continues until there are no requests required.
    stageAdvanced = false;
    ZWaveProductDatabase database;
    // Then we will wait for the response before continuing
    do {
        // something that is broken, or not responding to a particular request
        if (stageAdvanced == true) {
            retryCount = 0;
        } else {
            retryCount++;
            if (retryCount > MAX_RETRIES) {
                retryCount = 0;
                logger.error("NODE {}: Node advancer: Retries exceeded at {}", node.getNodeId(), currentStage.toString());
                if (currentStage.isStageMandatory() == false) {
                    // If the current stage is not mandatory, then we skip forward to the next
                    // stage.
                    logger.debug("NODE {}: Retry timout: Advancing", node.getNodeId());
                    setCurrentStage(currentStage.getNextStage());
                } else {
                    // For static stages, we MUST complete all steps otherwise we end
                    // up with incomplete information about the device.
                    // During the static stages, we use the back off timer to pace things
                    // and retry until the stage is complete
                    logger.debug("NODE {}: Retry timout: Can't advance", node.getNodeId());
                    break;
                }
            }
        }
        logger.debug("NODE {}: Node advancer: loop - {} try {}: stageAdvanced({})", node.getNodeId(), currentStage.toString(), retryCount, stageAdvanced);
        switch(currentStage) {
            case EMPTYNODE:
                logger.debug("NODE {}: Node advancer: Initialisation starting", node.getNodeId());
                break;
            case PROTOINFO:
                // If the incoming frame is the IdentifyNode, then we continue
                if (eventClass == SerialMessageClass.IdentifyNode) {
                    break;
                }
                logger.debug("NODE {}: Node advancer: PROTOINFO - send IdentifyNode", node.getNodeId());
                addToQueue(new IdentifyNodeMessageClass().doRequest(node.getNodeId()));
                break;
            case NEIGHBORS:
                // If the incoming frame is the IdentifyNode, then we continue
                if (eventClass == SerialMessageClass.GetRoutingInfo) {
                    break;
                }
                logger.debug("NODE {}: Node advancer: NEIGHBORS - send RoutingInfo", node.getNodeId());
                addToQueue(new GetRoutingInfoMessageClass().doRequest(node.getNodeId()));
                break;
            case FAILED_CHECK:
                // If this is a controller, we're done
                if (node.getDeviceClass().getSpecificDeviceClass() == Specific.PC_CONTROLLER) {
                    logger.debug("NODE {}: Node advancer: FAILED_CHECK - Controller - terminating initialisation", node.getNodeId());
                    currentStage = ZWaveNodeInitStage.DONE;
                    break;
                }
                // If the incoming frame is the IdentifyNode, then we continue
                if (eventClass == SerialMessageClass.IsFailedNodeID) {
                    break;
                }
                addToQueue(new IsFailedNodeMessageClass().doRequest(node.getNodeId()));
                break;
            case WAIT:
                logger.debug("NODE {}: Node advancer: WAIT - Listening={}, FrequentlyListening={}", node.getNodeId(), node.isListening(), node.isFrequentlyListening());
                // If the node is listening, or frequently listening, then we progress.
                if (node.isListening() == true || node.isFrequentlyListening() == true) {
                    logger.debug("NODE {}: Node advancer: WAIT - Advancing", node.getNodeId());
                    break;
                }
                // If the device supports the wakeup class, then see if we're awake
                ZWaveWakeUpCommandClass wakeUpCommandClass = (ZWaveWakeUpCommandClass) node.getCommandClass(CommandClass.WAKE_UP);
                if (wakeUpCommandClass != null && wakeUpCommandClass.isAwake() == true) {
                    logger.debug("NODE {}: Node advancer: WAIT - Node is awake", node.getNodeId());
                    break;
                }
                // If it's not listening, and not awake,
                // we'll wait a while before progressing with initialisation.
                logger.debug("NODE {}: Node advancer: WAIT - Still waiting!", node.getNodeId());
                return;
            case PING:
                // who cares!
                if (eventClass == SerialMessageClass.SendData) {
                    break;
                }
                ZWaveNoOperationCommandClass noOpCommandClass = (ZWaveNoOperationCommandClass) node.getCommandClass(CommandClass.NO_OPERATION);
                if (noOpCommandClass == null) {
                    break;
                }
                logger.debug("NODE {}: Node advancer: PING - send NoOperation", node.getNodeId());
                SerialMessage msg = noOpCommandClass.getNoOperationMessage();
                if (msg != null) {
                    // We only send out a single PING - no retries at controller
                    // level! This is to try and reduce network congestion during
                    // initialisation.
                    // For battery devices, the PING will time-out. This takes 5
                    // seconds and if there are retries, it will be 15 seconds!
                    // This will block the network for a considerable time if there
                    // are a lot of battery devices (eg. 2 minutes for 8 battery devices!).
                    msg.attempts = 1;
                    addToQueue(msg);
                }
                break;
            case SECURITY_REPORT:
                // response to come back
                if (this.node.supportsCommandClass(CommandClass.SECURITY)) {
                    ZWaveSecurityCommandClassWithInitialization securityCommandClass = (ZWaveSecurityCommandClassWithInitialization) this.node.getCommandClass(CommandClass.SECURITY);
                    // For a node restored from a config file, this may or may not return a message
                    Collection<SerialMessage> messageList = securityCommandClass.initialize(stageAdvanced);
                    // Speed up retry timer as we use this to fetch outgoing messages instead of just retries
                    retryTimer = 400;
                    if (messageList == null) {
                        // This means we're waiting for a reply or we are done
                        if (isRestoredFromConfigfile()) {
                            // Since we were restored from a config file, redo from the dynamic node stage.
                            logger.debug("NODE {}: Node advancer: Restored from file - skipping static initialisation", node.getNodeId());
                            currentStage = ZWaveNodeInitStage.SESSION_START;
                            securityCommandClass.startSecurityEncapsulationThread();
                            break;
                        } else {
                            // This node was just included, check for success or failure
                            if (securityCommandClass.wasSecureInclusionSuccessful()) {
                                logger.debug("NODE {}: Secure inclusion complete, continuing with inclusion", node.getNodeId());
                                securityCommandClass.startSecurityEncapsulationThread();
                                // TODO: DB remove
                                nodeSerializer.SerializeNode(node);
                                // retryTimer will be reset to a normal value below
                                break;
                            } else {
                                // securityCommandClass output a message about the failure
                                logger.debug("NODE {}: Since secure inclusion failed, the node must be manually excluded via habmin", node.getNodeId());
                                // Stop the retry timer
                                resetIdleTimer();
                                // Remove the security command class since without a key, it's unusable
                                node.removeCommandClass(CommandClass.SECURITY);
                                // We remove the event listener to reduce loading now that we're done
                                controller.removeEventListener(this);
                                return;
                            }
                        }
                    } else if (messageList.isEmpty()) {
                        // Let ZWaveInputThread go back and wait for an incoming message
                        return;
                    } else {
                        // Add one or more messages to the queue
                        addToQueue(messageList);
                        SerialMessage nextSecurityMessageToSend = messageList.iterator().next();
                        if (!nextSecurityMessageToSend.equals(securityLastSentMessage)) {
                            // Reset our retry count since this is a different message
                            retryCount = 0;
                            securityLastSentMessage = nextSecurityMessageToSend;
                        }
                    }
                } else {
                    // !node.supportsCommandClass(CommandClass.SECURITY)
                    if (isRestoredFromConfigfile()) {
                        // Since we were restored from a config file, redo from the dynamic node stage.
                        logger.debug("NODE {}: Node advancer: Restored from file - skipping static initialisation", node.getNodeId());
                        currentStage = ZWaveNodeInitStage.SESSION_START;
                    }
                    logger.debug("NODE {}: does not support SECURITY_REPORT, proceeding to next stage.", this.node.getNodeId());
                }
                break;
            case DETAILS:
                // If restored from a config file, redo from the dynamic node stage.
                if (isRestoredFromConfigfile()) {
                    logger.debug("NODE {}: Node advancer: Restored from file - skipping static initialisation", node.getNodeId());
                    currentStage = ZWaveNodeInitStage.SESSION_START;
                    break;
                }
                // If the incoming frame is the IdentifyNode, then we continue
                if (node.getApplicationUpdateReceived() == true) {
                    logger.debug("NODE {}: Node advancer: received RequestNodeInfo", node.getNodeId());
                    break;
                }
                logger.debug("NODE {}: Node advancer: DETAILS - send RequestNodeInfo", node.getNodeId());
                addToQueue(new RequestNodeInfoMessageClass().doRequest(node.getNodeId()));
                break;
            case MANUFACTURER:
                // If we already know the device information, then continue
                if (node.getManufacturer() != Integer.MAX_VALUE && node.getDeviceType() != Integer.MAX_VALUE && node.getDeviceId() != Integer.MAX_VALUE) {
                    break;
                }
                // try and get the manufacturerSpecific command class.
                ZWaveManufacturerSpecificCommandClass manufacturerSpecific = (ZWaveManufacturerSpecificCommandClass) node.getCommandClass(CommandClass.MANUFACTURER_SPECIFIC);
                if (manufacturerSpecific != null) {
                    // If this node implements the Manufacturer Specific command
                    // class, we use it to get manufacturer info.
                    logger.debug("NODE {}: Node advancer: MANUFACTURER - send ManufacturerSpecific", node.getNodeId());
                    addToQueue(manufacturerSpecific.getManufacturerSpecificMessage());
                }
                break;
            case VERSION:
                // Try and get the version command class.
                ZWaveVersionCommandClass version = (ZWaveVersionCommandClass) node.getCommandClass(CommandClass.VERSION);
                // using the Version command class
                for (ZWaveCommandClass zwaveVersionClass : node.getCommandClasses()) {
                    logger.debug("NODE {}: Node advancer: VERSION - checking {}, version is {}", node.getNodeId(), zwaveVersionClass.getCommandClass().getLabel(), zwaveVersionClass.getVersion());
                    // See if we want to force the version of this command class
                    // We now should know all the command classes, so run through the database and set any options
                    database = new ZWaveProductDatabase();
                    if (database.FindProduct(node.getManufacturer(), node.getDeviceType(), node.getDeviceId(), node.getApplicationVersion()) == true) {
                        List<ZWaveDbCommandClass> classList = database.getProductCommandClasses();
                        if (classList != null) {
                            // Loop through the command classes in the data and update the records...
                            for (ZWaveDbCommandClass dbClass : classList) {
                                if (dbClass.version != null && zwaveVersionClass.getCommandClass().getKey() == dbClass.Id) {
                                    logger.debug("NODE {}: Node advancer: VERSION - Set {} to Version {}", node.getNodeId(), zwaveVersionClass.getCommandClass().getLabel(), dbClass.version);
                                    zwaveVersionClass.setVersion(dbClass.version);
                                }
                            }
                        }
                    }
                    if (version != null && zwaveVersionClass.getMaxVersion() > 1 && zwaveVersionClass.getVersion() == 0) {
                        logger.debug("NODE {}: Node advancer: VERSION - queued   {}", node.getNodeId(), zwaveVersionClass.getCommandClass().getLabel());
                        addToQueue(version.checkVersion(zwaveVersionClass));
                    } else if (zwaveVersionClass.getVersion() == 0) {
                        logger.debug("NODE {}: Node advancer: VERSION - VERSION default to 1", node.getNodeId());
                        zwaveVersionClass.setVersion(1);
                    }
                }
                logger.debug("NODE {}: Node advancer: VERSION - queued {} frames", node.getNodeId(), msgQueue.size());
                break;
            case APP_VERSION:
                ZWaveVersionCommandClass versionCommandClass = (ZWaveVersionCommandClass) node.getCommandClass(CommandClass.VERSION);
                if (versionCommandClass == null) {
                    logger.debug("NODE {}: Node advancer: APP_VERSION - VERSION node supported", node.getNodeId());
                    break;
                }
                // If we know the library type, then we've got the app version
                if (versionCommandClass.getLibraryType() != LibraryType.LIB_UNKNOWN) {
                    break;
                }
                // Request the version report for this node
                logger.debug("NODE {}: Node advancer: APP_VERSION - send VersionMessage", node.getNodeId());
                addToQueue(versionCommandClass.getVersionMessage());
                break;
            case ENDPOINTS:
                // Try and get the multi instance / channel command class.
                ZWaveMultiInstanceCommandClass multiInstance = (ZWaveMultiInstanceCommandClass) node.getCommandClass(CommandClass.MULTI_INSTANCE);
                if (multiInstance != null) {
                    logger.debug("NODE {}: Node advancer: ENDPOINTS - MultiInstance is supported", node.getNodeId());
                    addToQueue(multiInstance.initEndpoints(stageAdvanced));
                    logger.debug("NODE {}: Node advancer: ENDPOINTS - queued {} frames", node.getNodeId(), msgQueue.size());
                } else {
                    logger.debug("NODE {}: Node advancer: ENDPOINTS - MultiInstance not supported.", node.getNodeId());
                    // Set all classes to 1 instance.
                    for (ZWaveCommandClass commandClass : node.getCommandClasses()) {
                        commandClass.setInstances(1);
                    }
                }
                break;
            case UPDATE_DATABASE:
                // This stage reads information from the database to allow us to modify the configuration
                logger.debug("NODE {}: Node advancer: UPDATE_DATABASE", node.getNodeId());
                // We now should know all the command classes, so run through the database and set any options
                database = new ZWaveProductDatabase();
                if (database.FindProduct(node.getManufacturer(), node.getDeviceType(), node.getDeviceId(), node.getApplicationVersion()) == true) {
                    List<ZWaveDbCommandClass> classList = database.getProductCommandClasses();
                    if (classList != null) {
                        // Loop through the command classes and update the records...
                        for (ZWaveDbCommandClass dbClass : classList) {
                            // If we want to remove the class, then remove it!
                            if (dbClass.remove != null && dbClass.remove == true) {
                                // TODO: This will only remove the root nodes and ignores endpoint
                                // TODO: Do we need to search into multi_instance?
                                node.removeCommandClass(CommandClass.getCommandClass(dbClass.Id));
                                logger.debug("NODE {}: Node advancer: UPDATE_DATABASE - removing {}", node.getNodeId(), CommandClass.getCommandClass(dbClass.Id).getLabel());
                                continue;
                            }
                            // Get the command class
                            int endpoint = dbClass.endpoint == null ? 0 : dbClass.endpoint;
                            ZWaveCommandClass zwaveClass = node.resolveCommandClass(CommandClass.getCommandClass(dbClass.Id), endpoint);
                            // If we found the command class, then set its options
                            if (zwaveClass != null) {
                                zwaveClass.setOptions(dbClass);
                                continue;
                            }
                            // TODO: Does this need to account for multiple endpoints!?!
                            if (dbClass.add != null && dbClass.add == true) {
                                ZWaveCommandClass commandClass = ZWaveCommandClass.getInstance(dbClass.Id, node, controller);
                                if (commandClass != null) {
                                    logger.debug("NODE {}: Node advancer: UPDATE_DATABASE - adding {}", node.getNodeId(), CommandClass.getCommandClass(dbClass.Id).getLabel());
                                    node.addCommandClass(commandClass);
                                }
                            }
                        }
                    }
                }
                break;
            case STATIC_VALUES:
                // Loop through all classes looking for static initialisation
                for (ZWaveCommandClass zwaveStaticClass : node.getCommandClasses()) {
                    logger.debug("NODE {}: Node advancer: STATIC_VALUES - checking {}", node.getNodeId(), zwaveStaticClass.getCommandClass().getLabel());
                    if (zwaveStaticClass instanceof ZWaveCommandClassInitialization) {
                        logger.debug("NODE {}: Node advancer: STATIC_VALUES - found    {}", node.getNodeId(), zwaveStaticClass.getCommandClass().getLabel());
                        ZWaveCommandClassInitialization zcci = (ZWaveCommandClassInitialization) zwaveStaticClass;
                        int instances = zwaveStaticClass.getInstances();
                        logger.debug("NODE {}: Found {} instances of {}", node.getNodeId(), instances, zwaveStaticClass.getCommandClass());
                        if (instances == 1) {
                            addToQueue(zcci.initialize(stageAdvanced));
                        } else {
                            for (int i = 1; i <= instances; i++) {
                                addToQueue(zcci.initialize(stageAdvanced), zwaveStaticClass, i);
                            }
                        }
                    } else if (zwaveStaticClass instanceof ZWaveMultiInstanceCommandClass) {
                        ZWaveMultiInstanceCommandClass multiInstanceCommandClass = (ZWaveMultiInstanceCommandClass) zwaveStaticClass;
                        for (ZWaveEndpoint endpoint : multiInstanceCommandClass.getEndpoints()) {
                            for (ZWaveCommandClass endpointCommandClass : endpoint.getCommandClasses()) {
                                logger.debug("NODE {}: Node advancer: STATIC_VALUES - checking {} for endpoint {}", node.getNodeId(), endpointCommandClass.getCommandClass().getLabel(), endpoint.getEndpointId());
                                if (endpointCommandClass instanceof ZWaveCommandClassInitialization) {
                                    logger.debug("NODE {}: Node advancer: STATIC_VALUES - found    {}", node.getNodeId(), endpointCommandClass.getCommandClass().getLabel());
                                    ZWaveCommandClassInitialization zcci2 = (ZWaveCommandClassInitialization) endpointCommandClass;
                                    addToQueue(zcci2.initialize(stageAdvanced), endpointCommandClass, endpoint.getEndpointId());
                                }
                            }
                        }
                    }
                }
                logger.debug("NODE {}: Node advancer: STATIC_VALUES - queued {} frames", node.getNodeId(), msgQueue.size());
                break;
            case ASSOCIATIONS:
                // Do we support associations
                ZWaveAssociationCommandClass associationCommandClass = (ZWaveAssociationCommandClass) node.getCommandClass(CommandClass.ASSOCIATION);
                if (associationCommandClass == null) {
                    break;
                }
                // so just do this once
                if (stageAdvanced == false) {
                    break;
                }
                // Open the product database
                ZWaveProductDatabase associations = new ZWaveProductDatabase();
                if (associations.FindProduct(node.getManufacturer(), node.getDeviceType(), node.getDeviceId(), node.getApplicationVersion()) == true) {
                    // We have this device in the database
                    // Assume the database is correct since some devices report invalid number of groups!
                    List<ZWaveDbAssociationGroup> groupList = associations.getProductAssociationGroups();
                    // No groups known
                    if (groupList == null) {
                        logger.debug("NODE {}: Node advancer: ASSOCIATIONS - none in database", node.getNodeId());
                        break;
                    }
                    // Request every group
                    for (ZWaveDbAssociationGroup group : groupList) {
                        logger.debug("NODE {}: Node advancer: ASSOCIATIONS request group {}", node.getNodeId(), group.Index);
                        addToQueue(associationCommandClass.getAssociationMessage(group.Index));
                    }
                } else {
                    for (int group = 1; group <= associationCommandClass.getMaxGroups(); group++) {
                        logger.debug("NODE {}: Node advancer: ASSOCIATIONS request group {}", node.getNodeId(), group);
                        addToQueue(associationCommandClass.getAssociationMessage(group));
                    }
                }
                break;
            case SET_WAKEUP:
                // It sets the node to point to us, and the time is left along
                if (controller.isMasterController() == false) {
                    break;
                }
                ZWaveWakeUpCommandClass wakeupCommandClass = (ZWaveWakeUpCommandClass) node.getCommandClass(CommandClass.WAKE_UP);
                if (wakeupCommandClass == null) {
                    logger.debug("NODE {}: Node advancer: SET_WAKEUP - Wakeup command class not supported", node.getNodeId());
                    break;
                }
                if (wakeupCommandClass.getTargetNodeId() == controller.getOwnNodeId()) {
                    logger.debug("NODE {}: Node advancer: SET_WAKEUP - TargetNode is set to controller", node.getNodeId());
                    break;
                }
                int value = 3600;
                if (wakeupCommandClass.getInterval() == 0) {
                    logger.debug("NODE {}: Node advancer: SET_WAKEUP - Interval is currently 0. Set to 3600", node.getNodeId());
                } else {
                    value = wakeupCommandClass.getInterval();
                }
                logger.debug("NODE {}: Node advancer: SET_WAKEUP - Set wakeup node to controller ({}), period {}", node.getNodeId(), controller.getOwnNodeId(), value);
                // Set the wake-up interval, and request an update
                addToQueue(wakeupCommandClass.setInterval(value));
                addToQueue(wakeupCommandClass.getIntervalMessage());
                break;
            case SET_ASSOCIATION:
                if (controller.isMasterController() == false) {
                    break;
                }
                database = new ZWaveProductDatabase();
                if (database.FindProduct(node.getManufacturer(), node.getDeviceType(), node.getDeviceId(), node.getApplicationVersion()) == false) {
                    // No database entry for this device!
                    logger.warn("NODE {}: Node advancer: SET_ASSOCIATION - Unknown device: {}:{}:{}", node.getNodeId(), Integer.toHexString(node.getManufacturer()), Integer.toHexString(node.getDeviceType()), Integer.toHexString(node.getDeviceId()));
                    break;
                }
                List<ZWaveDbAssociationGroup> groups = database.getProductAssociationGroups();
                if (groups == null || groups.size() == 0) {
                    logger.debug("NODE {}: Node advancer: SET_ASSOCIATION - No association groups", node.getNodeId());
                    break;
                }
                // Get the group members
                ZWaveAssociationCommandClass associationCls = (ZWaveAssociationCommandClass) node.getCommandClass(CommandClass.ASSOCIATION);
                if (associationCls == null) {
                    logger.debug("NODE {}: Node advancer: SET_ASSOCIATION - ASSOCIATION class not supported", node.getNodeId());
                    break;
                }
                // Loop through all the groups in the database
                for (ZWaveDbAssociationGroup group : groups) {
                    if (group.SetToController == true) {
                        // Check if we're already a member
                        if (associationCls.getGroupMembers(group.Index).contains(controller.getOwnNodeId())) {
                            logger.debug("NODE {}: Node advancer: SET_ASSOCIATION - ASSOCIATION set for group {}", node.getNodeId(), group.Index);
                        } else {
                            logger.debug("NODE {}: Node advancer: SET_ASSOCIATION - Adding ASSOCIATION to group {}", node.getNodeId(), group.Index);
                            // Set the association, and request the update so we confirm if it's set
                            addToQueue(associationCls.setAssociationMessage(group.Index, controller.getOwnNodeId()));
                            addToQueue(associationCls.getAssociationMessage(group.Index));
                        }
                    }
                }
                break;
            case GET_CONFIGURATION:
                database = new ZWaveProductDatabase();
                if (database.FindProduct(node.getManufacturer(), node.getDeviceType(), node.getDeviceId(), node.getApplicationVersion()) == false) {
                    // No database entry for this device!
                    logger.warn("NODE {}: Node advancer: GET_CONFIGURATION - Unknown device: {}:{}:{}", node.getNodeId(), Integer.toHexString(node.getManufacturer()), Integer.toHexString(node.getDeviceType()), Integer.toHexString(node.getDeviceId()));
                    break;
                }
                ZWaveConfigurationCommandClass configurationCommandClass = (ZWaveConfigurationCommandClass) node.getCommandClass(CommandClass.CONFIGURATION);
                // If there are no configuration entries for this node, then continue.
                List<ZWaveDbConfigurationParameter> configList = database.getProductConfigParameters();
                if (configList == null || configList.size() == 0) {
                    break;
                }
                // If the node doesn't support configuration class, then we better let people know!
                if (configurationCommandClass == null) {
                    logger.error("NODE {}: Node advancer: GET_CONFIGURATION - CONFIGURATION class not supported", node.getNodeId());
                    break;
                }
                // Request all parameters for this node
                for (ZWaveDbConfigurationParameter parameter : configList) {
                    // Some parameters don't return anything, so don't request them!
                    if (parameter.WriteOnly != null && parameter.WriteOnly == true) {
                        configurationCommandClass.setParameterWriteOnly(parameter.Index, parameter.Size, true);
                        continue;
                    }
                    // then request it!
                    if (configurationCommandClass.getParameter(parameter.Index) == null) {
                        addToQueue(configurationCommandClass.getConfigMessage(parameter.Index));
                    }
                }
                break;
            case DYNAMIC_VALUES:
                for (ZWaveCommandClass zwaveDynamicClass : node.getCommandClasses()) {
                    logger.debug("NODE {}: Node advancer: DYNAMIC_VALUES - checking {}", node.getNodeId(), zwaveDynamicClass.getCommandClass().getLabel());
                    if (zwaveDynamicClass instanceof ZWaveCommandClassDynamicState) {
                        logger.debug("NODE {}: Node advancer: DYNAMIC_VALUES - found    {}", node.getNodeId(), zwaveDynamicClass.getCommandClass().getLabel());
                        ZWaveCommandClassDynamicState zdds = (ZWaveCommandClassDynamicState) zwaveDynamicClass;
                        int instances = zwaveDynamicClass.getInstances();
                        logger.debug("NODE {}: Found {} instances of {}", node.getNodeId(), instances, zwaveDynamicClass.getCommandClass());
                        if (instances == 1) {
                            addToQueue(zdds.getDynamicValues(stageAdvanced));
                        } else {
                            for (int i = 1; i <= instances; i++) {
                                addToQueue(zdds.getDynamicValues(stageAdvanced), zwaveDynamicClass, i);
                            }
                        }
                    } else if (zwaveDynamicClass instanceof ZWaveMultiInstanceCommandClass) {
                        ZWaveMultiInstanceCommandClass multiInstanceCommandClass = (ZWaveMultiInstanceCommandClass) zwaveDynamicClass;
                        for (ZWaveEndpoint endpoint : multiInstanceCommandClass.getEndpoints()) {
                            for (ZWaveCommandClass endpointCommandClass : endpoint.getCommandClasses()) {
                                logger.debug("NODE {}: Node advancer: DYNAMIC_VALUES - checking {} for endpoint {}", node.getNodeId(), endpointCommandClass.getCommandClass().getLabel(), endpoint.getEndpointId());
                                if (endpointCommandClass instanceof ZWaveCommandClassDynamicState) {
                                    logger.debug("NODE {}: Node advancer: DYNAMIC_VALUES - found    {}", node.getNodeId(), endpointCommandClass.getCommandClass().getLabel());
                                    ZWaveCommandClassDynamicState zdds2 = (ZWaveCommandClassDynamicState) endpointCommandClass;
                                    addToQueue(zdds2.getDynamicValues(stageAdvanced), endpointCommandClass, endpoint.getEndpointId());
                                }
                            }
                        }
                    }
                }
                logger.debug("NODE {}: Node advancer: DYNAMIC_VALUES - queued {} frames", node.getNodeId(), msgQueue.size());
                break;
            case STATIC_END:
            case DONE:
                // Save the node information to file
                nodeSerializer.SerializeNode(node);
                if (currentStage != ZWaveNodeInitStage.DONE) {
                    break;
                }
                logger.debug("NODE {}: Node advancer: Initialisation complete!", node.getNodeId());
                // Stop the retry timer
                resetIdleTimer();
                // We remove the event listener to reduce loading now that we're done
                controller.removeEventListener(this);
                // Notify everyone!
                ZWaveEvent zEvent = new ZWaveInitializationCompletedEvent(node.getNodeId());
                controller.notifyEventListeners(zEvent);
                // increment the stage!
                return;
            case SESSION_START:
                // where to start initialisation if we restored from XML.
                break;
            default:
                logger.debug("NODE {}: Node advancer: Unknown node state {} encountered.", node.getNodeId(), currentStage.toString().toString());
                break;
        }
        // that we're starting again, then loop around again.
        if (currentStage != ZWaveNodeInitStage.DONE && sendMessage() == false) {
            // Move on to the next stage
            setCurrentStage(currentStage.getNextStage());
            stageAdvanced = true;
            // Reset the backoff timer
            retryTimer = BACKOFF_TIMER_START;
            logger.debug("NODE {}: Node advancer - advancing to {}", node.getNodeId(), currentStage.toString());
        }
    } while (msgQueue.isEmpty());
}
Also used : ZWaveVersionCommandClass(org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveVersionCommandClass) ZWaveEvent(org.openhab.binding.zwave.internal.protocol.event.ZWaveEvent) ZWaveInitializationCompletedEvent(org.openhab.binding.zwave.internal.protocol.event.ZWaveInitializationCompletedEvent) ZWaveCommandClassDynamicState(org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClassDynamicState) SerialMessage(org.openhab.binding.zwave.internal.protocol.SerialMessage) ZWaveNoOperationCommandClass(org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveNoOperationCommandClass) ZWaveWakeUpCommandClass(org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveWakeUpCommandClass) ZWaveAssociationCommandClass(org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveAssociationCommandClass) ZWaveDbCommandClass(org.openhab.binding.zwave.internal.config.ZWaveDbCommandClass) ZWaveConfigurationCommandClass(org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveConfigurationCommandClass) ZWaveManufacturerSpecificCommandClass(org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveManufacturerSpecificCommandClass) ZWaveSecurityCommandClassWithInitialization(org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveSecurityCommandClassWithInitialization) ZWaveMultiInstanceCommandClass(org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveMultiInstanceCommandClass) ZWaveEndpoint(org.openhab.binding.zwave.internal.protocol.ZWaveEndpoint) ZWaveCommandClassInitialization(org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClassInitialization) ZWaveProductDatabase(org.openhab.binding.zwave.internal.config.ZWaveProductDatabase) ZWaveCommandClass(org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClass) IsFailedNodeMessageClass(org.openhab.binding.zwave.internal.protocol.serialmessage.IsFailedNodeMessageClass) IdentifyNodeMessageClass(org.openhab.binding.zwave.internal.protocol.serialmessage.IdentifyNodeMessageClass) RequestNodeInfoMessageClass(org.openhab.binding.zwave.internal.protocol.serialmessage.RequestNodeInfoMessageClass) ZWaveDbConfigurationParameter(org.openhab.binding.zwave.internal.config.ZWaveDbConfigurationParameter) ZWaveEndpoint(org.openhab.binding.zwave.internal.protocol.ZWaveEndpoint) ZWaveDbAssociationGroup(org.openhab.binding.zwave.internal.config.ZWaveDbAssociationGroup) GetRoutingInfoMessageClass(org.openhab.binding.zwave.internal.protocol.serialmessage.GetRoutingInfoMessageClass)

Example 53 with SerialMessage

use of org.openhab.binding.zwave.internal.protocol.SerialMessage in project openhab1-addons by openhab.

the class ZWaveNodeStageAdvancer method sendMessage.

/**
     * Sends a message if there is one queued
     *
     * @return true if a message was sent. false otherwise.
     */
private boolean sendMessage() {
    if (msgQueue.isEmpty() == true) {
        return false;
    }
    // Check to see if we need to send a frame
    if (freeToSend == true) {
        SerialMessage msg = msgQueue.peek();
        if (msg != null) {
            freeToSend = false;
            if (msg.getMessageClass() == SerialMessageClass.SendData) {
                controller.sendData(msg);
            } else {
                controller.enqueue(msg);
            }
            logger.debug("NODE {}: Node advancer - queued packet. Queue length is {}", node.getNodeId(), msgQueue.size());
        }
    }
    return true;
}
Also used : SerialMessage(org.openhab.binding.zwave.internal.protocol.SerialMessage)

Example 54 with SerialMessage

use of org.openhab.binding.zwave.internal.protocol.SerialMessage in project openhab1-addons by openhab.

the class SetSucNodeMessageClass method doRequest.

public SerialMessage doRequest(int nodeId, SUCType type) {
    logger.debug("NODE {}: SetSucNodeID node as {}", nodeId, type.toString());
    // Queue the request
    SerialMessage newMessage = new SerialMessage(SerialMessageClass.SetSucNodeID, SerialMessageType.Request, SerialMessageClass.SetSucNodeID, SerialMessagePriority.High);
    byte[] newPayload = new byte[5];
    newPayload[0] = (byte) nodeId;
    switch(type) {
        case NONE:
            newPayload[1] = 0;
            newPayload[3] = 0;
            break;
        case BASIC:
            newPayload[1] = 1;
            newPayload[3] = 0;
            break;
        case SERVER:
            newPayload[1] = 1;
            newPayload[3] = 1;
            break;
    }
    // Low power option = false
    newPayload[2] = 0;
    // Callback!!!
    newPayload[4] = 1;
    newMessage.setMessagePayload(newPayload);
    return newMessage;
}
Also used : SerialMessage(org.openhab.binding.zwave.internal.protocol.SerialMessage)

Example 55 with SerialMessage

use of org.openhab.binding.zwave.internal.protocol.SerialMessage in project openhab1-addons by openhab.

the class ZWaveCommandProcessor method checkTransactionComplete.

/**
     * Perform a check to see if this is the expected reply
     * and we can complete the transaction
     *
     * @param lastSentMessage The original message we sent to the controller
     * @param incomingMessage The response from the controller
     */
protected void checkTransactionComplete(SerialMessage lastSentMessage, SerialMessage latestIncomingMessage) {
    // Put the message in our table so it will be processed now or later
    incomingMessageTable.put(System.currentTimeMillis(), latestIncomingMessage);
    // transaction before completing.
    if (lastSentMessage.isAckPending()) {
        logger.trace("Checking transaction complete: Message has Ack Pending: {}", lastSentMessage);
        // consists of (up to) 4 parts"
        return;
    }
    logger.debug("Sent message {}", lastSentMessage.toString());
    logger.debug("Recv message {}", latestIncomingMessage.toString());
    logger.debug("Checking transaction complete: Sent message {}", lastSentMessage.toString());
    final Iterator<Map.Entry<Long, SerialMessage>> iter = incomingMessageTable.entrySet().iterator();
    // Discard responses from 10 seconds ago or longer
    final long expired = System.currentTimeMillis() - 10000;
    while (iter.hasNext()) {
        final Map.Entry<Long, SerialMessage> entry = iter.next();
        // Check if it's expired and remove it if it is
        if (entry.getKey() < expired) {
            iter.remove();
            continue;
        }
        final SerialMessage anIncomingMessage = entry.getValue();
        logger.debug("Checking transaction complete: Recv message {}", anIncomingMessage.toString());
        if (anIncomingMessage.getMessageClass() == lastSentMessage.getExpectedReply() && !anIncomingMessage.isTransactionCanceled()) {
            logger.debug("Checking transaction complete: class={}, callback id={}, expected={}, cancelled={}        transaction complete!", anIncomingMessage.getMessageClass(), lastSentMessage.getCallbackId(), lastSentMessage.getExpectedReply(), anIncomingMessage.isTransactionCanceled());
            transactionComplete = true;
            // We've processed this reply
            iter.remove();
            return;
        } else {
            logger.debug("Checking transaction complete: class={}, callback id={}, expected={}, cancelled={}      mismatch", anIncomingMessage.getMessageClass(), lastSentMessage.getCallbackId(), lastSentMessage.getExpectedReply(), anIncomingMessage.isTransactionCanceled());
        }
    }
}
Also used : SerialMessage(org.openhab.binding.zwave.internal.protocol.SerialMessage) TreeMap(java.util.TreeMap) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

SerialMessage (org.openhab.binding.zwave.internal.protocol.SerialMessage)125 State (org.openhab.core.types.State)12 ZWaveEndpoint (org.openhab.binding.zwave.internal.protocol.ZWaveEndpoint)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 HashMap (java.util.HashMap)5 ZWaveNode (org.openhab.binding.zwave.internal.protocol.ZWaveNode)5 ZWaveWakeUpCommandClass (org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveWakeUpCommandClass)4 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 Map (java.util.Map)3 ConfigurationParameter (org.openhab.binding.zwave.internal.protocol.ConfigurationParameter)3 SecurityEncapsulatedSerialMessage (org.openhab.binding.zwave.internal.protocol.SecurityEncapsulatedSerialMessage)3 ZWaveCommandClass (org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClass)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 ZWaveDbConfigurationParameter (org.openhab.binding.zwave.internal.config.ZWaveDbConfigurationParameter)2 ZWaveProductDatabase (org.openhab.binding.zwave.internal.config.ZWaveProductDatabase)2 MultiLevelPercentCommandConverter (org.openhab.binding.zwave.internal.converter.command.MultiLevelPercentCommandConverter)2 ZWaveAssociationCommandClass (org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveAssociationCommandClass)2 ZWaveConfigurationCommandClass (org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveConfigurationCommandClass)2 ZWaveNetworkEvent (org.openhab.binding.zwave.internal.protocol.event.ZWaveNetworkEvent)2