/**
   * Creates a new Google Calendar Entry for each <code>item</code> and adds it to the processing
   * queue. The entries' title will either be the items name or <code>alias</code> if it is <code>
   * != null</code>.
   *
   * <p>The new Calendar Entry will contain a single command to be executed e.g.<br>
   *
   * <p><code>send &lt;item.name&gt; &lt;item.state&gt;</code>
   *
   * @param item the item which state should be persisted.
   * @param alias the alias under which the item should be persisted.
   */
  @Override
  public void store(final Item item, final String alias) {
    if (initialized) {
      String newAlias = alias != null ? alias : item.getName();

      CalendarEventEntry myEntry = new CalendarEventEntry();
      myEntry.setTitle(new PlainTextConstruct("[PresenceSimulation] " + newAlias));
      myEntry.setContent(
          new PlainTextConstruct(
              String.format(executeScript, item.getName(), item.getState().toString())));

      DateTime nowPlusOffset = new DateTime().plusDays(offset);

      com.google.gdata.data.DateTime time =
          com.google.gdata.data.DateTime.parseDateTime(nowPlusOffset.toString());
      When eventTimes = new When();
      eventTimes.setStartTime(time);
      eventTimes.setEndTime(time);
      myEntry.addTime(eventTimes);

      entries.offer(myEntry);

      logger.trace(
          "added new entry '{}' for item '{}' to upload queue",
          myEntry.getTitle().getPlainText(),
          item.getName());
    } else {
      logger.debug(
          "GCal PresenceSimulation Service isn't initialized properly! No entries will be uploaded to your Google Calendar");
    }
  }
Example #2
0
 /** Visualization for {@link StringType} and {@link DecimalType}. {@inheritDoc} */
 @Override
 public boolean visualizationVarStatus(
     ModStatusVar pchkInput, Command cmd, Item item, EventPublisher eventPublisher) {
   // We are actually not meant to visualize anything.
   // But (just in case) someone is really lazy in doing the item-definitions, we try to be helpful
   // by showing the
   // current value.
   if (pchkInput.getLogicalSourceAddr().equals(this.addr) && pchkInput.getVar() == this.var) {
     if (item.getAcceptedDataTypes().contains(StringType.class)) {
       String valueStr =
           pchkInput
               .getValue()
               .toVarUnitString(
                   this.unit,
                   LcnDefs.Var.isLockableRegulatorSource(this.var),
                   LcnDefs.Var.useLcnSpecialValues(this.var));
       eventPublisher.postUpdate(item.getName(), new StringType(valueStr));
       return true;
     } else if (item.getAcceptedDataTypes().contains(DecimalType.class)) {
       eventPublisher.postUpdate(
           item.getName(),
           new DecimalType(
               pchkInput
                   .getValue()
                   .toVarUnit(this.unit, LcnDefs.Var.isLockableRegulatorSource(this.var))));
       return true;
     }
   }
   return false;
 }
Example #3
0
  /** @{inheritDoc} */
  @Override
  protected void execute() {
    logger.trace("Connecting to {}" + baseURL);

    clearState();

    String xmlDoc = fetchStateFromController();

    if (xmlDoc == null) {
      return;
    }

    for (AutelisBindingProvider provider : providers) {
      for (String itemName : provider.getItemNames()) {
        Item item = provider.getItem(itemName);
        String config = provider.getAutelisBindingConfigString(itemName);
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        try {
          InputSource is = new InputSource(new StringReader(xmlDoc));
          String value = xpath.evaluate("response/" + config.replace('.', '/'), is);
          State state = toState(item.getClass(), value);
          State oldState = stateMap.put(itemName, state);
          if (!state.equals(oldState)) {
            logger.debug("updating item {} with state {}", itemName, state);
            eventPublisher.postUpdate(itemName, state);
          }
        } catch (XPathExpressionException e) {
          logger.warn("could not parse xml", e);
        }
      }
    }
  }
  /** {@inheritDoc} */
  @Override
  public void processBindingConfiguration(String context, Item item, String bindingConfig)
      throws BindingConfigParseException {
    logger.trace("Processing binding configuration for item {}", item.getName());
    super.processBindingConfiguration(context, item, bindingConfig);

    SatelBindingConfig bc = this.createBindingConfig(bindingConfig);
    logger.trace("Adding binding configuration for item {}: {}", item.getName(), bc);
    addBindingConfig(item, bc);
  }
