org.fourthline.cling.model.state.StateVariableValue Java Examples

The following examples show how to use org.fourthline.cling.model.state.StateVariableValue. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OutgoingEventRequestMessage.java    From TVRemoteIME with GNU General Public License v2.0 6 votes vote down vote up
public OutgoingEventRequestMessage(GENASubscription subscription,
                                   URL callbackURL,
                                   UnsignedIntegerFourBytes sequence,
                                   Collection<StateVariableValue> values) {

    super(new UpnpRequest(UpnpRequest.Method.NOTIFY, callbackURL));

    getHeaders().add(UpnpHeader.Type.CONTENT_TYPE, new ContentTypeHeader());
    getHeaders().add(UpnpHeader.Type.NT, new NTEventHeader());
    getHeaders().add(UpnpHeader.Type.NTS, new NTSHeader(NotificationSubtype.PROPCHANGE));
    getHeaders().add(UpnpHeader.Type.SID, new SubscriptionIdHeader(subscription.getSubscriptionId()));

    // Important! Pass by value so that we can safely increment it afterwards and before this is send!
    getHeaders().add(UpnpHeader.Type.SEQ, new EventSequenceHeader(sequence.getValue()));

    this.stateVariableValues = values;
}
 
Example #2
Source File: DefaultServiceManager.java    From DroidDLNA with GNU General Public License v3.0 6 votes vote down vote up
protected Collection<StateVariableValue> getCurrentState(String[] variableNames) throws Exception {
    lock();
    try {
        Collection<StateVariableValue> values = new ArrayList<StateVariableValue>();
        for (String variableName : variableNames) {
            variableName = variableName.trim();

            StateVariable stateVariable = getService().getStateVariable(variableName);
            if (stateVariable == null || !stateVariable.getEventDetails().isSendEvents()) {
                log.fine("Ignoring unknown or non-evented state variable: " + variableName);
                continue;
            }

            StateVariableAccessor accessor = getService().getAccessor(stateVariable);
            if (accessor == null) {
                log.warning("Ignoring evented state variable without accessor: " + variableName);
                continue;
            }
            values.add(accessor.read(stateVariable, getImplementation()));
        }
        return values;
    } finally {
        unlock();
    }
}
 
Example #3
Source File: PullGENAEventProcessorImpl.java    From DroidDLNA with GNU General Public License v3.0 6 votes vote down vote up
protected void readProperty(XmlPullParser xpp, IncomingEventRequestMessage message, StateVariable[] stateVariables) throws Exception  {
	// We're inside the property tag
	int event ;
	do {
		event = xpp.next();
		if(event == XmlPullParser.START_TAG) {

			String stateVariableName = xpp.getName();
			for (StateVariable stateVariable : stateVariables) {
				if (stateVariable.getName().equals(stateVariableName)) {
					log.fine("Reading state variable value: " + stateVariableName);
					String value = xpp.nextText();
					message.getStateVariableValues().add(new StateVariableValue(stateVariable, value));
					break;
				}
			} 
		}
	} while(event != XmlPullParser.END_DOCUMENT && (event != XmlPullParser.END_TAG || !xpp.getName().equals("property")));
}
 
Example #4
Source File: OutgoingEventRequestMessage.java    From DroidDLNA with GNU General Public License v3.0 6 votes vote down vote up
public OutgoingEventRequestMessage(GENASubscription subscription,
                                   URL callbackURL,
                                   UnsignedIntegerFourBytes sequence,
                                   Collection<StateVariableValue> values) {

    super(new UpnpRequest(UpnpRequest.Method.NOTIFY, callbackURL));

    getHeaders().add(UpnpHeader.Type.CONTENT_TYPE, new ContentTypeHeader());
    getHeaders().add(UpnpHeader.Type.NT, new NTEventHeader());
    getHeaders().add(UpnpHeader.Type.NTS, new NTSHeader(NotificationSubtype.PROPCHANGE));
    getHeaders().add(UpnpHeader.Type.SID, new SubscriptionIdHeader(subscription.getSubscriptionId()));

    // Important! Pass by value so that we can safely increment it afterwards and before this is send!
    getHeaders().add(UpnpHeader.Type.SEQ, new EventSequenceHeader(sequence.getValue()));

    this.stateVariableValues = values;
}
 
