Posts: 90
Joined: Fri Aug 03, 2018 12:39 pm

Tradfri light sunset switch on

Sat Dec 01, 2018 4:38 pm

After seeing the article in MagPi #76 about Ikea Tradfri lights, I thought I'd have a play. The Tradfri app doesn't have any functionality to switch a light on at sunset. Bit of Python later...

Code: Select all

from pytradfri import Gateway
from pytradfri.api.libcoap_api import APIFactory
from pytradfri.util import load_json, save_json
from time import sleep
import requests
import datetime
import time
import json

# Change this IP address to your gateway

# Make sure you're in the same directory as this file
CONFIG_FILE = 'tradfri_standalone_psk.conf'

# Load in the file, get our password for the gateway and create an API
#conf = load_json(CONFIG_FILE)
identity = 'xxxx'
psk = 'xxx'
api_factory = APIFactory(host=IP_ADDRESS, psk_id=identity, psk=psk)

# This section connects to the gateway and gets information on devices
api = api_factory.request
gateway = Gateway()
devices_command = gateway.get_devices()
devices_commands = api(devices_command)
devices = api(devices_commands)

# Create an array of objects that are lights
lights = [dev for dev in devices if dev.has_light_control]

url = "https://api.sunrise-sunset.org/json?lat=xxxx&lng=-xxxx"
response = requests.request("GET", url)
data=response.json() #Getting JSON Data
sunset_time_str=data['results']['sunset'] #Getting the Sunset Time

current_date=datetime.date.today() #Getting Today Date
sunset_time=datetime.datetime.strptime(sunset_time_str,'%I:%M:%S %p') #Converting String time to datetime object so that we can compare it current time
sunset_date_time=datetime.datetime.combine(current_date,sunset_time.time()) #Combine today date and time to single object


if current_date_time > sunset_date_time:
	print ("Lights On")
	brightness = 100

  print('Dont Turn ON')
This runs on a cron job on my Pi from 3.00 to 10.00 every 15 minutes. I struggled getting this bit working. I had to take the identity and PSK from the config file and hardcode them in here or I got a permission error - even though I tried all sorts with the permissions. I also had to put absolute paths in with the crontab or I got errors about modules missing. That's probably fixable another day but absolute paths works for the moment.

In my crontab, I have:

Code: Select all

*/15 15-22 * * * sudo -u pi /usr/bin/python3 /home/pi/libcoap/light.py > /dev/null 2>&1

Posts: 286
Joined: Fri Oct 11, 2013 12:28 pm

Re: Tradfri light sunset switch on

Sat Dec 01, 2018 7:32 pm

If you don't want to be reliant on a working internet connection, its possible to calculate sunrise/sunset yourself.

See: https://stackoverflow.com/questions/196 ... postgresql

I've attached the variant of the code from that link which I used.
(1.71 KiB) Downloaded 48 times

Return to “Automation, sensing and robotics”