Example #5
0
  /** {@inheritDoc} */
  @Override
  protected void internalReceiveCommand(String itemName, Command command) {
    try {
      logger.debug("internalReceiveCommand: itemName '{}', command '{}'", itemName, command);

      // Lookup the MiOS Unit name and property for this item
      String unitName = getMiosUnitName(itemName);

      MiosUnitConnector connector = getMiosConnector(unitName);
      if (connector == null) {
        logger.warn(
            "Received command ({}) for item '{}' but no connector found for MiOS Unit '{}', ignoring",
            new Object[] {command.toString(), itemName, unitName});
        return;
      }

      if (!connector.isConnected()) {
        logger.warn(
            "Received command ({}) for item '{}' but the connection to the MiOS Unit '{}' is down, ignoring",
            new Object[] {command.toString(), itemName, unitName});
        return;
      }

      for (BindingProvider provider : providers) {
        if (provider instanceof MiosBindingProvider) {
          MiosBindingProviderImpl miosProvider = (MiosBindingProviderImpl) provider;
          MiosBindingConfig config = miosProvider.getMiosBindingConfig(itemName);

          if (config != null) {
            ItemRegistry reg = miosProvider.getItemRegistry();

            if (reg != null) {
              Item item = reg.getItem(config.getItemName());
              State state = item.getState();
              connector.invokeCommand(config, command, state);
            } else {
              logger.warn(
                  "internalReceiveCommand: Missing ItemRegistry for item '{}' command '{}'",
                  itemName,
                  command);
            }
          } else {
            logger.trace(
                "internalReceiveCommand: Missing BindingConfig for item '{}' command '{}'",
                itemName,
                command);
          }
        }
      }

    } catch (Exception e) {
      logger.error("Error handling command", e);
    }
  }
 /** {@inheritDoc} */
 @Override
 public void validateItemType(Item item, String bindingConfig) throws BindingConfigParseException {
   if (!(item instanceof SwitchItem || item instanceof NumberItem || item instanceof StringItem)) {
     throw new BindingConfigParseException(
         "item '"
             + item.getName()
             + "' is of type '"
             + item.getClass().getSimpleName()
             + "', only Switch-, String and NumberItems are allowed - please check your *.items configuration");
   }
 }
 /** Item processing for the LCN bindings. {@inheritDoc} */
 @Override
 public void processBindingConfiguration(String context, Item item, String bindingConfig)
     throws BindingConfigParseException {
   super.processBindingConfiguration(context, item, bindingConfig);
   Matcher matcher = PATTERN_BINDING_GENERAL.matcher(bindingConfig);
   if (!matcher.matches()) {
     throw new BindingConfigParseException(bindingConfig + "' contains no valid binding!");
   }
   matcher.reset();
   LcnBindingConfig bc = new LcnBindingConfig(item);
   while (matcher.find()) {
     String binding = matcher.group(1);
     if (binding != null && !binding.trim().isEmpty()) {
       String openHabCmd = null;
       String connId, lcnTarget;
       Matcher openHabMatcher = PATTERN_BINDING_WITH_OPENHAB.matcher(binding);
       Matcher pureMatcher = PATTERN_BINDING_PURE.matcher(binding);
       if (openHabMatcher.matches()) {
         openHabCmd = openHabMatcher.group(1);
         connId = openHabMatcher.group(2);
         lcnTarget = openHabMatcher.group(3);
       } else if (pureMatcher.matches()) {
         connId = pureMatcher.group(1);
         lcnTarget = pureMatcher.group(2);
       } else {
         throw new BindingConfigParseException(
             "Invalid binding configuration for " + binding + "!");
       }
       String lcnShort = resolveMappings(lcnTarget, openHabCmd);
       if (lcnShort == null || lcnShort.equals(openHabCmd)) {
         lcnShort = lcnTarget;
       }
       Command cmd =
           openHabCmd == null
               ? TypeParser.parseCommand(new StringItem("").getAcceptedCommandTypes(), "")
               : openHabCmd.equals("%i")
                   ? new StringType("%i")
                   : TypeParser.parseCommand(item.getAcceptedCommandTypes(), openHabCmd);
       bc.add(new LcnBindingConfig.Mapping(cmd, connId, lcnShort));
     }
   }
   // Finished
   this.addBindingConfig(item, bc);
   for (LcnAddrMod addr : bc.getRelatedModules()) {
     HashSet<String> l = this.itemNamesByModulCache.get(addr);
     if (l == null) {
       l = new HashSet<String>();
       this.itemNamesByModulCache.put(addr, l);
     }
     l.add(item.getName());
   }
 }
