Telegram bot next level

So after my first try with the telegram bot i wanted something more.
I wanted that the bot could be a little bit smarter en could give me some suggestions of devices if i don’t know the name exactly.

So i started again and created an dynamic telegram bot for domoticz using telepot.

To secure the bot so that not everyone could talk to it i build in an check for usernames which can be set in the telegram app.

What can it do?
Using this bot you can ask him for an switch/scene/group/utility switch. After the bot found the device it will ask you what you want to do with it (on,off)

If the device is an selector switch the bot will build special keyboard in telegram where you can find you’re selector options from domoticz.

But sometimes you don’t know the full name of the device or you forget an character, in that case the bot will look for devices that could be the device that you want and will come with suggestions.

So for example if you have 2 switches called livingroomSpeaker, livingroomLights

If you type livingroomspeaker to the bot it will come with the switch and asks you what you want to do (on or off)

but if you type living the bot will make an suggestions and asks if you meant one of the following devices and comes with livingroomSpeaker and livingroomLights.

you can find the code in my github repo:
Github Dynamic Telegram Bot

So an couple examples:
Switch
switches

Selector Switch
select switch

Suggestions
suggestions

Car Location
car location

Telegram Bot

So my doorbell was fixed, it creates an picture and sent in automatically to an telegram group where my newly created bot, the misses and i are members from.

I thought it was fun by creating an system/method to send posts to the telegram group so i wanted to see how far i could go with it.

At the moment the misses is 32 weeks pregnant so the words walking and fast cant be in the same sentence but our delivery guy doesn’t now that to well every morning.

So i thought what if i created an telegram which gives the misses (and me of course) the possibility to talk back or choose options so the delivery guy knows that someone is home but that it takes a moment before the door can be opened.

Easily enough there where plenty of examples on the net waiting to be used by an nerdy dad in progress ๐Ÿ™‚

I already had sound in the bathroom where the speakers where loud enough to be heared at the frontdoor so only 2 thing where necessary:

  1. An telegrambot which excepts commands from only the misses and me.
  2. An api which plays an mp3 on the bathroom speakers ๐Ÿ™‚

so first the bot, i just an standard example and added some features like an urlopener for the api but also for domoticz (if we wanted more commands in telegram it could be used for setting the light on and off in the living or something like that) and of course only the commands send by the misses and me must me executed.

After an hour i had an pretty simple telegram bot which runs on my main domoticz server which checks the telegram housegroup en sends an special keyboard/button to the enduser so we only had to push on an button to play an mp3 file in the bathroom ๐Ÿ™‚

The steps to create an bot with botfather and get the token is explained on the telegram site itself where you can find more documentation about the possibility’s:ย https://core.telegram.org/bots

then the bot itself, it needed to install an python module named telepot so use the command pip install telepot for it.

import telepot
import urllib2
from telepot.namedtuple import ReplyKeyboardMarkup

def handle(msg):
chat_id = msg['chat']['id']
command = msg['text']
user = msg['from']['username']

markup = ReplyKeyboardMarkup(keyboard=[['Doorbell 1 moment','Doorbell not home'],
['Dog', 'surprise', 'Firework']],
one_time_keyboard=False)
print 'Got command: %s' % command
unames = ['user 1', 'user2', 'user3']
url = 'http://192.168.1.2:8080' # url of domoticz
telbotApi = 'ip adres of the api server'
run = False
if user.lower() in unames:
if command.lower() == '/start':
bot.sendMessage(chat_id, 'What can I do for you?', reply_markup=markup)
if command.lower() == 'doorbell 1 moment':
url = 'http://' + telbotApi + '/speak?id=1'
run = True
elif command.lower() =='doorbell not home':
url = 'http://' + telbotApi + '/speak?id=2'
run = True
elif command.lower() == 'dog':
url = 'http://' + telbotApi + '/speak?id=3'
run = True
elif command.lower() == 'surprise':
url = 'http://' + telbotApi + '/speak?id=4'
run = True
elif command.lower() == 'firework':
url = 'http://' + telbotApi + '/speak?id=5'
run = True
elif command.lower() =='kitchenled purple':
url += '/json.htm?type=command¶m=switchlight&idx=245&switchcmd=Set%20Level&level=50'
run = True
elif command.lower() =='kitchenled off':
url += '/json.htm?type=command¶m=switchlight&idx=245&switchcmd=Set%20Level&level=0'
run = True
elif command.lower() =='kitchenled red':
url += '/json.htm?type=command¶m=switchlight&idx=245&switchcmd=Set%20Level&level=10'
run = True
if run:
urllib2.urlopen(url)

bot = telepot.Bot('bot token in here')
bot.message_loop(handle)
print 'I am listening...'

while 1:
time.sleep(10)