Example #5
Source File: LastChangeAwareServiceManager.java    From DroidDLNA with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected Collection<StateVariableValue> readInitialEventedStateVariableValues() throws Exception {

    // We don't use the service's internal LastChange but a fresh new one just for
    // this initial event. Modifying the internal one would trigger event notification's
    // to other subscribers!
    LastChange lc = new LastChange(getLastChangeParser());

    // Get the current "logical" instances of the service
    UnsignedIntegerFourBytes[] ids = getImplementation().getCurrentInstanceIds();
    if (ids.length > 0) {
        for (UnsignedIntegerFourBytes instanceId : ids) {
            // Iterate through all "logical" instances and ask them what their state is
            getImplementation().appendCurrentState(lc, instanceId);
        }
    } else {
        // Use the default "logical" instance with ID 0
        getImplementation().appendCurrentState(lc, new UnsignedIntegerFourBytes(0));
    }

    // Sum it all up and return it in the initial event to the GENA subscriber
    StateVariable variable = getService().getStateVariable("LastChange");
    Collection<StateVariableValue> values = new ArrayList();
    values.add(new StateVariableValue(variable, lc.toString()));
    return values;
}
 
Example #6
Source File: DefaultServiceManager.java    From TVRemoteIME with GNU General Public License v2.0 6 votes vote down vote up
protected Collection<StateVariableValue> getCurrentState(String[] variableNames) throws Exception {
    lock();
    try {
        Collection<StateVariableValue> values = new ArrayList<StateVariableValue>();
        for (String variableName : variableNames) {
            variableName = variableName.trim();

            StateVariable stateVariable = getService().getStateVariable(variableName);
            if (stateVariable == null || !stateVariable.getEventDetails().isSendEvents()) {
                log.fine("Ignoring unknown or non-evented state variable: " + variableName);
                continue;
            }

            StateVariableAccessor accessor = getService().getAccessor(stateVariable);
            if (accessor == null) {
                log.warning("Ignoring evented state variable without accessor: " + variableName);
                continue;
            }
            values.add(accessor.read(stateVariable, getImplementation()));
        }
        return values;
    } finally {
        unlock();
    }
}
 
Example #7
Source File: PullGENAEventProcessorImpl.java    From TVRemoteIME with GNU General Public License v2.0 6 votes vote down vote up
protected void readProperty(XmlPullParser xpp, IncomingEventRequestMessage message, StateVariable[] stateVariables) throws Exception  {
	// We're inside the property tag
	int event ;
	do {
		event = xpp.next();
		if(event == XmlPullParser.START_TAG) {

			String stateVariableName = xpp.getName();
			for (StateVariable stateVariable : stateVariables) {
				if (stateVariable.getName().equals(stateVariableName)) {
					log.fine("Reading state variable value: " + stateVariableName);
					String value = xpp.nextText();
					message.getStateVariableValues().add(new StateVariableValue(stateVariable, value));
					break;
				}
			} 
		}
	} while(event != XmlPullParser.END_DOCUMENT && (event != XmlPullParser.END_TAG || !xpp.getName().equals("property")));
}
 
Example #8
Source File: LastChangeAwareServiceManager.java    From TVRemoteIME with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected Collection<StateVariableValue> readInitialEventedStateVariableValues() throws Exception {

    // We don't use the service's internal LastChange but a fresh new one just for
    // this initial event. Modifying the internal one would trigger event notification's
    // to other subscribers!
    LastChange lc = new LastChange(getLastChangeParser());

    // Get the current "logical" instances of the service
    UnsignedIntegerFourBytes[] ids = getImplementation().getCurrentInstanceIds();
    if (ids.length > 0) {
        for (UnsignedIntegerFourBytes instanceId : ids) {
            // Iterate through all "logical" instances and ask them what their state is
            getImplementation().appendCurrentState(lc, instanceId);
        }
    } else {
        // Use the default "logical" instance with ID 0
        getImplementation().appendCurrentState(lc, new UnsignedIntegerFourBytes(0));
    }

    // Sum it all up and return it in the initial event to the GENA subscriber
    StateVariable variable = getService().getStateVariable("LastChange");
    Collection<StateVariableValue> values = new ArrayList();
    values.add(new StateVariableValue(variable, lc.toString()));
    return values;
}
 