Example #8
0
  @Override
  public void handleXPLMessage(xPL_MessageI theMessage) {

    for (XplBindingProvider provider : providers) {
      List<String> matchingItems = provider.hasMessage(theMessage);
      for (String itemName : matchingItems) {
        XplBindingConfig config = provider.getConfig(itemName);
        if (config == null) {
          continue;
        }

        String current = theMessage.getNamedValue(config.NamedParameter);

        Item item = provider.getItem(itemName);
        if (item != null) {
          if (item instanceof SwitchItem) {
            OnOffType status =
                (current.equalsIgnoreCase("on")
                        || current.equalsIgnoreCase("true")
                        || current.equalsIgnoreCase("1")
                        || current.equalsIgnoreCase("open")
                        || current.equalsIgnoreCase("high"))
                    ? OnOffType.ON
                    : OnOffType.OFF;
            synchronized (item) {
              if (!item.getState().equals(status)) {
                eventPublisher.postUpdate(itemName, status);
                ((SwitchItem) item).setState(status);
              }
            }
          } else if (item instanceof NumberItem) {
            DecimalType value = new DecimalType(current);
            synchronized (item) {
              if (!item.getState().equals(value)) {
                eventPublisher.postUpdate(itemName, value);
                ((NumberItem) item).setState(value);
              }
            }
          }
          if (item instanceof StringItem) {
            StringType value = new StringType(current);
            synchronized (item) {
              if (!item.getState().equals(value)) {
                eventPublisher.postUpdate(itemName, value);
                ((StringItem) item).setState(value);
              }
            }
          }
        }
      }
    }
  }
 /** {@inheritDoc} */
 @Override
 public Item getItem(String itemName) {
   for (Set<Item> items : contextMap.values()) {
     if (items != null) {
       for (Item item : items) {
         if (itemName.equals(item.getName())) {
           return item;
         }
       }
     }
   }
   return null;
 }
  public List<ItemStateData> getItemStates() throws ServiceException {
    List<ItemStateData> itemStates = new ArrayList<ItemStateData>();

    ItemRegistry itemRegistry = getItemRegistry();
    for (Item item : itemRegistry.getItems()) {
      logger.debug("Item: " + item.getName() + " " + item.getState());
      StateTransformable state = getState(item);
      ItemStateData itemState =
          new ItemStateData(System.currentTimeMillis(), item.getName(), state);
      itemStates.add(itemState);
    }

    return itemStates;
  }
Example #11
0
 /**
  * Posts a status update for a specified item to the event bus.
  *
  * @param itemName the name of the item to send the status update for
  * @param stateAsString the new state of the item
  */
 public static Object postUpdate(String itemName, String stateString) {
   ItemRegistry registry = (ItemRegistry) ScriptActivator.itemRegistryTracker.getService();
   EventPublisher publisher = (EventPublisher) ScriptActivator.eventPublisherTracker.getService();
   if (publisher != null && registry != null) {
     try {
       Item item = registry.getItem(itemName);
       State state = TypeParser.parseState(item.getAcceptedDataTypes(), stateString);
       publisher.postUpdate(itemName, state);
     } catch (ItemNotFoundException e) {
       logger.warn("Item '" + itemName + "' does not exist.");
     }
   }
   return null;
 }
