Reorganize util methods

This commit is contained in:
Paulus Schoutsen 2015-07-07 00:01:17 -07:00
parent b346f6e8ad
commit aeae7c2c02
9 changed files with 104 additions and 93 deletions

View File

@ -56,6 +56,7 @@ from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.entity import ToggleEntity
import homeassistant.util as util
import homeassistant.util.color as color_util
from homeassistant.const import (
STATE_ON, SERVICE_TURN_ON, SERVICE_TURN_OFF, ATTR_ENTITY_ID)
from homeassistant.components import group, discovery, wink, isy994
@ -237,9 +238,9 @@ def setup(hass, config):
if len(rgb_color) == 3:
params[ATTR_XY_COLOR] = \
util.color_RGB_to_xy(int(rgb_color[0]),
int(rgb_color[1]),
int(rgb_color[2]))
color_util.color_RGB_to_xy(int(rgb_color[0]),
int(rgb_color[1]),
int(rgb_color[2]))
except (TypeError, ValueError):
# TypeError if rgb_color is not iterable

View File

@ -11,7 +11,7 @@ from homeassistant import HomeAssistantError
from homeassistant.const import (
CONF_LATITUDE, CONF_LONGITUDE, CONF_TEMPERATURE_UNIT, CONF_NAME,
CONF_TIME_ZONE)
import homeassistant.util as util
import homeassistant.util.location as loc_util
_LOGGER = logging.getLogger(__name__)
@ -55,7 +55,7 @@ def create_default_config(config_dir, detect_location=True):
info = {attr: default for attr, default, *_ in DEFAULT_CONFIG}
location_info = detect_location and util.detect_location_info()
location_info = detect_location and loc_util.detect_location_info()
if location_info:
if location_info.use_fahrenheit:

View File

