org.fourthline.cling.model.meta.StateVariable Java Examples

The following examples show how to use org.fourthline.cling.model.meta.StateVariable. 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: AnnotationLocalServiceBinder.java    From TVRemoteIME with GNU General Public License v2.0 6 votes vote down vote up
protected Map<Action, ActionExecutor> readActions(Class<?> clazz,
                                                  Map<StateVariable, StateVariableAccessor> stateVariables,
                                                  Set<Class> stringConvertibleTypes)
        throws LocalServiceBindingException {

    Map<Action, ActionExecutor> map = new HashMap();

    for (Method method : Reflections.getMethods(clazz, UpnpAction.class)) {
        AnnotationActionBinder actionBinder =
                new AnnotationActionBinder(method, stateVariables, stringConvertibleTypes);
        Action action = actionBinder.appendAction(map);
        if(isActionExcluded(action)) {
        	map.remove(action);
        }
    }

    return map;
}
 
Example #2
Source File: MutableStateVariable.java    From DroidDLNA with GNU General Public License v3.0 6 votes vote down vote up
public StateVariable build() {
    return new StateVariable(
            name,
            new StateVariableTypeDetails(
                    dataType,
                    defaultValue,
                    allowedValues == null || allowedValues.size() == 0
                            ? null
                            : allowedValues.toArray(new String[allowedValues.size()]),
                    allowedValueRange == null
                            ? null :
                            new StateVariableAllowedValueRange(
                                    allowedValueRange.minimum,
                                    allowedValueRange.maximum,
                                    allowedValueRange.step
                            )
            ),
            eventDetails
    );
}
 
Example #3
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 #4
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 #5
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 #6
Source File: StateVariableAccessor.java    From TVRemoteIME with GNU General Public License v2.0 6 votes vote down vote up
public StateVariableValue read(final StateVariable<LocalService> stateVariable, final Object serviceImpl) throws Exception {

        class AccessCommand implements Command {
            Object result;
            public void execute(ServiceManager serviceManager) throws Exception {
                result = read(serviceImpl);
                if (stateVariable.getService().isStringConvertibleType(result)) {
                    result = result.toString();
                }
            }
        }

        AccessCommand cmd = new AccessCommand();
        stateVariable.getService().getManager().execute(cmd);
        return new StateVariableValue(stateVariable, cmd.result);
    }
 
Example #7
Source File: AnnotationLocalServiceBinder.java    From DroidDLNA with GNU General Public License v3.0 6 votes vote down vote up
public LocalService read(Class<?> clazz, ServiceId id, ServiceType type,
                               boolean supportsQueryStateVariables, Set<Class> stringConvertibleTypes)
        throws LocalServiceBindingException {

    Map<StateVariable, StateVariableAccessor> stateVariables = readStateVariables(clazz, stringConvertibleTypes);
    Map<Action, ActionExecutor> actions = readActions(clazz, stateVariables, stringConvertibleTypes);

    // Special treatment of the state variable querying action
    if (supportsQueryStateVariables) {
        actions.put(new QueryStateVariableAction(), new QueryStateVariableExecutor());
    }

    try {
        return new LocalService(type, id, actions, stateVariables, stringConvertibleTypes, supportsQueryStateVariables);

    } catch (ValidationException ex) {
        log.severe("Could not validate device model: " + ex.toString());
        for (ValidationError validationError : ex.getErrors()) {
            log.severe(validationError.toString());
        }
        throw new LocalServiceBindingException("Validation of model failed, check the log");
    }
}
 