Example #12
0
 /**
  * Sends a command for a specified item to the event bus.
  *
  * @param itemName the name of the item to send the command to
  * @param commandString the command to send
  */
 public static Object sendCommand(String itemName, String commandString) {
   ItemRegistry registry = (ItemRegistry) ScriptActivator.itemRegistryTracker.getService();
   EventPublisher publisher = (EventPublisher) ScriptActivator.eventPublisherTracker.getService();
   if (publisher != null && registry != null) {
     try {
       Item item = registry.getItem(itemName);
       Command command = TypeParser.parseCommand(item.getAcceptedCommandTypes(), commandString);
       publisher.sendCommand(itemName, command);
     } catch (ItemNotFoundException e) {
       logger.warn("Item '" + itemName + "' does not exist.");
     }
   }
   return null;
 }
  @Override
  public void complete_ItemName(
      EObject model,
      RuleCall ruleCall,
      ContentAssistContext context,
      ICompletionProposalAcceptor acceptor) {
    super.complete_ItemName(model, ruleCall, context, acceptor);
    ItemRegistry itemRegistry = RuleModelUIActivator.itemRegistryTracker.getService();

    for (Item item : itemRegistry.getItems()) {
      if (item.getName().startsWith(context.getPrefix())) {
        acceptor.accept(createCompletionProposal(item.getName(), context));
      }
    }
  }
Example #14
0
 /** Visualization for {@link DecimalType} and {@link StringType}. {@inheritDoc} */
 @Override
 public boolean visualizationLedsAndLogicOpsStatus(
     ModStatusLedsAndLogicOps pchkInput, Command cmd, Item item, EventPublisher eventPublisher) {
   if (pchkInput.getLogicalSourceAddr().equals(this.addr)) {
     if (item.getAcceptedDataTypes().contains(DecimalType.class)) {
       int n;
       switch (pchkInput.getLedState(this.ledId)) {
         case OFF:
           n = 0;
           break;
         case ON:
           n = 1;
           break;
         case BLINK:
           n = 2;
           break;
         case FLICKER:
           n = 3;
           break;
         default:
           throw new Error();
       }
       eventPublisher.postUpdate(item.getName(), new DecimalType(n));
       return true;
     } else if (item.getAcceptedDataTypes().contains(StringType.class)) {
       String s;
       switch (pchkInput.getLedState(this.ledId)) {
         case OFF:
           s = this.stateTexts[0];
           break;
         case ON:
           s = this.stateTexts[1];
           break;
         case BLINK:
           s = this.stateTexts[2];
           break;
         case FLICKER:
           s = this.stateTexts[3];
           break;
         default:
           throw new Error();
       }
       eventPublisher.postUpdate(item.getName(), new StringType(s));
       return true;
     }
   }
   return false;
 }
Example #15
0
 /**
  * Sends a command for a specified item to the event bus.
  *
  * @param item the item to send the command to
  * @param commandString the command to send
  */
 public static Object sendCommand(Item item, String commandString) {
   if (item != null) {
     return sendCommand(item.getName(), commandString);
   } else {
     return null;
   }
 }
Example #16
0
 /**
  * Posts a status update for a specified item to the event bus. t
  *
  * @param item the item to send the status update for
  * @param state the new state of the item
  */
 public static Object postUpdate(Item item, State state) {
   EventPublisher publisher = (EventPublisher) ScriptActivator.eventPublisherTracker.getService();
   if (publisher != null && item != null) {
     publisher.postUpdate(item.getName(), state);
   }
   return null;
 }
Example #17
0
 /**
  * Posts a status update for a specified item to the event bus.
  *
  * @param item the item to send the status update for
  * @param stateAsString the new state of the item
  */
 public static Object postUpdate(Item item, String stateAsString) {
   if (item != null) {
     return postUpdate(item.getName(), stateAsString);
   } else {
     return null;
   }
 }