@ -16,8 +16,6 @@ import random
import string
from functools import wraps
import requests
# DEPRECATED AS OF 4/27/2015 - moved to homeassistant.util.dt package
# pylint: disable=unused-import
from .dt import ( # noqa
@ -64,46 +62,6 @@ def repr_helper(inp):
return str(inp)
# Taken from: http://www.cse.unr.edu/~quiroz/inc/colortransforms.py
# License: Code is given as is. Use at your own risk and discretion.
# pylint: disable=invalid-name
def color_RGB_to_xy(R, G, B):
""" Convert from RGB color to XY color. """
if R + G + B == 0:
return 0, 0
var_R = (R / 255.)
var_G = (G / 255.)
var_B = (B / 255.)
if var_R > 0.04045:
var_R = ((var_R + 0.055) / 1.055) ** 2.4
else:
var_R /= 12.92
if var_G > 0.04045:
var_G = ((var_G + 0.055) / 1.055) ** 2.4
else:
var_G /= 12.92
if var_B > 0.04045:
var_B = ((var_B + 0.055) / 1.055) ** 2.4
else:
var_B /= 12.92
var_R *= 100
var_G *= 100
var_B *= 100
# Observer. = 2 deg, Illuminant = D65
X = var_R * 0.4124 + var_G * 0.3576 + var_B * 0.1805
Y = var_R * 0.2126 + var_G * 0.7152 + var_B * 0.0722
Z = var_R * 0.0193 + var_G * 0.1192 + var_B * 0.9505
# Convert XYZ to xy, see CIE 1931 color space on wikipedia
return X / (X + Y + Z), Y / (X + Y + Z)
def convert(value, to_type, default=None):
""" Converts value to to_type, returns default if fails. """
try:
@ -154,32 +112,6 @@ def get_random_string(length=10):
return ''.join(generator.choice(source_chars) for _ in range(length))
LocationInfo = collections.namedtuple(
"LocationInfo",
['ip', 'country_code', 'country_name', 'region_code', 'region_name',
'city', 'zip_code', 'time_zone', 'latitude', 'longitude',
'use_fahrenheit'])
def detect_location_info():
""" Detect location information. """
try:
raw_info = requests.get(
'https://freegeoip.net/json/', timeout=5).json()
except requests.RequestException:
return
data = {key: raw_info.get(key) for key in LocationInfo._fields}
# From Wikipedia: Fahrenheit is used in the Bahamas, Belize,
# the Cayman Islands, Palau, and the United States and associated
# territories of American Samoa and the U.S. Virgin Islands
data['use_fahrenheit'] = data['country_code'] in (
'BS', 'BZ', 'KY', 'PW', 'US', 'AS', 'VI')
return LocationInfo(**data)
class OrderedEnum(enum.Enum):
""" Taken from Python 3.4.0 docs. """
# pylint: disable=no-init, too-few-public-methods

View File

@ -0,0 +1,41 @@
"""Color util methods."""
# Taken from: http://www.cse.unr.edu/~quiroz/inc/colortransforms.py
# License: Code is given as is. Use at your own risk and discretion.
# pylint: disable=invalid-name
def color_RGB_to_xy(R, G, B):
""" Convert from RGB color to XY color. """
if R + G + B == 0:
return 0, 0
var_R = (R / 255.)
var_G = (G / 255.)
var_B = (B / 255.)
if var_R > 0.04045:
var_R = ((var_R + 0.055) / 1.055) ** 2.4
else:
var_R /= 12.92
if var_G > 0.04045:
var_G = ((var_G + 0.055) / 1.055) ** 2.4
else:
var_G /= 12.92
if var_B > 0.04045:
var_B = ((var_B + 0.055) / 1.055) ** 2.4
else:
var_B /= 12.92
var_R *= 100
var_G *= 100
var_B *= 100
# Observer. = 2 deg, Illuminant = D65
X = var_R * 0.4124 + var_G * 0.3576 + var_B * 0.1805
Y = var_R * 0.2126 + var_G * 0.7152 + var_B * 0.0722
Z = var_R * 0.0193 + var_G * 0.1192 + var_B * 0.9505
# Convert XYZ to xy, see CIE 1931 color space on wikipedia
return X / (X + Y + Z), Y / (X + Y + Z)

View File

@ -0,0 +1,30 @@
"""Module with location helpers."""
import collections
import requests
LocationInfo = collections.namedtuple(
"LocationInfo",
['ip', 'country_code', 'country_name', 'region_code', 'region_name',
'city', 'zip_code', 'time_zone', 'latitude', 'longitude',
'use_fahrenheit'])
def detect_location_info():
""" Detect location information. """
try:
raw_info = requests.get(
'https://freegeoip.net/json/', timeout=5).json()
except requests.RequestException:
return
data = {key: raw_info.get(key) for key in LocationInfo._fields}
# From Wikipedia: Fahrenheit is used in the Bahamas, Belize,
# the Cayman Islands, Palau, and the United States and associated
# territories of American Samoa and the U.S. Virgin Islands
data['use_fahrenheit'] = data['country_code'] in (
'BS', 'BZ', 'KY', 'PW', 'US', 'AS', 'VI')
return LocationInfo(**data)

View File

@ -9,7 +9,7 @@ import unittest
import os
import homeassistant.loader as loader
import homeassistant.util as util
import homeassistant.util.color as color_util
from homeassistant.const import (
ATTR_ENTITY_ID, STATE_ON, STATE_OFF, CONF_PLATFORM,
SERVICE_TURN_ON, SERVICE_TURN_OFF)
@ -154,7 +154,7 @@ class TestLight(unittest.TestCase):
method, data = dev2.last_call('turn_on')
self.assertEqual(
{light.ATTR_XY_COLOR: util.color_RGB_to_xy(255, 255, 255)},
{light.ATTR_XY_COLOR: color_util.color_RGB_to_xy(255, 255, 255)},
data)
method, data = dev3.last_call('turn_on')

View File

@ -10,7 +10,7 @@ import unittest.mock as mock
import os
from homeassistant import DOMAIN, HomeAssistantError
import homeassistant.util as util
import homeassistant.util.location as location_util
import homeassistant.config as config_util
from homeassistant.const import (
CONF_LATITUDE, CONF_LONGITUDE, CONF_TEMPERATURE_UNIT, CONF_NAME,
@ -31,7 +31,7 @@ def create_file(path):
def mock_detect_location_info():
""" Mock implementation of util.detect_location_info. """
return util.LocationInfo(
return location_util.LocationInfo(
ip='1.1.1.1',
country_code='US',
country_name='United States',
@ -151,7 +151,7 @@ class TestConfig(unittest.TestCase):
def test_create_default_config_detect_location(self):
""" Test that detect location sets the correct config keys. """
with mock.patch('homeassistant.util.detect_location_info',
with mock.patch('homeassistant.util.location.detect_location_info',
mock_detect_location_info):
config_util.ensure_config_exists(CONFIG_DIR)

View File

@ -50,21 +50,6 @@ class TestUtil(unittest.TestCase):
self.assertEqual("12:00:00 09-07-1986",
util.repr_helper(datetime(1986, 7, 9, 12, 0, 0)))
# pylint: disable=invalid-name
def test_color_RGB_to_xy(self):
""" Test color_RGB_to_xy. """
self.assertEqual((0, 0), util.color_RGB_to_xy(0, 0, 0))
self.assertEqual((0.3127159072215825, 0.3290014805066623),
util.color_RGB_to_xy(255, 255, 255))
self.assertEqual((0.15001662234042554, 0.060006648936170214),
util.color_RGB_to_xy(0, 0, 255))
self.assertEqual((0.3, 0.6), util.color_RGB_to_xy(0, 255, 0))
self.assertEqual((0.6400744994567747, 0.3299705106316933),
util.color_RGB_to_xy(255, 0, 0))
def test_convert(self):
""" Test convert. """
self.assertEqual(5, util.convert("5", int))

22
tests/test_util_color.py Normal file
View File

@ -0,0 +1,22 @@
"""
Tests Home Assistant color util methods.
"""
import unittest
import homeassistant.util.color as color_util
class TestColorUtil(unittest.TestCase):
# pylint: disable=invalid-name
def test_color_RGB_to_xy(self):
""" Test color_RGB_to_xy. """
self.assertEqual((0, 0), color_util.color_RGB_to_xy(0, 0, 0))
self.assertEqual((0.3127159072215825, 0.3290014805066623),
color_util.color_RGB_to_xy(255, 255, 255))
self.assertEqual((0.15001662234042554, 0.060006648936170214),
color_util.color_RGB_to_xy(0, 0, 255))
self.assertEqual((0.3, 0.6), color_util.color_RGB_to_xy(0, 255, 0))
self.assertEqual((0.6400744994567747, 0.3299705106316933),
color_util.color_RGB_to_xy(255, 0, 0))