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.
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 IP_ADDRESS = '192.168.1.5' # 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 current_date_time=datetime.datetime.now() if current_date_time > sunset_date_time: print ("Lights On") brightness = 100 api(lights.light_control.set_dimmer(brightness)) else: print('Dont Turn ON')
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