Example #18
0
 /**
  * Posts a status update for a specified item to the event bus.
  *
  * @param item the item to send the status update for
  * @param state the new state of the item as a number
  */
 public static Object postUpdate(Item item, Number state) {
   if (item != null && state != null) {
     return postUpdate(item.getName(), state.toString());
   } else {
     return null;
   }
 }
  /** {@inheritDoc} */
  @Override
  public State convertEventToState(Item item, SatelEvent event) {
    if (!(event instanceof IntegraStatusEvent) || hasOptionEnabled(Options.COMMANDS_ONLY)) {
      return null;
    }

    IntegraStatusEvent statusEvent = (IntegraStatusEvent) event;

    switch (this.statusType) {
      case DATE_TIME:
        if (item.getAcceptedDataTypes().contains(DateTimeType.class)) {
          return new DateTimeType(statusEvent.getIntegraTime());
        } else {
          return null;
        }
      case SERVICE_MODE:
        return booleanToState(item, statusEvent.inServiceMode());
      case TROUBLES:
        return booleanToState(item, statusEvent.troublesPresent());
      case TROUBLES_MEMORY:
        return booleanToState(item, statusEvent.troublesMemory());
      case ACU100_PRESENT:
        return booleanToState(item, statusEvent.isAcu100Present());
      case INTRX_PRESENT:
        return booleanToState(item, statusEvent.isIntRxPresent());
      case GRADE23_SET:
        return booleanToState(item, statusEvent.isGrade23Set());
    }

    return null;
  }
 /** {@inheritDoc} */
 @Override
 public void validateItemType(Item item, String bindingConfig) throws BindingConfigParseException {
   // TODO: should parse, then do type checking based on binding config string!
   if ((item instanceof NumberItem)
       || (item instanceof ContactItem)
       || (item instanceof StringItem)
       || (item instanceof SwitchItem)) {
     return;
   }
   throw new BindingConfigParseException(
       "item '"
           + item.getName()
           + "' is of type '"
           + item.getClass().getSimpleName()
           + "', only Number, Contact, String, or Switch item types are allowed. Check your *.items configuration");
 }
Example #21
0
 /**
  * Sends a number as a command for a specified item to the event bus.
  *
  * @param item the item to send the command to
  * @param number the number to send as a command
  */
 public static Object sendCommand(Item item, Number number) {
   if (item != null && number != null) {
     return sendCommand(item.getName(), number.toString());
   } else {
     return null;
   }
 }
Example #22
0
 /**
  * Stores the current states for a list of items in a map. A group item is not itself put into the
  * map, but instead all its members.
  *
  * @param items the items for which the state should be stored
  * @return the map of items with their states
  */
 public static Map<Item, State> storeStates(Item... items) {
   Map<Item, State> statesMap = Maps.newHashMap();
   if (items != null) {
     for (Item item : items) {
       if (item instanceof GroupItem) {
         GroupItem groupItem = (GroupItem) item;
         for (Item member : groupItem.getAllMembers()) {
           statesMap.put(member, member.getState());
         }
       } else {
         statesMap.put(item, item.getState());
       }
     }
   }
   return statesMap;
 }
Example #23
0
 /**
  * Sends a command for a specified item to the event bus.
  *
  * @param item the item to send the command to
  * @param command the command to send
  */
 public static Object sendCommand(Item item, Command command) {
   EventPublisher publisher = (EventPublisher) ScriptActivator.eventPublisherTracker.getService();
   if (publisher != null && item != null) {
     publisher.sendCommand(item.getName(), command);
   }
   return null;
 }
  /** {@inheritDoc} */
  @Override
  void handleEvent(ZWaveCommandClassValueEvent event, Item item, Map<String, String> arguments) {
    ZWaveStateConverter<?, ?> converter = this.getStateConverter(item, event.getValue());

    if (converter == null) {
      logger.warn(
          "NODE {}: No converter found for item = {}, endpoint = {}, ignoring event.",
          event.getNodeId(),
          item.getName(),
          event.getEndpoint());
      return;
    }

    State state = converter.convertFromValueToState(event.getValue());
    this.getEventPublisher().postUpdate(item.getName(), state);
  }