So this script only needs 3 things for it to work.

  1. an bot token in the line: telepot.Bot(‘bot token in here’)
  2. set the url and telbotApi address


after that it can run in the background and it will give you an keyboard button markup with 2 lines:

  1. First line is doorbell 1 moment and doorbell not home
  2. Second line gives you some fun options, Dog, Surprise and Firework (holidays are comming ๐Ÿ™‚ )

After checking that the script was working like it supposed to i went to create an simple small api which plays an mp3 file with the name of the id which was given by the telegramBot.

On the raspberry in the bathroom i created an folder api which included 1 subfolder “files” i wasn’t pleased with the tts (Text to Speak) options for the dutch language so i thought i will create/use mp3 files which then can be played using the api.
So i created some mp3 files and of course for the upcomming new years events some firework audio and an loud dog just because it can.
after changing the names of the mp3’s to 1.mp3, 2.mp3 and so on i started by creating the simple api.


from flask import Flask
from flask import request
import subprocess
app = Flask(__name__)

def play_mp3(path):
subprocess.Popen(['mpg123', '-q', path]).wait()

@app.route('/')
def index():
return 'doorbell api'

@app.route('/speak')
def speak():
_par = str(request.args.get('id'))
try:
play_mp3('/var/scripts/api/files/' + _par + '.mp3')
except:
return 'error playing file'
return _par

if __name__ == '__main__':
app.run(host='0.0.0.0',port=80, debug=True)

for this to work you need to install a couple of things on the raspberry:

sudo apt-get install mpg123
sudo pip install flask

after running this it will wait for an url with the following parameters: ‘/speak?id=’ and the id of the mp3 file you want to play.
i start the api by adding the following line to bottom of /etc/rc.local before exit 0

python /path/to/api.py &

and voila it works when the system reboots.
It was fun creating this and it works like an charm so i am thinking to explore more things on telegram to combine it with domoticz or an babyroom ๐Ÿ™‚

The python files and mp3 samples used in this project can be downloaded using the following link if you are interested.
TelegramBotDoorbell

Domoticz MPD Airplay solution

So its been a while again but i wanted to write something about my audio solution so i can control multiple speakers using domoticz and could select on which speakers i wanted my music played and even multiple rooms with the same music.

When i was searching on the web i found the forked-daapd solution which includes an Itunes server and MPD possibility’s.

No difficult at all you just install the solution and make some changes to the config so the server can find you’re music files and you are up and running.

To find an good iphone or android app is still difficult for me because on iphone i use the MPoD app but it doesn’t work all the time and on android i use the app MPDroid which is actually more stable for me.

So i had some old pc speakers which i didn’t used for an long time but it was perfect for testing and even the bathroom.

The thing i had to do was to make sure that the speakers could get music using the airplay protocol. Also there where several sollutions for on the internet so i used a couple of Raspberry Pi Zero’s and added the packages for the airplay protocol to it.

After that yes my forked-daapd server could find the speakers as outputs and i could select them.

Then the interesting part for me, i wanted that my domoticz server could automatically detect an new airplay device and add it to the hardware audio_devices.

So i created an python script which logs on the forked-daapd mpd server and checks the output devices which it compares to the domoticz audio_devices hardware.

this is the getAudioSpeakers.py in my github page.
https://github.com/squandor/DomoticzTools

This script does an couple of things:

  • It checks if the audio device which he found in the MPD server also exists in Domoticz, does it not exist that it will create an device with an On and Off action and an nice audio icon for it of course ๐Ÿ™‚ย 
  • but it also checks and controls the Volume which has been set in the app to add it to domoticz

That was the first script but the problem was it was in 1 direction. if something changes on the forked-daapd server it will synchronize to domoticz. But i wanted that the server also changes when i select an audio device in domoticz.

the second script controls that one, it is also the script which will be used in the on/off action for the device:

ControlAudio.py:

  • Its an simple script which takes parameters and changes the values on the mpd server.

#!/usr/bin/python
from mpd import MPDClient
import mpd
import random
import sys

def createClient():
client = MPDClient()
client.timeout = 10
client.connect(“192.168.1.145”, 6600)
return client

def stopClient(client):
client.clear()
client.stop()

name = sys.argv[1]
command = sys.argv[2]

client = createClient()
audioids = client.outputs()
for i in audioids:
if i[‘outputname’] == name:
id = i[‘outputid’]
if command == “1”:
client.enableoutput(id)
if command == “0”:
client.disableoutput(id)

But to let it work with domoticz i needed an simple step before this with an shell script which calls the controlAudio.py script…

ControlAudio.sh:
#!/bin/bash
/home/pi/domoticz/scripts/$1 $2 $3

