Search in sources :

Example 6 with ActionDoc

use of org.openhab.core.scriptengine.action.ActionDoc in project openhab1-addons by openhab.

the class Satel method satelReadDeviceName.

/**
     * Reads name of alarm system's device.
     * Device types:
     * <ul>
     * <li>PARTITION</li>
     * <li>ZONE</li>
     * <li>USER</li>
     * <li>EXPANDER</li>
     * <li>LCD</li>
     * <li>OUTPUT</li>
     * <li>TIMER</li>
     * <li>TELEPHONE</li>
     * <li>OBJECT</li>
     * </ul>
     *
     * @param deviceType type of the device
     * @param deviceNumber number of the device
     * @return string representing device's name or <code>null</code> if device is not present or an error occurred
     */
@ActionDoc(text = "Returns name of a device.")
public static String satelReadDeviceName(@ParamDoc(name = "deviceType", text = "type of the device, one of: PARTITION, ZONE, USER, EXPANDER, LCD, OUTPUT, TIMER, TELEPHONE, OBJECT") String deviceType, @ParamDoc(name = "deviceNumber", text = "number of the device to read") int deviceNumber) {
    if (!satelIsConnected()) {
        logger.warn("Not connected to communication module or Satel binding not available.");
        return null;
    }
    DeviceType devType;
    try {
        devType = DeviceType.valueOf(deviceType.toUpperCase());
    } catch (Exception e) {
        logger.warn("Invalid device type given: {}", deviceType);
        return null;
    }
    ReadDeviceInfoCommand cmd = new ReadDeviceInfoCommand(devType, deviceNumber);
    if (!SatelActionService.satelCommModule.sendCommand(cmd)) {
        logger.warn("Unable to read device info: {}, {}", deviceType, deviceNumber);
        return null;
    }
    try {
        return cmd.getName(SatelActionService.satelCommModule.getTextEncoding());
    } catch (UnsupportedEncodingException e) {
        logger.error("Unsupported encoding: {}", SatelActionService.satelCommModule.getTextEncoding());
        return null;
    }
}
Also used : DeviceType(org.openhab.binding.satel.command.ReadDeviceInfoCommand.DeviceType) ReadDeviceInfoCommand(org.openhab.binding.satel.command.ReadDeviceInfoCommand) UnsupportedEncodingException(java.io.UnsupportedEncodingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ActionDoc(org.openhab.core.scriptengine.action.ActionDoc)

Example 7 with ActionDoc

use of org.openhab.core.scriptengine.action.ActionDoc in project openhab1-addons by openhab.

the class Squeezebox method squeezeboxSpeak.

@ActionDoc(text = "Speak a message via one of your Squeezebox devices using the specified volume and using specified resume status", returns = "<code>true</code>, if successful and <code>false</code> otherwise.")
public static boolean squeezeboxSpeak(@ParamDoc(name = "playerId", text = "The Squeezebox to send the message to") String playerId, @ParamDoc(name = "message", text = "The message to say") String message, @ParamDoc(name = "volume", text = "The volume to set the device when speaking this message (between 1-100)") int volume, @ParamDoc(name = "resumePlayback", text = "Continue playback after speech") Boolean resumePlayback) {
    if (!isReady()) {
        return false;
    }
    // get the player - can return null if the playerId is bogus
    SqueezePlayer player = squeezeServer.getPlayer(playerId);
    if (player == null) {
        return false;
    }
    logger.trace("***START SPEECH**** Player: '{}'", playerId);
    // get the current player state
    int playerVolume = player.getUnmuteVolume();
    boolean playerPowered = player.isPowered();
    boolean playerMuted = player.isMuted();
    Mode playerMode = player.getMode();
    int currNumTracks = player.getNumberPlaylistTracks();
    int currPlayingTime = player.getCurrentPlayingTime();
    int currPlaylistIndex = player.getCurrentPlaylistIndex();
    int currPlaylistShuffle = player.getCurrentPlaylistShuffle();
    int currPlaylistRepeat = player.getCurrentPlaylistRepeat();
    int newNumTracks = 0;
    logger.trace("Current Playing Mode '{}'", playerMode.toString());
    logger.trace("Current Volume '{}'", playerVolume);
    logger.trace("Current Num Playlist Tracks '{}'", currNumTracks);
    logger.trace("Current Playing Playlist Index '{}'", currPlaylistIndex);
    logger.trace("Current Playing Time '{}'", currPlayingTime);
    logger.trace("Current Shuffle Mode '{}'", currPlaylistShuffle);
    logger.trace("Current Repeat Mode '{}'", currPlaylistRepeat);
    // If Playing Pause player before adjusting volume!
    if (playerMode == Mode.play) {
        squeezeServer.pause(playerId);
    }
    // set the player ready to play this announcement
    if (playerMuted) {
        logger.trace("Setting player state: unmuted");
        squeezeServer.unMute(playerId);
    }
    if (volume != -1) {
        logger.trace("Setting player state: volume {}", volume);
        squeezeServer.setVolume(playerId, volume);
    }
    if (currPlaylistRepeat != 0) {
        squeezeServer.setRepeatMode(playerId, 0);
    }
    if (currPlaylistShuffle != 0) {
        squeezeServer.setShuffleMode(playerId, 0);
        currPlaylistIndex = 0;
        logger.trace("Shuffle Changed! Set Current Playing Index to 0");
    }
    // can only 'say' 100 chars at a time
    List<String> sentences = getSentences(message, squeezeServer.getTtsMaxSentenceLength());
    // send each sentence in turn
    for (String sentence : sentences) {
        logger.trace("Sending sentence to " + playerId + " (" + sentence + ")");
        String encodedSentence;
        try {
            encodedSentence = URLEncoder.encode(sentence, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.warn("Failed to encode sentence '" + sentence + "'. Skipping sentence.", e);
            continue;
        }
        encodedSentence = encodedSentence.replace("+", "%20");
        logger.trace("Encoded sentence " + encodedSentence);
        // build the URL to send to the Squeezebox to play
        String url = String.format(squeezeServer.getTtsUrl(), encodedSentence);
        // create an instance of our special listener so we can detect when the sentence is complete
        SqueezeboxSentenceListener listener = new SqueezeboxSentenceListener(playerId);
        squeezeServer.addPlayerEventListener(listener);
        // send the URL (this will power up the player and un-mute if necessary)
        logger.trace("Adding URL to current playlist '{}' to play", url);
        squeezeServer.addPlaylistItem(playerId, url);
        logger.trace("Sleeping for 1s for updated playlist to refresh", url);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            continue;
        }
        newNumTracks = player.getNumberPlaylistTracks();
        logger.trace("New Playlist Track Number: '{}'", newNumTracks);
        squeezeServer.playPlaylistItem(playerId, newNumTracks - 1);
        squeezeServer.play(playerId);
        // wait for this message to complete (timing out after 30s)
        int timeoutCount = 0;
        while (!listener.isFinished() && timeoutCount < 300) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                break;
            }
            timeoutCount++;
        }
        if (timeoutCount >= 200) {
            logger.warn("Sentence timed out while speaking!");
        }
        squeezeServer.stop(playerId);
        // clean up the listener
        squeezeServer.removePlayerEventListener(listener);
        listener = null;
        logger.trace("Done playing speech - restore state...");
    }
    logger.trace("Deleting Playlist Index: '{}'", newNumTracks - 1);
    squeezeServer.deletePlaylistItem(playerId, newNumTracks - 1);
    // restore the player volume before playback
    if (volume != -1) {
        logger.trace("Restoring player to previous state: volume {}", playerVolume);
        squeezeServer.setVolume(playerId, playerVolume);
    }
    if (playerMode != Mode.stop) {
        logger.trace("Restoring Playlist Index Number: '{}'", currPlaylistIndex);
        squeezeServer.playPlaylistItem(playerId, currPlaylistIndex);
        logger.trace("Restoring Playing Time : '{}'", currPlayingTime);
        squeezeServer.setPlayingTime(playerId, currPlayingTime);
    }
    // Must sleep 350ms before restoring previous playback state...
    try {
        Thread.sleep(350);
    } catch (InterruptedException e) {
    }
    // restore play mode state
    if (playerMode == Mode.play) {
        if (resumePlayback) {
            logger.trace("Restoring Playing Mode: '{}'", playerMode);
            squeezeServer.play(playerId);
        } else {
            logger.warn("NOT restoring Playing Mode: '{}' because resumePlayback is false", playerMode);
            squeezeServer.pause(playerId);
        }
    } else if (playerMode == Mode.pause) {
        squeezeServer.pause(playerId);
    } else {
        squeezeServer.stop(playerId);
    }
    logger.trace("Restoring player to previous state: shuffle {}", currPlaylistShuffle);
    squeezeServer.setShuffleMode(playerId, currPlaylistShuffle);
    logger.trace("Restoring player to previous state: repeat {}", currPlaylistRepeat);
    squeezeServer.setRepeatMode(playerId, currPlaylistRepeat);
    if (playerMuted) {
        logger.trace("Restoring player to previous state: muted");
        squeezeServer.mute(playerId);
    }
    if (!playerPowered) {
        logger.trace("Restoring player to previous state: off");
        squeezeServer.powerOff(playerId);
    }
    logger.trace("*****DONE SPEECH****** Player: '{}'", playerId);
    return true;
}
Also used : Mode(org.openhab.io.squeezeserver.SqueezePlayer.Mode) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SqueezePlayer(org.openhab.io.squeezeserver.SqueezePlayer) ActionDoc(org.openhab.core.scriptengine.action.ActionDoc)

