Updated 08/10/17: python scripts now with username and password for mqtt broker
Here is my attempt to use cheap sensors (like the ones you can get from here: http://camjam.me/?page_id=623 ) with Home Assistant.
I’m using the temperature, motion and light sensors.
- A DS18B20 temperature sensor ( https://www.adafruit.com/product/381 )
- A Cheap light dependent resistor ( https://www.modmypi.com/raspberry-pi/sensors-1061/lightcolour-1068/ldr-light-dependent-resistor )
- A cheap motion sensor ( https://thepihut.com/products/pir-motion-sensor-module )
I’ve got Home Assistant running on a Pi 3 and a Pi Zero on which I connected the sensors.
The goal is to send the sensor’s data from the pi zero thanks to python scripts to Home assistant through MQTT.
Installation of necessary packages on the Pi Zero (with the sensors):
sudo apt-get install python3 python3-pip
sudo pip3 install paho-mqtt
sudo pip3 install RPi.GPIO
1- Temperature Sensor
On Home Assistant:
Creation of the topic in sensors.yaml:
- platform: mqtt
state_topic: "home-assistant/firstfloor/temperature"
name: First Floor Temperature
unit_of_measurement: °C
On the Pi Zero:
Creation of the python script:
nano /home/pi/tempmqtt.py
#!/usr/bin/python3
# Import package
import os
import glob
import time
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
# Def
broker = "192.168.1.29"
state_topic = "home-assistant/firstfloor/temperature"
delay = 30
# Initialize the GPIO Pins
os.system('modprobe w1-gpio') # Turns on the GPIO module
os.system('modprobe w1-therm') # Turns on the Temperature module
# Finds the correct device file that holds the temperature data
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
# A function that reads the sensors data
def read_temp_raw():
f = open(device_file, 'r') # Opens the temperature device file
lines = f.readlines() # Returns the text
f.close()
return lines
# Convert the value of the sensor into a temperature
def read_temp():
lines = read_temp_raw() # Read the temperature 'device file'
# While the first line does not contain 'YES', wait for 0.2s
# and then read the device file again.
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw()
# Look for the position of the '=' in the second line of the
# device file.
equals_pos = lines[1].find('t=')
# If the '=' is found, convert the rest of the line after the
# '=' into degrees Celsius
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
return temp_c
############### MQTT section ##################
client = mqtt.Client()
client.username_pw_set("username", "password")
client.connect(broker)
client.loop_start()
while True:
print(read_temp())
time.sleep(1)
sensor_data = read_temp()
client.publish("home-assistant/firstfloor/temperature", str(sensor_data))
time.sleep(delay)
Give permissions to script:
sudo chmod +x /home/pi/tempmqtt.py
Autorun the python script on boot using systemd:
sudo nano /lib/systemd/system/tempmqtt.service
[Unit]
Description=Temp Mqtt Service
After=multi-user.target
[Service]
Type=idle
ExecStart=/usr/bin/python3 /home/pi/tempmqtt.py
[Install]
WantedBy=multi-user.target
Enable service and reload systemd:
sudo chmod 644 /lib/systemd/system/tempmqtt.service
sudo systemctl daemon-reload
sudo systemctl enable tempmqtt.service
2- Light Sensor
On Home Assistant:
Creation of the topic in sensors.yaml:
sensors.yaml
- platform: mqtt
state_topic: "home-assistant/firstfloor/light_intensity"
name: First Floor Light Intensity
On the Pi Zero:
Creation of the python script:
nano /home/pi/light.py
#!/usr/bin/python3
# Import package
import RPi.GPIO as GPIO
import time
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
# Def
broker = "192.168.1.29"
state_topic = "home-assistant/firstfloor/light_intensity"
delay = 30
# Import Libraries
import time
import RPi.GPIO as GPIO
# Set the GPIO Mode
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# A variable with the LDR reading pin number
PinLDR = 27
def ReadLDR():
LDRCount = 0 # Sets the count to 0
GPIO.setup(PinLDR, GPIO.OUT)
GPIO.output(PinLDR, GPIO.LOW)
time.sleep(0.1) # Drains all charge from the capacitor
GPIO.setup(PinLDR, GPIO.IN) # Sets the pin to be input
# While the input pin reads ‘off’ or Low, count
while (GPIO.input(PinLDR) == GPIO.LOW):
LDRCount += 1 # Add one to the counter
return LDRCount
############### MQTT section ##################
client = mqtt.Client()
client.username_pw_set("username", "password")
client.connect(broker)
client.loop_start()
while True:
print(ReadLDR())
time.sleep(1)
sensor_data = ReadLDR()
client.publish("home-assistant/firstfloor/light_intensity", str(sensor_data))
time.sleep(delay)
Give permissions to script:
sudo chmod +x /home/pi/light.py
Autorun the python script on boot using systemd:
sudo nano /lib/systemd/system/lightmqtt.service
[Unit]
Description=Light Mqtt Service
After=multi-user.target
[Service]
Type=idle
ExecStart=/usr/bin/python3 /home/pi/light.py
[Install]
WantedBy=multi-user.target
Enable service and reload systemd:
sudo chmod 644 /lib/systemd/system/lightmqtt.service
sudo systemctl daemon-reload
sudo systemctl enable lightmqtt.service
3- PIR Sensor
On Home Assistant:
Creation of the topic in sensors.yaml:
sensors.yaml
- platform: mqtt
state_topic: "home-assistant/firstfloor/motion"
name: First Floor Motion Detector
On the Pi Zero:
Creation of the python script:
nano /home/pi/pir.py
#!/usr/bin/python3
# Import required Python libraries
import time
import RPi.GPIO as GPIO
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
# Def
broker = "192.168.1.29"
state_topic = "home-assistant/firstfloor/motion"
auth = {
'username':"",
'password':""
}
# Use BCM GPIO references
# instead of physical pin numbers
GPIO.setmode(GPIO.BCM)
# Define GPIO to use on Pi
GPIO_PIR = 17
print ("PIR Module Holding Time Test (CTRL-C to exit)")
# Set pin as input
GPIO.setup(GPIO_PIR,GPIO.IN) # Echo
Current_State = 0
Previous_State = 0
#MQTT
client = mqtt.Client()
client.connect(broker)
client.loop_start()
try:
print ("Waiting for PIR to settle ...")
# Loop until PIR output is 0
while GPIO.input(GPIO_PIR)==1:
Current_State = 0
print ("Ready")
publish.single('home-assistant/firstfloor/motion', 'no motion', hostname=broker, auth=auth)
# Loop until users quits with CTRL-C
while True:
# Read PIR state
Current_State = GPIO.input(GPIO_PIR)
if Current_State==1 and Previous_State==0:
# PIR is triggered
start_time=time.time()
print ("Motion detected!")
publish.single('home-assistant/firstfloor/motion', 'motion detected', hostname=broker, auth=auth)
# Record previous state
Previous_State=1
elif Current_State==0 and Previous_State==1:
# PIR has returned to ready state
stop_time=time.time()
print ("Ready "),
elapsed_time=int(stop_time-start_time)
print ("(Elapsed time : " + str(elapsed_time) + " secs)")
Previous_State=0
publish.single('home-assistant/firstfloor/motion', 'no motion', hostname=broker, auth=auth)
except KeyboardInterrupt:
print ("Quit")
# Reset GPIO settings
GPIO.cleanup()
Give permissions to script:
sudo chmod +x /home/pi/pir.py
Autorun the python script on boot using systemd:
sudo nano /lib/systemd/system/pirmqtt.service
[Unit]
Description=PIR Mqtt Service
After=multi-user.target
[Service]
Type=idle
ExecStart=/usr/bin/python3 /home/pi/pir.py
[Install]
WantedBy=multi-user.target
Enable service and reload systemd:
sudo chmod 644 /lib/systemd/system/pirmqtt.service
sudo systemctl daemon-reload
sudo systemctl enable pirmqtt.service
Restart Home assistant and reboot the Pi Zero.
Et Voilà!
AUTOMATION EXAMPLES:
These ones are for my entrance hallway which is always a pretty dark room unfortunately:
The light is turned on automatically when motion is detected and the light sensor readings are above 1400 (which is when it is getting too dark for me)
- alias: Turn on hallway light when motion is detected
initial_state: True
trigger:
- platform: state
entity_id: sensor.hallway_motion_detector
to: 'motion detected'
condition:
condition: numeric_state
entity_id: sensor.hallway_light_intensity
above: 1400
action:
- service: light.turn_on
data:
entity_id: light.hue_white_lamp_1
- service: light.hue_activate_scene
data:
group_name: "Hallway"
scene_name: "Dimmed"
The light stays on as long as there is motion detected and then turned off after a few seconds.
- alias: Turn off hallway light when no motion is detected
initial_state: True
trigger:
- platform: state
entity_id: sensor.hallway_motion_detector
to: 'no motion'
for:
seconds: 17
condition:
condition: time
after: '08:00:00'
before: '20:30:00'
action:
service: light.turn_off
data:
entity_id: light.hue_white_lamp_1
Night mode:
- alias: Hallway light night mode
initial_state: True
trigger:
- platform: state
entity_id: sensor.hallway_motion_detector
to: 'no motion'
for:
seconds: 17
condition:
condition: time
after: '20:30:01'
before: '07:59:59'
action:
- service: light.turn_on
data:
entity_id: light.hue_white_lamp_1
- service: light.hue_activate_scene
data:
group_name: "Hallway"
scene_name: "Nightlight"
CONCLUSION:
The sensors are pretty reliable and i’ve been using them for my hallway for a few months now.
The only problem being the motion sensor which is really tricky to calibrate…