so using this procedure the getAudioSpeakers.py will create an audio speaker device with for example an on action where Woonkamer is the airplay device name and 1 the on value:
script:///home/pi/domoticz/scripts/controlAudio.sh controlAudio.py Woonkamer 1

then i added an cron job which will run the getAudioSpeakers.py every 5 minutes.

The only thing needed now was the volume in domoticz. for this i created an volume device under the audio_devices hardware.

After that i created an lua script which runs when the volume is changed:

So if i want an new set of speakers in an room i make sure there is an airplay protocol in the speakers or i add an raspberry zero to it and it will be automatically added to domoticz and callable using the python scripts ๐Ÿ™‚

I’ve added all the scripts to my github page under MPD
https://github.com/squandor/DomoticzTools

happy days! ๐Ÿ™‚

 

 

RGB Led Strip

So i have a couple of raspberry pi’s running in my house so i can control my thermostat, audio, lights and hoses for the garden but i wanted to change my kitchen a little and i saw some kitchens on the internet with lights in the bottom of the whole kitchen.

I thought hmm could it be possible, so i started to search on the web if other people tried to control an led strip.. duhh so many people did it but an specific instruction was a little bit difficult to find.

After a while i did find enough instructions so i made an list with the hardware i needed to control an rgb led strip and the supply’s to install it in the kitchen.

So the list was:

  • RGB ledstrip, i didn’t want to spend a lot of money because i haven’t worked with it so i could wreck it the first time ๐Ÿ™‚ so i bought this one: Renkforce 5MAC862W ย for โ‚ฌ 17,99
  • Then i needed some transistors, for the sake of safety that if i wreck an transistor and cant keep trying to control the led strip i bought 40 of them:ย Transistor TIP120STM TO220 for โ‚ฌ 0,28 a piece
  • Raspberry pi Zero
  • Microsd card
  • Breadboard
  • Some Male Female jumper cables, just enough to connect everything. i bought enough last year on AliExpress so no worry’s here.
  • Cable tray 2.5 m
  • UTP Cable, 2 m

To install the led strip in the kitchen i bought an simple cable tray of 2.5 ย meters, we will use both sites of the tray because we don’t want the ledstrip closed inside the tray but the tray will hold the ledstrip in one line and displays it nicely on the ground ๐Ÿ™‚

So the next friday everything was delivered at home so i started by connecting the led strip to the raspberry pi using the breadboard, jumpercables and the transistors.

i used the instructions on: http://dordnung.de/raspberrypi-ledstrip/ย using the following scheme’s

 

for the easy modus i also added an push button to the breadboard so i could test my api and ledstrip. To simple add an button just have 1 pin added to ground and the other to an bcm gpio pin.

When i was done with the instructions i tried the example script and you know what the led strip wasn’t working… After an hour looking at a simple 4 line script to turn the led strip on and checking the breadboard again and again i was sick of it and begun to mess around with the led strip. apparently the rgb connections where different than the led strip itself say’d so my + was on an other pin and my r and b where switched…. strange that they wrote it down differently on the led itself but pff i was happy that it was working ๐Ÿ™‚ !!

 

So the led strip was working and i could control the colors, i was so happy until i thought about the installation in the kitchen. How could i connect the led strip to the raspberry without seeing any awful cables or jumper wires. After some thinking i ย thought an UTP cable has enough connectors in it maybe it could work so i tried that and yes after some soldering and connecting the right cables to each other it was working ๐Ÿ™‚ so now the final step, installation in the kitchen itself.

First a nice place for the raspberry and the power for the led strip and the raspberry itself. It seemed that i was lucky because an kitchen tray wasn’t as high as it could be so i’ve had enough space in an tray ๐Ÿ™‚

Than it was just installing the cable tray beneath the kitchen and put the led strip in it

First i tried a couple of meters to look how it was, and actually it wasn’t to bad. so i went on with the rest of it and tadaa.

Now i needed to write the api for it so i could control the led strip using my domoticz installation.

1,2,3 and poof i’ve had an simple api which controls the transistors so i could control the colors using an selector switch in domoticz.

But i wasn’t ready. my purpose of these actions is at an moment in the future my house can think a little bit for itself. I remembered what an friend of my has in his own house. And lamp or led strip that colors blue when it starts to rain within 20 min.

I thought you now what, i will do that as wel. so i’ve searched the domoticz sites for the buienradar lua script and found the is it gonna rain wiki:ย https://www.domoticz.com/wiki/Is_it_gonna_rain

Here i found the script for the rain and created an extra lua script which checks if the switch rain is on it will change the kitchen led strip to Blue and saves the old value to an user variable.

The reason for this was that if the rain switch went off that the kitchen led strip will change into his old value again.

and you know what, for the first time it worked at once ๐Ÿ˜€

so another project done and that in one weekend of work ๐Ÿ™‚ up to the next one