Example #8
Source File: AnnotationLocalServiceBinder.java    From TVRemoteIME with GNU General Public License v2.0 6 votes vote down vote up
public LocalService read(Class<?> clazz, ServiceId id, ServiceType type,
                               boolean supportsQueryStateVariables, Set<Class> stringConvertibleTypes)
        throws LocalServiceBindingException {

    Map<StateVariable, StateVariableAccessor> stateVariables = readStateVariables(clazz, stringConvertibleTypes);
    Map<Action, ActionExecutor> actions = readActions(clazz, stateVariables, stringConvertibleTypes);

    // Special treatment of the state variable querying action
    if (supportsQueryStateVariables) {
        actions.put(new QueryStateVariableAction(), new QueryStateVariableExecutor());
    }

    try {
        return new LocalService(type, id, actions, stateVariables, stringConvertibleTypes, supportsQueryStateVariables);

    } catch (ValidationException ex) {
        log.severe("Could not validate device model: " + ex.toString());
        for (ValidationError validationError : ex.getErrors()) {
            log.severe(validationError.toString());
        }
        throw new LocalServiceBindingException("Validation of model failed, check the log");
    }
}
 
Example #9
Source File: AnnotationLocalServiceBinder.java    From DroidDLNA with GNU General Public License v3.0 6 votes vote down vote up
protected Map<Action, ActionExecutor> readActions(Class<?> clazz,
                                                  Map<StateVariable, StateVariableAccessor> stateVariables,
                                                  Set<Class> stringConvertibleTypes)
        throws LocalServiceBindingException {

    Map<Action, ActionExecutor> map = new HashMap();

    for (Method method : Reflections.getMethods(clazz, UpnpAction.class)) {
        AnnotationActionBinder actionBinder =
                new AnnotationActionBinder(method, stateVariables, stringConvertibleTypes);
        Action action = actionBinder.appendAction(map);
        if(isActionExcluded(action)) {
        	map.remove(action);
        }
    }

    return map;
}
 
Example #10
Source File: StateVariableAccessor.java    From DroidDLNA with GNU General Public License v3.0 6 votes vote down vote up
public StateVariableValue read(final StateVariable<LocalService> stateVariable, final Object serviceImpl) throws Exception {

        class AccessCommand implements Command {
            Object result;
            public void execute(ServiceManager serviceManager) throws Exception {
                result = read(serviceImpl);
                if (stateVariable.getService().isStringConvertibleType(result)) {
                    result = result.toString();
                }
            }
        }

        AccessCommand cmd = new AccessCommand();
        stateVariable.getService().getManager().execute(cmd);
        return new StateVariableValue(stateVariable, cmd.result);
    }
 
Example #11
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 #12
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 #13
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 #14
Source File: MutableStateVariable.java    From TVRemoteIME with GNU General Public License v2.0 6 votes vote down vote up
public StateVariable build() {
    return new StateVariable(
            name,
            new StateVariableTypeDetails(
                    dataType,
                    defaultValue,
                    allowedValues == null || allowedValues.size() == 0
                            ? null
                            : allowedValues.toArray(new String[allowedValues.size()]),
                    allowedValueRange == null
                            ? null :
                            new StateVariableAllowedValueRange(
                                    allowedValueRange.minimum,
                                    allowedValueRange.maximum,
                                    allowedValueRange.step
                            )
            ),
            eventDetails
    );
}
 
Example #15
Source File: MutableService.java    From TVRemoteIME with GNU General Public License v2.0 5 votes vote down vote up
public StateVariable[] createStateVariables() {
    StateVariable[] array = new StateVariable[stateVariables.size()];
    int i = 0;
    for (MutableStateVariable stateVariable : stateVariables) {
        array[i++] = stateVariable.build();
    }
    return array;
}
 
Example #16
Source File: QueryStateVariableExecutor.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
protected void executeQueryStateVariable(ActionInvocation<LocalService> actionInvocation, Object serviceImpl) throws Exception {

        LocalService service = actionInvocation.getAction().getService();

        String stateVariableName = actionInvocation.getInput("varName").toString();
        StateVariable stateVariable = service.getStateVariable(stateVariableName);

        if (stateVariable == null) {
            throw new ActionException(
                    ErrorCode.ARGUMENT_VALUE_INVALID, "No state variable found: " + stateVariableName
            );
        }

        StateVariableAccessor accessor;
        if ((accessor = service.getAccessor(stateVariable.getName())) == null) {
            throw new ActionException(
                    ErrorCode.ARGUMENT_VALUE_INVALID, "No accessor for state variable, can't read state: " + stateVariableName
            );
        }

        try {
            setOutputArgumentValue(
                    actionInvocation,
                    actionInvocation.getAction().getOutputArgument("return"),
                    accessor.read(stateVariable, serviceImpl).toString()
            );
        } catch (Exception ex) {
            throw new ActionException(ErrorCode.ACTION_FAILED, ex.getMessage());
        }
    }
 
