Saturday 31 December 2016

PIR Raspberry PI sensor

Using a HC-SR505(generic PIR) module to detect motion for your home automastion is pretty straigh forward. For my setup i connected pin 2 to 5v pin 12 to signal pin 14 to GND
check this for pinlayout : https://kjetiliot.blogspot.no/p/raspberry-pi.html

Install dependencies:

  1. sudo apt-get install python-pip
  2. pip install paho-mqtt
Code:

Make the script executable

sudo chmod a+x filename

Add script to crontab

To start the script to automaticly run at at startup run the command : sudo crontab -e and add the following line(edit the path to fit your filename and path) : @reboot sudo python /home/pi/pirsensor.py & You can now reboot and check everything is working.
You can test that the pir is publishing correctly by subscribint to the mqtt topic you used in the pir sensor python script mosquitto_sub -v -t 'home/office/presence'

Parts:


Sunday 27 November 2016

Upgrade HASS RPAIO



sudo su -s /bin/bash hass (sudo)
source /srv/hass/hass_venv/bin/activate   (virtual enviroment)
pip3 install --upgrade homeassistant    (update)
exit ( return to user mode)
sudo systemctl restart home-assistant.service (restart HASS)

press ctrl + f5 to hard refresh your front end

ref: https://home-assistant.io/getting-started/installation-raspberry-pi-all-in-one/

sudo su -s /bin/bash homeassistant
source /srv/homeassistant/bin/activate
pip3 install --upgrade homeassistant
exit
sudo systemctl restart home-assistant@homeassistant

Monday 17 October 2016

Change color and dim the lights when playing on steam.

Dim my lights and set the hue to blue when i start a game in my steam account. This was a bit tricky because i have to make a fake sensor make a automation on the game value instead of the state=online. It works very fastm, max delay from i start or end a game is around 1 minutt.

Thursday 13 October 2016

Easy steam scraping with BeautifulSoup


I wanted to make a sensor for my steam account to use for future projects. After some googling i found BeautifulSoup. I framework to search with in text/html and xml. After some fiddling i got it working. To get steam working you need a working public profile page.

Install BeautifulSoup

sudo apg-get update -y && sudo atp-get upgrade -y && sudo apt-get install python-bs4 -y

Steam scraper

Will return blank if Im not playing anything or the name of the game if im playing.

Referance
https://www.crummy.com/software/BeautifulSoup/bs4/doc/

Raspian commandline network speedtest

To check internet speed on your raspberry do the following steps.


  • sudo apg-get update
  • sudo apt-get upgrade
  • sudo apt-get install python-pip
  • sudo easy_install speedtest-cli


Then simply type speedtest-cli and you will get something like this



Monday 10 October 2016

Smartify a simple heater


I needed to make a controller for my cheap and simple heater. It don't have any termostat and the setting are really strange and I could not find the correct settings, either too hot or too cold. I connected a 433 sender to a raspberry pi and made a flask web API. I then added a switch in Home Assistant that run a curl command to the other pi.

Hardware

Parts

Wiring

  • VCC -> pin 1 3,3Volt
  • Gnd -> pin 6 Gnd
  • Date/Data/signdal -> GPIO 17 (pin11)

Software


Flask code

 

Homeassistant


Referances

Wednesday 5 October 2016

NodeMCU Rgb controller


