snippets

More or less useful code snippets
Log | Files | Refs

el-price-color.py (1561B)


      1 #!/usr/bin/python3
      2 
      3 # Fetch electricity prices from hvakosterstrommen.no
      4 # and set the color of a Philips Hue color bulb accordingly.
      5 
      6 import requests
      7 import sys
      8 from datetime import datetime
      9 from pathlib import Path
     10 from os import path
     11 import json
     12 import time
     13 
     14 BRIDGE = 'http://192.168.10.140'
     15 TARGET = 7
     16 username = open(f'{Path.home()}/.hue-user').read()
     17 
     18 # Electricity prices
     19 def fetch_prices(cache_file, dt):
     20     BASE_PATH = 'https://www.hvakosterstrommen.no'
     21     resp = requests.get(f'{BASE_PATH}/api/v1/prices/{dt.year}/{dt.strftime("%m-%d")}_NO1.json')
     22     with open(cache_file, 'w') as f:
     23         f.write(resp.text)
     24 
     25 dt = datetime.now()
     26 cache_file = f'/tmp/el-price-{dt.year}-{dt.month}-{dt.day}'
     27 if not path.exists(cache_file):
     28     fetch_prices(cache_file, dt)
     29 with open(cache_file) as f:
     30     prices = json.load(f)
     31 
     32 prices = [p['NOK_per_kWh'] for p in prices]
     33 avg = sum(prices)/len(prices)
     34 min_p = min(prices)
     35 max_p = max(prices)
     36 
     37 if len(sys.argv) > 2 and sys.argv[2] == 'day':
     38     hours_to_show = range(len(prices))
     39 else:
     40     hours_to_show = [dt.hour]
     41 
     42 # Lights
     43 for h in hours_to_show:
     44     # The values are chosen so that lowest price of day -> green and highest -> red.
     45     # (green=[0.30, 0.70], and red=[0.70, 0.30])
     46     off = 0.4 * (prices[h] - min_p) / (max_p - min_p)
     47     res = requests.put(f'{BRIDGE}/api/{username}/lights/{TARGET}/state', json={
     48         'on': True,
     49         'bri': int(254*int(sys.argv[1])/100),
     50         'xy': [0.3+off, 0.7-off],
     51         'transitiontime': 10 # centisec = 10 sec
     52     })
     53     print(res.content)
     54     time.sleep(1)