Example 8 with ActionDoc

use of org.openhab.core.scriptengine.action.ActionDoc in project openhab1-addons by openhab.

the class CiscoSpark method sparkMessage.

/**
     * Sends a Message via Cisco Spark
     *
     * @param msgTxt the Message to send
     * @param roomId the Room to which to send
     *
     * @return <code>true</code>, if sending the message has been successful and
     *         <code>false</code> in all other cases.
     */
@ActionDoc(text = "Sends a Message via Cisco Spark", returns = "<code>true</code>, if sending the tweet has been successful and <code>false</code> in all other cases.")
public static boolean sparkMessage(@ParamDoc(name = "msgTxt", text = "the Message to send") String msgTxt, @ParamDoc(name = "roomId", text = "the Room to which to send") String roomId) {
    if (!CiscoSparkActionService.isProperlyConfigured) {
        logger.debug("Cisco Spark is not yet configured > execution aborted!");
        return false;
    }
    // Validate message
    if (msgTxt == null || "".equals(msgTxt)) {
        logger.warn("Message can't be empty");
        return false;
    }
    // Validate room id
    try {
        UUID.fromString(roomId);
    } catch (IllegalArgumentException e) {
        logger.warn("Room id is not a UUID");
        return false;
    }
    try {
        logger.debug("Creating message");
        // Create the message
        Message msg = new Message();
        msg.setRoomId(roomId);
        msg.setMarkdown(msgTxt);
        logger.debug("About to send message");
        // send the Message
        spark.messages().post(msg);
        logger.debug("Successfully sent Message '{}'", msg.getMarkdown());
        return true;
    } catch (SparkException se) {
        logger.warn("Failed to send message.", se);
        return false;
    } catch (Exception e) {
        logger.warn("Failed to send message!", e);
        return false;
    }
}
Also used : Message(com.ciscospark.Message) SparkException(com.ciscospark.SparkException) AddressException(javax.mail.internet.AddressException) SparkException(com.ciscospark.SparkException) ActionDoc(org.openhab.core.scriptengine.action.ActionDoc)