I made a easy IR controller for my generic RGB light strip. You can simply use curl(like http://IP-ADDR/rgbon) to turn on/off, dim the light or do some silly effects.

Arduino code:
Pinlayout:
Vin(USB 5v): Vcc
Gnd: Gnd
D3: Signal



Parts:
Home Assistant Implentation



Simple 3d printed prototype box with everything mounted

Sunday 28 August 2016

Raspberry Pi Backup

Here are the commands I use to preform a full backup of my raspi's. This will store the microsd card to either a usb stick(must be bigger than the microsd) and a backup to a share on my windows desktop.

USB Backup

sudo mkfs.vfat /dev/sda1 -n usbdrive
sudo mount /dev/sda1 /mnt
sudo chmod 755 /mnt
sudo dd if=/dev/mmcblk0p2 of=backupimage.img

Note: sda1 is the usb device , mmcblk0p2 is the memory card. Adjust acordenly.

Backup to Windows Pc


sudo mount -t cifs -o username=PI,password=PASSWORD//WINDOWSPC/share /mnt/smbbackup -o rw

sudo dd if=/dev/mmcblk0p2 of=/mnt/smbbackup/backupimage.img

 Note: mmcblk0p2 is the memory share

Save shutdown of raspberry pi

It's tempting to just pull the power when we move the pi but that will 
stress the SD card and eventually corrupt it.
so instead run the command.

sudo shutdown -h now

Friday 22 July 2016

Execute windows commands from Raspberry Pi

On the Windows pc

on an elivated command prompt run:
reg add "HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\system" /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f

on the Raspberry Pi

sudo apt-get update
sudo apt-get install git dh-autoreconf autoconf libc6 samba-dev libtalloc-dev libtevent-dev
gcc-mingw-w64
git clone git://git.code.sf.net/p/winexe/winexe-waf winexe-winexe-waf
cd ./winexe-winexe-waf/source
sudo ./waf configure
sudo ./waf
sudo mkdir /usr/winexe
sudo cp * /usr/winexe/
sudo /usr/winexe/winexe -U USERNAME%PASSWORD --runas=USERNAME%PASSWORD  //IP 'ipconfig'

 If succsessfull this will return the ip settings on your windows pc.

NB! add %% after each line if you make a handsoff script.



Thursday 14 July 2016

"Everything" APT-GET in one command

If you are tired of all the apt-get commands all the time do the following.

sudo nano apg-fresh.sh

sudo apt-get update && sudo apt-get upgrade -y && sudo apt-get autoremove && sudo apt-get autoclean

ctrl + o
ctrl + x

sudo chmod +x apg-fresh.sh

./apg-fresh.sh



This script will update, upgrade, autoremove and autoclean without any interaction. I.E keeping everything safe and clean.

Wednesday 18 May 2016

Running a looping python script automatically

To run a looping python script at startup after a reboot or halt. The best way is to put the script in the root crontab.

Write the following command  : sudo crontab -e 
Enter the follwing line @reboot python3 /usr/python/arduino.py &
My personal choise of editor is nano so you might select nano in the editor chooser window. ctrl + x + x saves and exit.



NB! the & at the end. and then you can reboot your linux boot to test that everything is working fine. Youy can read more about crontab here : http://www.computerhope.com/unix/ucrontab.htm

Monday 16 May 2016

Talking and reporting flower





I started this to learn to program arduino but it escaled pretty quicly.when i was finished with the project i had a flowersensor that reported to home assistant and i was able to chat with the data thru telegram.





Hardware I used:


Sensors:
  • Photo Resistor
  • LM35 Temp Sensor 
  • PIR Motion Sensor
  • DHT11 Temperature and Humidity Sensor
  • Soil humidity sensor
Just connect them as described in code and in the datasheets for the sensors.


Getting started with the electronics and the arduino:

#include "DHT.h"
#define DHTPIN 7    
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
int humidSensorPIN = 0;
int lightSensorPIN = 1;
int tempSensorPIN = 2;

void setup()
{
  Serial.begin(9600);
  dht.begin();
}

void loop()
{
  Serial.print("Soilhumidity:");
  Serial.println(analogRead(humidSensorPIN));
  Serial.print("Light:");
  Serial.println(analogRead(lightSensorPIN));
  int tempratureVal;
  int tempratureDat;
  tempratureVal = analogRead(tempSensorPIN);
  tempratureDat = (125 * tempratureVal) >> 8;
  Serial.print("TempratureRes:");
  Serial.println(tempratureDat);
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  float f = dht.readTemperature(true);
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  Serial.print("AirHumidity:");
  Serial.println(h);
  Serial.print("Temperature:");
  Serial.println(t);
  byte sensorPin = 6;
  byte state = digitalRead(sensorPin);
  Serial.print("Presence:");
  Serial.println(state);
  delay(5000);
}


This makes the aruino pump the following data out to the usb connector to the raspberry.

Light:137
TempratureRes:20
AirHumidity:23.00
Temperature:21.00
Presence:0
Soilhumidity:0


Now I connected it to the raspberry pi and wrote this python script. Notice you might change the usb serial port, if may vary from raspberry to raspberry. Mine is as you can see ttyACM0 The script reads the data and parse and send it to my mqtt server. this code use a bit of CPI so you might play around with the time.sleep(1) command to optimize for you system.

---- start arduino.py ----
#!/usr/bin/python
import time
import serial
import paho.mqtt.client as mqtt
connected = False
# Establish the connection on a specific port
ser = serial.Serial('/dev/ttyACM0', 9600)
mqttc = mqtt.Client()
mqttc.username_pw_set("mqtt", "mqtt")
mqttc.connect("localhost", 1883,60)
## loop until the arduino tells us it is ready
while not connected:
    serin = ser.read()
    connected = True

while 1:
    if ser.inWaiting():
        x=ser.readline().decode("utf-8")
        if str(x[:6])=="Light:":
            mqttc.publish("home/office/light",str(x[6:8]));
        elif x[:14]=="TempratureRes:":
            mqttc.publish("home/office/tempratureres",str(x[14:16]));
        elif x[:12]=="AirHumidity:":
            mqttc.publish("home/office/airhumidity",str(x[12:14]));
        elif x[:12]=="Temperature:":
            mqttc.publish("home/office/temperature",str(x[12:14]));
        elif x[:9]=="Presence:":
            mqttc.publish("home/office/presence",str(x[9:10]));
        elif x[:13]=="Soilhumidity:":
            mqttc.publish("home/office/soilhumidity",str(x[13:16]));
        else:
            print (x)

time.sleep(1)           
ser.close()

---- end arduino.py ----

Now I have the data in mqtt I can connect Home Assistant(HASS) to the read the data.  HASS is a really good framework to have for you iot projects as it's very flexible as you can see later. add the following lines in the configuration.yaml file to read the sensor data from mqtt.

mqtt:
  broker: 127.0.0.1
  port: 1883
  client_id: home-assistant-1
  keepalive: 60
  username: mqtt
  password: mqtt

sensor 3:
  platform: mqtt
  state_topic: "home/office/light"
  qos: 0
  name: "home/office/light"

sensor 4:
  platform: mqtt
  state_topic: "home/office/temperature"
  qos: 0
  name: "home/office/temperature"
  unit_of_measurement: "c"
 
sensor 5:
  platform: mqtt
  state_topic: "home/office/presence"
  qos: 0
  name: "home/office/presence"
 
sensor 6:
  platform: mqtt
  state_topic: "home/office/soilhumidity"
  qos: 0
  name: "home/office/soilhumidity"
 
sensor 7:
  platform: mqtt
  unit_of_measurement: "%"
  state_topic: "home/office/airhumidity"
  qos: 0
  name: "home/office/airhumidity"
 
sensor 8:
  unit_of_measurement: "c"
  platform: mqtt
  state_topic: "home/office/tempratureres"
  qos: 0
  name: "home/office/temperatureres"



Now you get something like this in HASS.
HASS now provides you a easy way to read JSON data from it. So i wrote a python script to read the data and talk to telegram for input and output.

--- start telegram.py ----
import time
import datetime
import telepot
import json
from requests import get
headers = {'x-ha-access': 'raspberry','content-type': 'application/json'}
def handle(msg):
    chat_id = msg['chat']['id']
    command = msg['text']    elif command == '/time':
        bot.sendMessage(chat_id, str(datetime.datetime.now()))
    elif command == '/how you doing?':
        url = 'http://localhost:8123/api/states/sensor.mqtt_sensor'
        response = get(url, headers=headers)
        tmps = str(response.text)
        d = json.loads(tmps)
        temp= d['state']
        bot.sendMessage(chat_id, 'I feel great! my temp is ' + temp + 'c')
bot = telepot.Bot('--- BOT API ---')
bot.message_loop(handle)
print ("I am listening ...")
while 1:
    time.sleep(10)
--- end telegram.py ----

Insert the BOT API code you get from bot father. Now you can start chatting with your new bot. It's easy to add new commands to the bot if you want to build more logic around it.



Disclamer: I'm not a python/c programmer so this code could/should be optimized.