import java.util.Base64 import java.io.ByteArrayOutputStream import java.net.URL rule "Receive telegram" when Item TelegramBotMessage received update "take a snapshot" then val String ruleID = "Receive telegram" // code partially taken from https://community.openhab.org/t/oh-3-1-download-an-image-from-the-internet-and-save-into-a-item-of-the-type-image/125277/4 // unfortunately sendHttpGetRequest modifies the retrieved picture; a few bytes at beginning are cut off and a few are modified // this is why the download of the picture needs to be done by java methods logInfo( ruleID, "telegram message take a snopshot received" ) val telegramAction = getActions("telegram","telegram:telegramBot:Telegram_Bot_WS") if ( TelegramBotMessage.state.toString == "take a snapshot" ) { logInfo( ruleID, "will take a snopshot" ) val String pictureurl = "http://thecam.fritz.box/cgi-bin/api.cgi?cmd=Snap&channel=0&rs=wuuPhkmUCeI9WG7C&user=user&password=password" var userImageDataBytes = newByteArrayOfSize(0) try { // use the built in java URL class - pass it the url to download val url = new URL( pictureurl ) // create an output stream - we'll use it for building up our downloaded bytes val byteStreamOutput = new ByteArrayOutputStream() // open the url as a stream - aka - start getting stuff val inputStream = url.openStream() // n is a variable for tracking how much data we have read off the inputStream per loop (and how much we write to the output stream) var n = 0 // buffer is another byte array. basically we're using it as a fixed size copy byte array var buffer = newByteArrayOfSize(1024) do { // read from input stream (the data at the url) into buffer - and place how many bytes were read into n n = inputStream.read(buffer) if (n > 0) { // if we read more than 0 bytes - copy them from buffer into our output stream byteStreamOutput.write(buffer, 0, n) } } while (n > 0) // keep doing this until we don't have anything to read. userImageDataBytes = byteStreamOutput.toByteArray() // assemble all the bytes we wrote into an actual byte array } catch(Throwable t) { logError(ruleId, "Es ist ein Problem aufgetreten: " + t.toString) } logInfo( ruleID, "Bild Daten erhalten") // make a new RawType with the byte array and the mime type - the open hab type Image needs a raw type // my images are all jpeg - so this mime type is right for me // val rawType = new RawType(userImageDataBytes, "image/jpeg") val encoded = "data:image/jpg;base64," + Base64.getEncoder().encodeToString( userImageDataBytes ) telegramAction.sendTelegramPhoto( encoded , "sent from openHAB") } end