Search in sources :

Example 1 with SonosBindingProvider

use of org.openhab.binding.sonos.SonosBindingProvider in project openhab1-addons by openhab.

the class SonosBinding method processVariableMap.

@SuppressWarnings("rawtypes")
public void processVariableMap(RemoteDevice device, Map<String, StateVariableValue> values) {
    if (device != null && values != null) {
        SonosZonePlayer associatedPlayer = sonosZonePlayerCache.getByDevice(device);
        if (associatedPlayer == null) {
            logger.debug("There is no Sonos Player defined matching the device {}", device);
            return;
        }
        for (String stateVariable : values.keySet()) {
            // find all the CommandTypes that are defined for each
            // StateVariable
            List<SonosCommandType> supportedCommands = SonosCommandType.getCommandByVariable(stateVariable);
            StateVariableValue status = values.get(stateVariable);
            for (SonosCommandType sonosCommandType : supportedCommands) {
                // create a new State based on the type of Sonos Command and
                // the status value in the map
                Type newState = null;
                try {
                    newState = createStateForType((Class<? extends State>) sonosCommandType.getTypeClass(), status.getValue().toString());
                } catch (BindingConfigParseException e) {
                    logger.error("Error parsing a value {} to a state variable of type {}", status.toString(), sonosCommandType.getTypeClass().toString());
                }
                for (SonosBindingProvider provider : providers) {
                    List<String> qualifiedItems = provider.getItemNames(sonosZonePlayerCache.getByDevice(device).getId(), sonosCommandType.getSonosCommand());
                    List<String> qualifiedItemsByUDN = provider.getItemNames(sonosZonePlayerCache.getByDevice(device).getUdn().getIdentifierString(), sonosCommandType.getSonosCommand());
                    for (String item : qualifiedItemsByUDN) {
                        if (!qualifiedItems.contains(item)) {
                            qualifiedItems.add(item);
                        }
                    }
                    for (String anItem : qualifiedItems) {
                        // get the openHAB commands attached to each Item at
                        // this given Provider
                        List<Command> commands = provider.getCommands(anItem, sonosCommandType.getSonosCommand());
                        if (provider.getAcceptedDataTypes(anItem).contains(sonosCommandType.getTypeClass())) {
                            if (newState != null) {
                                eventPublisher.postUpdate(anItem, (State) newState);
                            } else {
                                throw new IllegalClassException("Cannot process update for the command of type " + sonosCommandType.toString());
                            }
                        } else {
                            logger.warn("Cannot cast {} to an accepted state type for item {}", sonosCommandType.getTypeClass().toString(), anItem);
                        }
                    }
                }
            }
        }
    }
}
Also used : StateVariableValue(org.teleal.cling.model.state.StateVariableValue) SonosCommandType(org.openhab.binding.sonos.SonosCommandType) IllegalClassException(org.apache.commons.lang.IllegalClassException) StringType(org.openhab.core.library.types.StringType) SonosCommandType(org.openhab.binding.sonos.SonosCommandType) OnOffType(org.openhab.core.library.types.OnOffType) UDAServiceType(org.teleal.cling.model.types.UDAServiceType) Type(org.openhab.core.types.Type) DecimalType(org.openhab.core.library.types.DecimalType) SonosBindingProvider(org.openhab.binding.sonos.SonosBindingProvider) Command(org.openhab.core.types.Command) State(org.openhab.core.types.State) BindingConfigParseException(org.openhab.model.item.binding.BindingConfigParseException)

Example 2 with SonosBindingProvider

use of org.openhab.binding.sonos.SonosBindingProvider in project openhab1-addons by openhab.

the class SonosBinding method execute.