Example #9
Source File: LocalGENASubscription.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
public LocalGENASubscription(LocalService service,
                             Integer requestedDurationSeconds, List<URL> callbackURLs) throws Exception {
    super(service);

    setSubscriptionDuration(requestedDurationSeconds);

    log.fine("Reading initial state of local service at subscription time");
    long currentTime = new Date().getTime();
    this.currentValues.clear();

    Collection<StateVariableValue> values = getService().getManager().getCurrentState();

    log.finer("Got evented state variable values: " + values.size());

    for (StateVariableValue value : values) {
        this.currentValues.put(value.getStateVariable().getName(), value);

        if (log.isLoggable(Level.FINEST)) {
            log.finer("Read state variable value '" + value.getStateVariable().getName() + "': " + value.toString());
        }

        // Preserve "last sent" state for future moderation
        lastSentTimestamp.put(value.getStateVariable().getName(), currentTime);
        if (value.getStateVariable().isModeratedNumericType()) {
            lastSentNumericValue.put(value.getStateVariable().getName(), Long.valueOf(value.toString()));
        }
    }

    this.subscriptionId = SubscriptionIdHeader.PREFIX + UUID.randomUUID();
    this.currentSequence = new UnsignedIntegerFourBytes(0);
    this.callbackURLs = callbackURLs;
}
 