Example #17
Source File: AnnotationActionBinder.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
protected StateVariable getStateVariable(String name) {
    for (StateVariable stateVariable : getStateVariables().keySet()) {
        if (stateVariable.getName().equals(name)) {
            return stateVariable;
        }
    }
    return null;
}
 
Example #18
Source File: AnnotationActionBinder.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
protected void validateType(StateVariable stateVariable, Class type) throws LocalServiceBindingException {

        // Validate datatype as good as we can
        // (for enums and other convertible types, the state variable type should be STRING)

        Datatype.Default expectedDefaultMapping =
                ModelUtil.isStringConvertibleType(getStringConvertibleTypes(), type)
                        ? Datatype.Default.STRING
                        : Datatype.Default.getByJavaType(type);

        log.finer("Expecting '" + stateVariable + "' to match default mapping: " + expectedDefaultMapping);

        if (expectedDefaultMapping != null &&
                !stateVariable.getTypeDetails().getDatatype().isHandlingJavaType(expectedDefaultMapping.getJavaType())) {

            // TODO: Consider custom types?!
            throw new LocalServiceBindingException(
                    "State variable '" + stateVariable + "' datatype can't handle action " +
                            "argument's Java type (change one): " + expectedDefaultMapping.getJavaType()
            );

        } else if (expectedDefaultMapping == null && stateVariable.getTypeDetails().getDatatype().getBuiltin() != null) {
            throw new LocalServiceBindingException(
                    "State variable '" + stateVariable  + "' should be custom datatype " +
                            "(action argument type is unknown Java type): " + type.getSimpleName()
            );
        }

        log.finer("State variable matches required argument datatype (or can't be validated because it is custom)");
    }
 
Example #19
Source File: PullGENAEventProcessorImpl.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
protected void readProperties(XmlPullParser xpp, IncomingEventRequestMessage message) throws Exception {
	// We're inside the propertyset tag
	StateVariable[] stateVariables = message.getService().getStateVariables();
	int event;
	while((event = xpp.next()) != XmlPullParser.END_DOCUMENT) {
		if(event != XmlPullParser.START_TAG) continue;
		if(xpp.getName().equals("property")) {
			readProperty(xpp, message, stateVariables);
		} 
	}
}
 
Example #20
Source File: UDA10ServiceDescriptorBinderImpl.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
private void generateServiceStateTable(Service serviceModel, Document descriptor, Element scpdElement) {

        Element serviceStateTableElement = appendNewElement(descriptor, scpdElement, ELEMENT.serviceStateTable);

        for (StateVariable stateVariable : serviceModel.getStateVariables()) {
            generateStateVariable(stateVariable, descriptor, serviceStateTableElement);
        }
    }
 
Example #21
Source File: MutableService.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
public StateVariable[] createStateVariables() {
    StateVariable[] array = new StateVariable[stateVariables.size()];
    int i = 0;
    for (MutableStateVariable stateVariable : stateVariables) {
        array[i++] = stateVariable.build();
    }
    return array;
}
 
Example #22
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 #23
Source File: PullGENAEventProcessorImpl.java    From TVRemoteIME with GNU General Public License v2.0 5 votes vote down vote up
protected void readProperties(XmlPullParser xpp, IncomingEventRequestMessage message) throws Exception {
	// We're inside the propertyset tag
	StateVariable[] stateVariables = message.getService().getStateVariables();
	int event;
	while((event = xpp.next()) != XmlPullParser.END_DOCUMENT) {
		if(event != XmlPullParser.START_TAG) continue;
		if(xpp.getName().equals("property")) {
			readProperty(xpp, message, stateVariables);
		} 
	}
}
 