@Override
protected void execute() {
    if (isProperlyConfigured()) {
        if (!bindingStarted) {
            // This will create necessary network resources for UPnP right away
            upnpService = new UpnpServiceImpl(new SonosUpnpServiceConfiguration(), listener);
            try {
                Iterator<SonosZonePlayer> it = sonosZonePlayerCache.iterator();
                while (it.hasNext()) {
                    SonosZonePlayer aPlayer = it.next();
                    if (aPlayer.getDevice() == null) {
                        logger.info("Querying the network for a predefined Sonos device with UDN {}", aPlayer.getUdn());
                        upnpService.getControlPoint().search(new UDNHeader(aPlayer.getUdn()));
                    }
                }
                logger.info("Querying the network for any other Sonos device");
                final UDAServiceType udaType = new UDAServiceType("AVTransport");
                upnpService.getControlPoint().search(new UDAServiceTypeHeader(udaType));
            } catch (Exception e) {
                logger.warn("An exception occurred while searching the network for Sonos devices: ", e.getMessage());
            }
            bindingStarted = true;
        }
        Scheduler sched = null;
        try {
            sched = StdSchedulerFactory.getDefaultScheduler();
        } catch (SchedulerException e) {
            logger.error("An exception occurred while getting a reference to the Quartz Scheduler");
        }
        // Cycle through the Items and setup sonos zone players if required
        for (SonosBindingProvider provider : providers) {
            for (String itemName : provider.getItemNames()) {
                for (String sonosID : provider.getSonosID(itemName)) {
                    if (!sonosZonePlayerCache.contains(sonosID)) {
                        // the device is not yet discovered on the network or not defined in the .cfg
                        // Verify that the sonosID has the format of a valid UDN
                        Pattern SONOS_UDN_PATTERN = Pattern.compile("RINCON_(\\w{17})");
                        Matcher matcher = SONOS_UDN_PATTERN.matcher(sonosID);
                        if (matcher.matches()) {
                            // Add device to the cached Configs
                            SonosZonePlayer thePlayer = new SonosZonePlayer(sonosID, self);
                            thePlayer.setUdn(new UDN(sonosID));
                            sonosZonePlayerCache.add(thePlayer);
                            // Query the network for this device
                            logger.info("Querying the network for a predefined Sonos device with UDN '{}'", thePlayer.getUdn());
                            upnpService.getControlPoint().search(new UDNHeader(thePlayer.getUdn()));
                        }
                    }
                }
            }
        }
        // Cycle through the item binding configuration that define polling criteria
        for (SonosCommandType sonosCommandType : SonosCommandType.getPolling()) {
            for (SonosBindingProvider provider : providers) {
                for (String itemName : provider.getItemNames(sonosCommandType.getSonosCommand())) {
                    for (Command aCommand : provider.getCommands(itemName, sonosCommandType.getSonosCommand())) {
                        // We are dealing with a valid device
                        SonosZonePlayer thePlayer = sonosZonePlayerCache.getById(provider.getSonosID(itemName, aCommand));
                        if (thePlayer != null) {
                            RemoteDevice theDevice = thePlayer.getDevice();
                            // Not all Sonos devices have the same capabilities
                            if (theDevice != null) {
                                if (theDevice.findService(new UDAServiceId(sonosCommandType.getService())) != null) {
                                    boolean jobExists = false;
                                    // enumerate each job group
                                    try {
                                        for (String group : sched.getJobGroupNames()) {
                                            // enumerate each job in group
                                            for (JobKey jobKey : sched.getJobKeys(jobGroupEquals(group))) {
                                                if (jobKey.getName().equals(provider.getSonosID(itemName, aCommand) + "-" + sonosCommandType.getJobClass().toString())) {
                                                    jobExists = true;
                                                    break;
                                                }
                                            }
                                        }
                                    } catch (SchedulerException e1) {
                                        logger.error("An exception occurred while quering the Quartz Scheduler ({})", e1.getMessage());
                                    }
                                    if (!jobExists) {
                                        // set up the Quartz jobs
                                        JobDataMap map = new JobDataMap();
                                        map.put("Player", thePlayer);
                                        JobDetail job = newJob(sonosCommandType.getJobClass()).withIdentity(provider.getSonosID(itemName, aCommand) + "-" + sonosCommandType.getJobClass().toString(), "Sonos-" + provider.toString()).usingJobData(map).build();
                                        Trigger trigger = newTrigger().withIdentity(provider.getSonosID(itemName, aCommand) + "-" + sonosCommandType.getJobClass().toString(), "Sonos-" + provider.toString()).startNow().withSchedule(simpleSchedule().repeatForever().withIntervalInMilliseconds(pollingPeriod)).build();
                                        try {
                                            sched.scheduleJob(job, trigger);
                                        } catch (SchedulerException e) {
                                            logger.error("An exception occurred while scheduling a Quartz Job ({})", e.getMessage());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) JobDataMap(org.quartz.JobDataMap) UpnpServiceImpl(org.teleal.cling.UpnpServiceImpl) SchedulerException(org.quartz.SchedulerException) UDNHeader(org.teleal.cling.model.message.header.UDNHeader) Matcher(java.util.regex.Matcher) Scheduler(org.quartz.Scheduler) SonosCommandType(org.openhab.binding.sonos.SonosCommandType) UDAServiceTypeHeader(org.teleal.cling.model.message.header.UDAServiceTypeHeader) ConfigurationException(org.osgi.service.cm.ConfigurationException) IllegalClassException(org.apache.commons.lang.IllegalClassException) JobExecutionException(org.quartz.JobExecutionException) SAXException(org.xml.sax.SAXException) BindingConfigParseException(org.openhab.model.item.binding.BindingConfigParseException) SchedulerException(org.quartz.SchedulerException) JobKey(org.quartz.JobKey) JobDetail(org.quartz.JobDetail) SonosBindingProvider(org.openhab.binding.sonos.SonosBindingProvider) Trigger(org.quartz.Trigger) TriggerBuilder.newTrigger(org.quartz.TriggerBuilder.newTrigger) Command(org.openhab.core.types.Command) UDAServiceType(org.teleal.cling.model.types.UDAServiceType) RemoteDevice(org.teleal.cling.model.meta.RemoteDevice) UDN(org.teleal.cling.model.types.UDN) UDAServiceId(org.teleal.cling.model.types.UDAServiceId)

Example 3 with SonosBindingProvider

use of org.openhab.binding.sonos.SonosBindingProvider in project openhab1-addons by openhab.

the class SonosBinding method internalReceiveCommand.

@Override
protected void internalReceiveCommand(String itemName, Command command) {
    SonosBindingProvider provider = findFirstMatchingBindingProvider(itemName);
    String commandAsString = command.toString();
    if (command != null) {
        List<Command> commands = new ArrayList<Command>();
        if (command instanceof StringType || command instanceof DecimalType) {
            commands = provider.getVariableCommands(itemName);
        } else {
            commands.add(command);
        }
        for (Command someCommand : commands) {
            String sonosID = provider.getSonosID(itemName, someCommand);
            String sonosCommand = provider.getSonosCommand(itemName, someCommand);
            SonosCommandType sonosCommandType = null;
            try {
                sonosCommandType = SonosCommandType.getCommandType(sonosCommand, Direction.OUT);
            } catch (Exception e) {
                logger.error("An exception occured while verifying command compatibility ({})", e.getMessage());
            }
            if (sonosID != null) {
                if (sonosCommandType != null) {
                    logger.debug("Executing command: item:{}, command:{}, ID:{}, CommandType:{}, commandString:{}", new Object[] { itemName, someCommand, sonosID, sonosCommandType, commandAsString });
                    executeCommand(itemName, someCommand, sonosID, sonosCommandType, commandAsString);
                } else {
                    logger.error("wrong command type for binding [Item={}, command={}]", itemName, commandAsString);
                }
            } else {
                logger.error("{} is an unrecognised command for Item {}", commandAsString, itemName);
            }
        }
    }
}
Also used : SonosBindingProvider(org.openhab.binding.sonos.SonosBindingProvider) Command(org.openhab.core.types.Command) StringType(org.openhab.core.library.types.StringType) SonosCommandType(org.openhab.binding.sonos.SonosCommandType) ArrayList(java.util.ArrayList) DecimalType(org.openhab.core.library.types.DecimalType) ConfigurationException(org.osgi.service.cm.ConfigurationException) IllegalClassException(org.apache.commons.lang.IllegalClassException) JobExecutionException(org.quartz.JobExecutionException) SAXException(org.xml.sax.SAXException) BindingConfigParseException(org.openhab.model.item.binding.BindingConfigParseException) SchedulerException(org.quartz.SchedulerException)

Aggregations

IllegalClassException (org.apache.commons.lang.IllegalClassException)3 SonosBindingProvider (org.openhab.binding.sonos.SonosBindingProvider)3 SonosCommandType (org.openhab.binding.sonos.SonosCommandType)3 Command (org.openhab.core.types.Command)3 BindingConfigParseException (org.openhab.model.item.binding.BindingConfigParseException)3 DecimalType (org.openhab.core.library.types.DecimalType)2 StringType (org.openhab.core.library.types.StringType)2 ConfigurationException (org.osgi.service.cm.ConfigurationException)2 JobExecutionException (org.quartz.JobExecutionException)2 SchedulerException (org.quartz.SchedulerException)2 UDAServiceType (org.teleal.cling.model.types.UDAServiceType)2 SAXException (org.xml.sax.SAXException)2 ArrayList (java.util.ArrayList)1 Matcher (java.util.regex.Matcher)1 Pattern (java.util.regex.Pattern)1 OnOffType (org.openhab.core.library.types.OnOffType)1 State (org.openhab.core.types.State)1 Type (org.openhab.core.types.Type)1 JobDataMap (org.quartz.JobDataMap)1 JobDetail (org.quartz.JobDetail)1