Example #10
Source File: LocalGENASubscription.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Moderates {@link org.fourthline.cling.model.ServiceManager#EVENTED_STATE_VARIABLES} events and state variable
 * values, calls {@link #eventReceived()}.
 */
synchronized public void propertyChange(PropertyChangeEvent e) {
    if (!e.getPropertyName().equals(ServiceManager.EVENTED_STATE_VARIABLES)) return;

    log.fine("Eventing triggered, getting state for subscription: " + getSubscriptionId());

    long currentTime = new Date().getTime();

    Collection<StateVariableValue> newValues = (Collection) e.getNewValue();
    Set<String> excludedVariables = moderateStateVariables(currentTime, newValues);

    currentValues.clear();
    for (StateVariableValue newValue : newValues) {
        String name = newValue.getStateVariable().getName();
        if (!excludedVariables.contains(name)) {
            log.fine("Adding state variable value to current values of event: " + newValue.getStateVariable() + " = " + newValue);
            currentValues.put(newValue.getStateVariable().getName(), newValue);

            // Preserve "last sent" state for future moderation
            lastSentTimestamp.put(name, currentTime);
            if (newValue.getStateVariable().isModeratedNumericType()) {
                lastSentNumericValue.put(name, Long.valueOf(newValue.toString()));
            }
        }
    }

    if (currentValues.size() > 0) {
        log.fine("Propagating new state variable values to subscription: " + this);
        // TODO: I'm not happy with this design, this dispatches to a separate thread which _then_
        // is supposed to lock and read the values off this instance. That obviously doesn't work
        // so it's currently a hack in SendingEvent.java
        eventReceived();
    } else {
        log.fine("No state variable values for event (all moderated out?), not triggering event");
    }
}
 
Example #11
Source File: RemoteGENASubscription.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
synchronized public void receive(UnsignedIntegerFourBytes sequence, Collection<StateVariableValue> newValues) {

        if (this.currentSequence != null) {

            // TODO: Handle rollover to 1!
            if (this.currentSequence.getValue().equals(this.currentSequence.getBits().getMaxValue()) && sequence.getValue() == 1) {
                System.err.println("TODO: HANDLE ROLLOVER");
                return;
            }

            if (this.currentSequence.getValue() >= sequence.getValue()) {
                return;
            }

            int difference;
            long expectedValue = currentSequence.getValue() + 1;
            if ((difference = (int) (sequence.getValue() - expectedValue)) != 0) {
                eventsMissed(difference);
            }

        }

        this.currentSequence = sequence;

        for (StateVariableValue newValue : newValues) {
            currentValues.put(newValue.getStateVariable().getName(), newValue);
        }

        eventReceived();
    }
 
Example #12
Source File: GENAEventProcessorImpl.java    From TVRemoteIME with GNU General Public License v2.0 5 votes vote down vote up
protected void readProperties(Element propertysetElement, IncomingEventRequestMessage message) {
    NodeList propertysetElementChildren = propertysetElement.getChildNodes();

    StateVariable[] stateVariables = message.getService().getStateVariables();

    for (int i = 0; i < propertysetElementChildren.getLength(); i++) {
        Node propertysetChild = propertysetElementChildren.item(i);

        if (propertysetChild.getNodeType() != Node.ELEMENT_NODE)
            continue;

        if (getUnprefixedNodeName(propertysetChild).equals("property")) {

            NodeList propertyChildren = propertysetChild.getChildNodes();

            for (int j = 0; j < propertyChildren.getLength(); j++) {
                Node propertyChild = propertyChildren.item(j);

                if (propertyChild.getNodeType() != Node.ELEMENT_NODE)
                    continue;

                String stateVariableName = getUnprefixedNodeName(propertyChild);
                for (StateVariable stateVariable : stateVariables) {
                    if (stateVariable.getName().equals(stateVariableName)) {
                        log.fine("Reading state variable value: " + stateVariableName);
                        String value = XMLUtil.getTextContent(propertyChild);
                        message.getStateVariableValues().add(
                                new StateVariableValue(stateVariable, value)
                        );
                        break;
                    }
                }

            }
        }
    }
}
 
Example #13
Source File: GENAEventProcessorImpl.java    From TVRemoteIME with GNU General Public License v2.0 5 votes vote down vote up
protected void writeProperties(Document d, Element propertysetElement, OutgoingEventRequestMessage message) {
    for (StateVariableValue stateVariableValue : message.getStateVariableValues()) {
        Element propertyElement = d.createElementNS(Constants.NS_UPNP_EVENT_10, "e:property");
        propertysetElement.appendChild(propertyElement);
        XMLUtil.appendNewElement(
                d,
                propertyElement,
                stateVariableValue.getStateVariable().getName(),
                stateVariableValue.toString()
        );
    }
}
 
Example #14
Source File: DefaultServiceManager.java    From TVRemoteIME with GNU General Public License v2.0 5 votes vote down vote up
public void propertyChange(PropertyChangeEvent e) {
    log.finer("Property change event on local service: " + e.getPropertyName());

    // Prevent recursion
    if (e.getPropertyName().equals(EVENTED_STATE_VARIABLES)) return;

    String[] variableNames = ModelUtil.fromCommaSeparatedList(e.getPropertyName());
    log.fine("Changed variable names: " + Arrays.toString(variableNames));

    try {
        Collection<StateVariableValue> currentValues = getCurrentState(variableNames);

        if (!currentValues.isEmpty()) {
            getPropertyChangeSupport().firePropertyChange(
                EVENTED_STATE_VARIABLES,
                null,
                currentValues
            );
        }

    } catch (Exception ex) {
        // TODO: Is it OK to only log this error? It means we keep running although we couldn't send events?
        log.log(
            Level.SEVERE,
            "Error reading state of service after state variable update event: " + Exceptions.unwrap(ex),
            ex
        );
    }
}
 
Example #15
Source File: DefaultServiceManager.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
public void propertyChange(PropertyChangeEvent e) {
    log.finer("Property change event on local service: " + e.getPropertyName());

    // Prevent recursion
    if (e.getPropertyName().equals(EVENTED_STATE_VARIABLES)) return;

    String[] variableNames = ModelUtil.fromCommaSeparatedList(e.getPropertyName());
    log.fine("Changed variable names: " + Arrays.toString(variableNames));

    try {
        Collection<StateVariableValue> currentValues = getCurrentState(variableNames);

        if (!currentValues.isEmpty()) {
            getPropertyChangeSupport().firePropertyChange(
                EVENTED_STATE_VARIABLES,
                null,
                currentValues
            );
        }

    } catch (Exception ex) {
        // TODO: Is it OK to only log this error? It means we keep running although we couldn't send events?
        log.log(
            Level.SEVERE,
            "Error reading state of service after state variable update event: " + Exceptions.unwrap(ex),
            ex
        );
    }
}
 
Example #16
Source File: LocalGENASubscription.java    From TVRemoteIME with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Moderates {@link org.fourthline.cling.model.ServiceManager#EVENTED_STATE_VARIABLES} events and state variable
 * values, calls {@link #eventReceived()}.
 */
synchronized public void propertyChange(PropertyChangeEvent e) {
    if (!e.getPropertyName().equals(ServiceManager.EVENTED_STATE_VARIABLES)) return;

    log.fine("Eventing triggered, getting state for subscription: " + getSubscriptionId());

    long currentTime = new Date().getTime();

    Collection<StateVariableValue> newValues = (Collection) e.getNewValue();
    Set<String> excludedVariables = moderateStateVariables(currentTime, newValues);

    currentValues.clear();
    for (StateVariableValue newValue : newValues) {
        String name = newValue.getStateVariable().getName();
        if (!excludedVariables.contains(name)) {
            log.fine("Adding state variable value to current values of event: " + newValue.getStateVariable() + " = " + newValue);
            currentValues.put(newValue.getStateVariable().getName(), newValue);

            // Preserve "last sent" state for future moderation
            lastSentTimestamp.put(name, currentTime);
            if (newValue.getStateVariable().isModeratedNumericType()) {
                lastSentNumericValue.put(name, Long.valueOf(newValue.toString()));
            }
        }
    }

    if (currentValues.size() > 0) {
        log.fine("Propagating new state variable values to subscription: " + this);
        // TODO: I'm not happy with this design, this dispatches to a separate thread which _then_
        // is supposed to lock and read the values off this instance. That obviously doesn't work
        // so it's currently a hack in SendingEvent.java
        eventReceived();
    } else {
        log.fine("No state variable values for event (all moderated out?), not triggering event");
    }
}
 
Example #17
Source File: LocalGENASubscription.java    From TVRemoteIME with GNU General Public License v2.0 5 votes vote down vote up
public LocalGENASubscription(LocalService service,
                             Integer requestedDurationSeconds, List<URL> callbackURLs) throws Exception {
    super(service);

    setSubscriptionDuration(requestedDurationSeconds);

    log.fine("Reading initial state of local service at subscription time");
    long currentTime = new Date().getTime();
    this.currentValues.clear();

    Collection<StateVariableValue> values = getService().getManager().getCurrentState();

    log.finer("Got evented state variable values: " + values.size());

    for (StateVariableValue value : values) {
        this.currentValues.put(value.getStateVariable().getName(), value);

        if (log.isLoggable(Level.FINEST)) {
            log.finer("Read state variable value '" + value.getStateVariable().getName() + "': " + value.toString());
        }

        // Preserve "last sent" state for future moderation
        lastSentTimestamp.put(value.getStateVariable().getName(), currentTime);
        if (value.getStateVariable().isModeratedNumericType()) {
            lastSentNumericValue.put(value.getStateVariable().getName(), Long.valueOf(value.toString()));
        }
    }

    this.subscriptionId = SubscriptionIdHeader.PREFIX + UUID.randomUUID();
    this.currentSequence = new UnsignedIntegerFourBytes(0);
    this.callbackURLs = callbackURLs;
}
 
Example #18
Source File: RemoteGENASubscription.java    From TVRemoteIME with GNU General Public License v2.0 5 votes vote down vote up
synchronized public void receive(UnsignedIntegerFourBytes sequence, Collection<StateVariableValue> newValues) {

        if (this.currentSequence != null) {

            // TODO: Handle rollover to 1!
            if (this.currentSequence.getValue().equals(this.currentSequence.getBits().getMaxValue()) && sequence.getValue() == 1) {
                System.err.println("TODO: HANDLE ROLLOVER");
                return;
            }

            if (this.currentSequence.getValue() >= sequence.getValue()) {
                return;
            }

            int difference;
            long expectedValue = currentSequence.getValue() + 1;
            if ((difference = (int) (sequence.getValue() - expectedValue)) != 0) {
                eventsMissed(difference);
            }

        }

        this.currentSequence = sequence;

        for (StateVariableValue newValue : newValues) {
            currentValues.put(newValue.getStateVariable().getName(), newValue);
        }

        eventReceived();
    }
 
Example #19
Source File: GENAEventProcessorImpl.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
protected void writeProperties(Document d, Element propertysetElement, OutgoingEventRequestMessage message) {
    for (StateVariableValue stateVariableValue : message.getStateVariableValues()) {
        Element propertyElement = d.createElementNS(Constants.NS_UPNP_EVENT_10, "e:property");
        propertysetElement.appendChild(propertyElement);
        XMLUtil.appendNewElement(
                d,
                propertyElement,
                stateVariableValue.getStateVariable().getName(),
                stateVariableValue.toString()
        );
    }
}
 
Example #20
Source File: GENAEventProcessorImpl.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
protected void readProperties(Element propertysetElement, IncomingEventRequestMessage message) {
    NodeList propertysetElementChildren = propertysetElement.getChildNodes();

    StateVariable[] stateVariables = message.getService().getStateVariables();

    for (int i = 0; i < propertysetElementChildren.getLength(); i++) {
        Node propertysetChild = propertysetElementChildren.item(i);

        if (propertysetChild.getNodeType() != Node.ELEMENT_NODE)
            continue;

        if (getUnprefixedNodeName(propertysetChild).equals("property")) {

            NodeList propertyChildren = propertysetChild.getChildNodes();

            for (int j = 0; j < propertyChildren.getLength(); j++) {
                Node propertyChild = propertyChildren.item(j);

                if (propertyChild.getNodeType() != Node.ELEMENT_NODE)
                    continue;

                String stateVariableName = getUnprefixedNodeName(propertyChild);
                for (StateVariable stateVariable : stateVariables) {
                    if (stateVariable.getName().equals(stateVariableName)) {
                        log.fine("Reading state variable value: " + stateVariableName);
                        String value = XMLUtil.getTextContent(propertyChild);
                        message.getStateVariableValues().add(
                                new StateVariableValue(stateVariable, value)
                        );
                        break;
                    }
                }

            }
        }
    }
}
 
Example #21
Source File: DefaultServiceManager.java    From DroidDLNA with GNU General Public License v3.0 4 votes vote down vote up
protected Collection<StateVariableValue> readInitialEventedStateVariableValues() throws Exception {
    return null;
}
 
Example #22
Source File: LocalGENASubscription.java    From DroidDLNA with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Checks whether a state variable is moderated, and if this change is within the maximum rate and range limits.
 *
 * @param currentTime The current unix time.
 * @param values The state variable values to moderate.
 * @return A collection of state variable values that although they might have changed, are excluded from the event.
 */
synchronized protected Set<String> moderateStateVariables(long currentTime, Collection<StateVariableValue> values) {

    Set<String> excludedVariables = new HashSet();

    // Moderate event variables that have a maximum rate or minimum delta
    for (StateVariableValue stateVariableValue : values) {

        StateVariable stateVariable = stateVariableValue.getStateVariable();
        String stateVariableName = stateVariableValue.getStateVariable().getName();

        if (stateVariable.getEventDetails().getEventMaximumRateMilliseconds() == 0 &&
                stateVariable.getEventDetails().getEventMinimumDelta() == 0) {
            log.finer("Variable is not moderated: " + stateVariable);
            continue;
        }

        // That should actually never happen, because we always "send" it as the initial state/event
        if (!lastSentTimestamp.containsKey(stateVariableName)) {
            log.finer("Variable is moderated but was never sent before: " + stateVariable);
            continue;
        }

        if (stateVariable.getEventDetails().getEventMaximumRateMilliseconds() > 0) {
            long timestampLastSent = lastSentTimestamp.get(stateVariableName);
            long timestampNextSend = timestampLastSent + (stateVariable.getEventDetails().getEventMaximumRateMilliseconds());
            if (currentTime <= timestampNextSend) {
                log.finer("Excluding state variable with maximum rate: " + stateVariable);
                excludedVariables.add(stateVariableName);
                continue;
            }
        }

        if (stateVariable.isModeratedNumericType() && lastSentNumericValue.get(stateVariableName) != null) {

            long oldValue = Long.valueOf(lastSentNumericValue.get(stateVariableName));
            long newValue = Long.valueOf(stateVariableValue.toString());
            long minDelta = stateVariable.getEventDetails().getEventMinimumDelta();

            if (newValue > oldValue && newValue - oldValue < minDelta) {
                log.finer("Excluding state variable with minimum delta: " + stateVariable);
                excludedVariables.add(stateVariableName);
                continue;
            }

            if (newValue < oldValue && oldValue - newValue < minDelta) {
                log.finer("Excluding state variable with minimum delta: " + stateVariable);
                excludedVariables.add(stateVariableName);
            }
        }

    }
    return excludedVariables;
}
 
Example #23
Source File: DLNAController.java    From Popeens-DSub with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void create(final boolean playing, final int seconds) {
	downloadService.setPlayerState(PlayerState.PREPARING);

	callback = new SubscriptionCallback(getTransportService(), 600) {
		@Override
		protected void failed(GENASubscription genaSubscription, UpnpResponse upnpResponse, Exception e, String msg) {
			Log.w(TAG, "Register subscription callback failed: " + msg, e);
		}

		@Override
		protected void established(GENASubscription genaSubscription) {
			Action seekAction = genaSubscription.getService().getAction("Seek");
			if(seekAction != null) {
				StateVariable seekMode = genaSubscription.getService().getStateVariable("A_ARG_TYPE_SeekMode");
				for(String allowedValue: seekMode.getTypeDetails().getAllowedValues()) {
					if("REL_TIME".equals(allowedValue)) {
						supportsSeek = true;
					}
				}
			}
			Action setupNextAction = genaSubscription.getService().getAction("SetNextAVTransportURI");
			if(setupNextAction != null) {
				supportsSetupNext = true;
			}

			startSong(downloadService.getCurrentPlaying(), playing, seconds);
			downloadService.postDelayed(searchDLNA, SEARCH_UPDATE_INTERVAL_SECONDS);
		}

		@Override
		protected void ended(GENASubscription genaSubscription, CancelReason cancelReason, UpnpResponse upnpResponse) {
			Log.i(TAG, "Ended subscription");
			if(cancelReason != null) {
				Log.i(TAG, "Cancel Reason: " + cancelReason.toString());
			}
			if(upnpResponse != null) {
				Log.i(TAG, "Reponse Message: " + upnpResponse.getStatusMessage());
				Log.i(TAG, "Response Details: " + upnpResponse.getResponseDetails());
			}
		}

		@Override
		protected void eventReceived(GENASubscription genaSubscription) {
			Map<String, StateVariableValue> m = genaSubscription.getCurrentValues();
			try {
				String lastChangeText = m.get("LastChange").toString();
				lastChangeText = lastChangeText.replace(",X_DLNA_SeekTime","").replace(",X_DLNA_SeekByte", "");
				LastChange lastChange = new LastChange(new AVTransportLastChangeParser(), lastChangeText);

				if (lastChange.getEventedValue(0, AVTransportVariable.TransportState.class) == null) {
					return;
				}

				switch (lastChange.getEventedValue(0, AVTransportVariable.TransportState.class).getValue()) {
					case PLAYING:
						downloadService.setPlayerState(PlayerState.STARTED);
						break;
					case PAUSED_PLAYBACK:
						downloadService.setPlayerState(PlayerState.PAUSED);
						break;
					case STOPPED:
						boolean failed = false;
						for(StateVariableValue val: m.values()) {
							if(val.toString().indexOf("TransportStatus val=\"ERROR_OCCURRED\"") != -1) {
								Log.w(TAG, "Failed to load with event: " + val.toString());
								failed = true;
							}
						}

						if(failed) {
							failedLoad();
						} else if(downloadService.getPlayerState() == PlayerState.STARTED) {
							// Played until the end
							downloadService.onSongCompleted();
						} else {
							downloadService.setPlayerState(PlayerState.STOPPED);
						}
						break;
					case TRANSITIONING:
						downloadService.setPlayerState(PlayerState.PREPARING);
						break;
					case NO_MEDIA_PRESENT:
						downloadService.setPlayerState(PlayerState.IDLE);
						break;
					default:
				}
			}
			catch (Exception e) {
				Log.w(TAG, "Failed to parse UPNP event", e);
			}
		}

		@Override
		protected void eventsMissed(GENASubscription genaSubscription, int i) {
			Log.w(TAG, "Event missed: " + i);
		}
	};
	controlPoint.execute(callback);
}
 
Example #24
Source File: GENASubscription.java    From DroidDLNA with GNU General Public License v3.0 4 votes vote down vote up
synchronized public Map<String, StateVariableValue<S>> getCurrentValues() {
    return currentValues;
}
 
Example #25
Source File: IncomingEventRequestMessage.java    From DroidDLNA with GNU General Public License v3.0 4 votes vote down vote up
public List<StateVariableValue> getStateVariableValues() {
    return stateVariableValues;
}
 
Example #26
Source File: OutgoingEventRequestMessage.java    From DroidDLNA with GNU General Public License v3.0 4 votes vote down vote up
public Collection<StateVariableValue> getStateVariableValues() {
    return stateVariableValues;
}
 
Example #27
Source File: DefaultServiceManager.java    From TVRemoteIME with GNU General Public License v2.0 4 votes vote down vote up
protected Collection<StateVariableValue> readInitialEventedStateVariableValues() throws Exception {
    return null;
}
 
Example #28
Source File: LocalGENASubscription.java    From TVRemoteIME with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Checks whether a state variable is moderated, and if this change is within the maximum rate and range limits.
 *
 * @param currentTime The current unix time.
 * @param values The state variable values to moderate.
 * @return A collection of state variable values that although they might have changed, are excluded from the event.
 */
synchronized protected Set<String> moderateStateVariables(long currentTime, Collection<StateVariableValue> values) {

    Set<String> excludedVariables = new HashSet();

    // Moderate event variables that have a maximum rate or minimum delta
    for (StateVariableValue stateVariableValue : values) {

        StateVariable stateVariable = stateVariableValue.getStateVariable();
        String stateVariableName = stateVariableValue.getStateVariable().getName();

        if (stateVariable.getEventDetails().getEventMaximumRateMilliseconds() == 0 &&
                stateVariable.getEventDetails().getEventMinimumDelta() == 0) {
            log.finer("Variable is not moderated: " + stateVariable);
            continue;
        }

        // That should actually never happen, because we always "send" it as the initial state/event
        if (!lastSentTimestamp.containsKey(stateVariableName)) {
            log.finer("Variable is moderated but was never sent before: " + stateVariable);
            continue;
        }

        if (stateVariable.getEventDetails().getEventMaximumRateMilliseconds() > 0) {
            long timestampLastSent = lastSentTimestamp.get(stateVariableName);
            long timestampNextSend = timestampLastSent + (stateVariable.getEventDetails().getEventMaximumRateMilliseconds());
            if (currentTime <= timestampNextSend) {
                log.finer("Excluding state variable with maximum rate: " + stateVariable);
                excludedVariables.add(stateVariableName);
                continue;
            }
        }

        if (stateVariable.isModeratedNumericType() && lastSentNumericValue.get(stateVariableName) != null) {

            long oldValue = Long.valueOf(lastSentNumericValue.get(stateVariableName));
            long newValue = Long.valueOf(stateVariableValue.toString());
            long minDelta = stateVariable.getEventDetails().getEventMinimumDelta();

            if (newValue > oldValue && newValue - oldValue < minDelta) {
                log.finer("Excluding state variable with minimum delta: " + stateVariable);
                excludedVariables.add(stateVariableName);
                continue;
            }

            if (newValue < oldValue && oldValue - newValue < minDelta) {
                log.finer("Excluding state variable with minimum delta: " + stateVariable);
                excludedVariables.add(stateVariableName);
            }
        }

    }
    return excludedVariables;
}
 
Example #29
Source File: GENASubscription.java    From TVRemoteIME with GNU General Public License v2.0 4 votes vote down vote up
synchronized public Map<String, StateVariableValue<S>> getCurrentValues() {
    return currentValues;
}
 
Example #30
Source File: IncomingEventRequestMessage.java    From TVRemoteIME with GNU General Public License v2.0 4 votes vote down vote up
public List<StateVariableValue> getStateVariableValues() {
    return stateVariableValues;
}