Example #24
Source File: UDA10ServiceDescriptorBinderImpl.java    From TVRemoteIME with GNU General Public License v2.0 5 votes vote down vote up
private void generateServiceStateTable(Service serviceModel, Document descriptor, Element scpdElement) {

        Element serviceStateTableElement = appendNewElement(descriptor, scpdElement, ELEMENT.serviceStateTable);

        for (StateVariable stateVariable : serviceModel.getStateVariables()) {
            generateStateVariable(stateVariable, descriptor, serviceStateTableElement);
        }
    }
 
Example #25
Source File: AnnotationActionBinder.java    From TVRemoteIME with GNU General Public License v2.0 5 votes vote down vote up
protected void validateType(StateVariable stateVariable, Class type) throws LocalServiceBindingException {

        // Validate datatype as good as we can
        // (for enums and other convertible types, the state variable type should be STRING)

        Datatype.Default expectedDefaultMapping =
                ModelUtil.isStringConvertibleType(getStringConvertibleTypes(), type)
                        ? Datatype.Default.STRING
                        : Datatype.Default.getByJavaType(type);

        log.finer("Expecting '" + stateVariable + "' to match default mapping: " + expectedDefaultMapping);

        if (expectedDefaultMapping != null &&
                !stateVariable.getTypeDetails().getDatatype().isHandlingJavaType(expectedDefaultMapping.getJavaType())) {

            // TODO: Consider custom types?!
            throw new LocalServiceBindingException(
                    "State variable '" + stateVariable + "' datatype can't handle action " +
                            "argument's Java type (change one): " + expectedDefaultMapping.getJavaType()
            );

        } else if (expectedDefaultMapping == null && stateVariable.getTypeDetails().getDatatype().getBuiltin() != null) {
            throw new LocalServiceBindingException(
                    "State variable '" + stateVariable  + "' should be custom datatype " +
                            "(action argument type is unknown Java type): " + type.getSimpleName()
            );
        }

        log.finer("State variable matches required argument datatype (or can't be validated because it is custom)");
    }
 
Example #26
Source File: AnnotationActionBinder.java    From TVRemoteIME with GNU General Public License v2.0 5 votes vote down vote up
protected StateVariable getStateVariable(String name) {
    for (StateVariable stateVariable : getStateVariables().keySet()) {
        if (stateVariable.getName().equals(name)) {
            return stateVariable;
        }
    }
    return null;
}
 
Example #27
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 #28
Source File: QueryStateVariableExecutor.java    From TVRemoteIME with GNU General Public License v2.0 5 votes vote down vote up
protected void executeQueryStateVariable(ActionInvocation<LocalService> actionInvocation, Object serviceImpl) throws Exception {

        LocalService service = actionInvocation.getAction().getService();

        String stateVariableName = actionInvocation.getInput("varName").toString();
        StateVariable stateVariable = service.getStateVariable(stateVariableName);

        if (stateVariable == null) {
            throw new ActionException(
                    ErrorCode.ARGUMENT_VALUE_INVALID, "No state variable found: " + stateVariableName
            );
        }

        StateVariableAccessor accessor;
        if ((accessor = service.getAccessor(stateVariable.getName())) == null) {
            throw new ActionException(
                    ErrorCode.ARGUMENT_VALUE_INVALID, "No accessor for state variable, can't read state: " + stateVariableName
            );
        }

        try {
            setOutputArgumentValue(
                    actionInvocation,
                    actionInvocation.getAction().getOutputArgument("return"),
                    accessor.read(stateVariable, serviceImpl).toString()
            );
        } catch (Exception ex) {
            throw new ActionException(ErrorCode.ACTION_FAILED, ex.getMessage());
        }
    }
 
Example #29
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 #30
Source File: AnnotationActionBinder.java    From DroidDLNA with GNU General Public License v3.0 4 votes vote down vote up
public AnnotationActionBinder(Method method, Map<StateVariable, StateVariableAccessor> stateVariables, Set<Class> stringConvertibleTypes) {
    this.annotation = method.getAnnotation(UpnpAction.class);
    this.stateVariables = stateVariables;
    this.method = method;
    this.stringConvertibleTypes = stringConvertibleTypes;
}