Example 9 with ActionDoc

use of org.openhab.core.scriptengine.action.ActionDoc in project openhab1-addons by openhab.

the class CiscoSpark method sparkPerson.

/**
     * Sends a Message to a Person via Cisco Spark
     *
     * @param msgTxt the Message to send
     * @param personEmail the email of the person to which to send
     *
     * @return <code>true</code>, if sending the message has been successful and
     *         <code>false</code> in all other cases.
     */
@ActionDoc(text = "Sends a Message via Cisco Spark", returns = "<code>true</code>, if sending the tweet has been successful and <code>false</code> in all other cases.")
public static boolean sparkPerson(@ParamDoc(name = "msgTxt", text = "the Message to send") String msgTxt, @ParamDoc(name = "personEmail", text = "the email of the person to which to send") String personEmail) {
    if (!CiscoSparkActionService.isProperlyConfigured) {
        logger.warn("Cisco Spark is not yet configured > execution aborted!");
        return false;
    }
    // Validate message
    if (msgTxt == null || "".equals(msgTxt)) {
        logger.warn("Message can't be empty");
        return false;
    }
    // Validate email
    try {
        InternetAddress email = new InternetAddress(personEmail);
        email.validate();
    } catch (AddressException e) {
        logger.warn("Email address is not valid");
        return false;
    }
    try {
        logger.debug("Creating message");
        // Create the message
        Message msg = new Message();
        msg.setToPersonEmail(personEmail);
        msg.setMarkdown(msgTxt);
        logger.debug("About to send message");
        // send the Message
        spark.messages().post(msg);
        logger.debug("Successfully sent Message '{}'", msg.getMarkdown());
        return true;
    } catch (SparkException se) {
        logger.warn("Failed to send message.", se);
        return false;
    } catch (Exception e) {
        logger.warn("Failed to send message!", e);
        return false;
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Message(com.ciscospark.Message) SparkException(com.ciscospark.SparkException) AddressException(javax.mail.internet.AddressException) AddressException(javax.mail.internet.AddressException) SparkException(com.ciscospark.SparkException) ActionDoc(org.openhab.core.scriptengine.action.ActionDoc)

Example 10 with ActionDoc

use of org.openhab.core.scriptengine.action.ActionDoc in project openhab1-addons by openhab.

the class EcobeeAction method ecobeeSetHold.

/**
     * The set hold function sets the thermostat into a hold with the specified temperature. Creates a hold for the
     * specified duration. Note that an event is created regardless of whether the program is in the same state as the
     * requested state.
     *
     * There is also support for creating a hold by passing a holdClimateRef request parameter/value pair to this
     * function (See Event). When an existing and valid Climate.climateRef value is passed to this function, the
     * coolHoldTemp, heatHoldTemp and fan mode from that Climate are used in the creation of the hold event. The values
     * from that Climate will take precedence over any coolHoldTemp, heatHoldTemp and fan mode parameters passed into
     * this function separately.
     *
     * To resume from a hold and return to the program, use the ResumeProgram function.
     *
     * @see <a href="https://www.ecobee.com/home/developer/api/documentation/v1/functions/SetHold.shtml">Set Hold</a>
     */
@ActionDoc(text = "The set hold function sets the thermostat into a hold with the specified event parameters.")
public static boolean ecobeeSetHold(@ParamDoc(name = "selection", text = "The thermostat selection to set hold.") String selection, @ParamDoc(name = "params", text = "The map of hold parameters.") Map<String, Object> params, @ParamDoc(name = "holdType", text = "(opt) The hold duration type. Valid values: dateTime, nextTransition, indefinite, holdHours.") String holdType, @ParamDoc(name = "holdHours", text = "(opt) The number of hours to hold for, used and required if holdType='holdHours'.") Number holdHours, @ParamDoc(name = "startDateTime", text = "(opt) The start date in thermostat time.") Date startDateTime, @ParamDoc(name = "endDateTime", text = "(opt) The end date in thermostat time.") Date endDateTime) {
    Event event = new Event();
    for (String key : params.keySet()) {
        Object value = params.get(key);
        switch(key) {
            case "isOccupied":
                event.setOccupied((Boolean) value);
                break;
            case "isCoolOff":
                event.setCoolOff((Boolean) value);
                break;
            case "isHeatOff":
                event.setHeatOff((Boolean) value);
                break;
            case "coolHoldTemp":
                event.setCoolHoldTemp(Temperature.fromLocalTemperature(new BigDecimal(value.toString())));
                break;
            case "heatHoldTemp":
                event.setHeatHoldTemp(Temperature.fromLocalTemperature(new BigDecimal(value.toString())));
                break;
            case "fan":
                event.setFan(FanMode.forValue((String) value));
                break;
            case "vent":
                event.setVent(VentilatorMode.forValue((String) value));
                break;
            case "ventilatorMinOnTime":
                event.setVentilatorMinOnTime((Integer) value);
                break;
            case "isOptional":
                event.setOptional((Boolean) value);
                break;
            case "isTemperatureRelative":
                event.setTemperatureRelative((Boolean) value);
                break;
            case "coolRelativeTemp":
                event.setCoolRelativeTemp(Temperature.fromLocalTemperature(new BigDecimal(value.toString())));
                break;
            case "heatRelativeTemp":
                event.setHeatRelativeTemp(Temperature.fromLocalTemperature(new BigDecimal(value.toString())));
                break;
            case "isTemperatureAbsolute":
                event.setTemperatureAbsolute((Boolean) value);
                break;
            case "fanMinOnTime":
                event.setFanMinOnTime((Integer) value);
                break;
            case "holdClimateRef":
                event.setHoldClimateRef((String) value);
                break;
            default:
                logger.warn("Unrecognized event field '{}' with value '{}' ignored.", key, value);
                break;
        }
    }
    SetHoldFunction function = new SetHoldFunction(event, (holdType == null) ? null : HoldType.forValue(holdType), (holdHours == null) ? null : holdHours.intValue(), startDateTime, endDateTime);
    return callEcobeeInternal(selection, function);
}
Also used : Event(org.openhab.binding.ecobee.messages.Thermostat.Event) SetHoldFunction(org.openhab.binding.ecobee.messages.SetHoldFunction) BigDecimal(java.math.BigDecimal) ActionDoc(org.openhab.core.scriptengine.action.ActionDoc)

Aggregations

ActionDoc (org.openhab.core.scriptengine.action.ActionDoc)14 Message (com.ciscospark.Message)2 SparkException (com.ciscospark.SparkException)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 IOException (java.io.IOException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 ImageInputStream (javax.imageio.stream.ImageInputStream)2 AddressException (javax.mail.internet.AddressException)2 DefaultHttpMethodRetryHandler (org.apache.commons.httpclient.DefaultHttpMethodRetryHandler)2 HttpClient (org.apache.commons.httpclient.HttpClient)2 HttpException (org.apache.commons.httpclient.HttpException)2 PostMethod (org.apache.commons.httpclient.methods.PostMethod)2 NotConnectedException (org.jivesoftware.smack.SmackException.NotConnectedException)2 XMPPException (org.jivesoftware.smack.XMPPException)2 MultiUserChat (org.jivesoftware.smackx.muc.MultiUserChat)2 TwitterException (twitter4j.TwitterException)2 InputStream (java.io.InputStream)1 BigDecimal (java.math.BigDecimal)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1