Example #25
0
  /** {@inheritDoc} */
  @Override
  public void receiveCommand(
      Item item,
      Command command,
      ZWaveNode node,
      ZWaveMeterCommandClass commandClass,
      int endpointId,
      Map<String, String> arguments) {

    // It's not an ON command from a button switch, do not reset
    if (command != OnOffType.ON) {
      return;
    }

    // get the reset message - will return null if not supported
    SerialMessage serialMessage =
        node.encapsulate(commandClass.getResetMessage(), commandClass, endpointId);

    if (serialMessage == null) {
      logger.warn(
          "NODE {}: Meter reset not supported for item = {}, endpoint = {}, ignoring event.",
          node.getNodeId(),
          item.getName(),
          endpointId);
      return;
    }

    // send reset message
    this.getController().sendData(serialMessage);

    // poll the device
    for (SerialMessage serialGetMessage : commandClass.getDynamicValues(true)) {
      this.getController().sendData(node.encapsulate(serialGetMessage, commandClass, endpointId));
    }
  }
  /** Constructor */
  public SappBindingConfigDimmerItem(Item item, String bindingConfig)
      throws BindingConfigParseException {

    super(item.getName());

    this.status = parseSappAddressStatus(bindingConfig);
  }
Example #27
0
  /**
   * Procedure to validate selector string.
   *
   * @param valueSelector selector string e.g. RawData, Command, Temperature
   * @return true if item is valid.
   * @throws IllegalArgumentException Not valid value selector.
   * @throws InvalidClassException Not valid class for value selector.
   */
  public static boolean validateBinding(String valueSelector, Item item)
      throws IllegalArgumentException, InvalidClassException {

    for (RMEValueSelector c : RMEValueSelector.values()) {
      if (c.text.equals(valueSelector) && item != null) {

        logger.debug("Accepted types are {}", item.getAcceptedDataTypes());
        logger.debug("typeclass is {}", c.getTypeClass());

        if (item.getAcceptedDataTypes().contains(c.getTypeClass())) return true;
        else throw new InvalidClassException("Not valid class for value selector");
      }
    }

    throw new IllegalArgumentException("Not valid value selector");
  }
 /**
  * Checks if the bindingConfig contains a valid binding type and returns an appropriate instance.
  *
  * @param item
  * @param bindingConfig
  * @throws BindingConfigParseException if bindingConfig is no valid binding type
  */
 protected EcoTouchBindingConfig parseBindingConfig(Item item, EcoTouchTags bindingConfig)
     throws BindingConfigParseException {
   if (EcoTouchTags.validateBinding(bindingConfig, item.getClass())) {
     return new EcoTouchBindingConfig(bindingConfig);
   } else {
     throw new BindingConfigParseException("'" + bindingConfig + "' is no valid binding type");
   }
 }
 /**
  * Checks if the bindingConfig contains a valid binding type and returns an appropriate instance.
  *
  * @param item
  * @param bindingConfig
  * @throws BindingConfigParseException if bindingConfig is no valid binding type
  */
 protected HeatPumpBindingConfig parseBindingConfig(Item item, HeatpumpCommandType bindingConfig)
     throws BindingConfigParseException {
   if (HeatpumpCommandType.validateBinding(bindingConfig, item.getClass())) {
     return new HeatPumpBindingConfig(bindingConfig);
   } else {
     throw new BindingConfigParseException("'" + bindingConfig + "' is no valid binding type");
   }
 }
 /**
  * Removes existing item configurations
  *
  * @param bcl array list of binding configs to be checked
  * @param item item to be checked for
  */
 private static void removeExisting(ArrayList<AlarmDecoderBindingConfig> bcl, Item item) {
   for (Iterator<AlarmDecoderBindingConfig> it = bcl.iterator(); it.hasNext(); ) {
     AlarmDecoderBindingConfig bc = it.next();
     if (bc.getItemName().equals(item.getName())) {
       it.remove();
     }
   }
 }