├── info.md
├── equation.png
├── hacs.json
├── index_demo.png
├── default_settings.png
├── apps
└── update_lights
│ ├── color_to_kelvin.py
│ ├── update_lights.py
│ └── color.py
├── README.md
└── LICENSE
/info.md:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/equation.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/haberda/Periodic-lights/HEAD/equation.png
--------------------------------------------------------------------------------
/hacs.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Periodic lights",
3 | "render_readme": "True"
4 | }
5 |
--------------------------------------------------------------------------------
/index_demo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/haberda/Periodic-lights/HEAD/index_demo.png
--------------------------------------------------------------------------------
/default_settings.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/haberda/Periodic-lights/HEAD/default_settings.png
--------------------------------------------------------------------------------
/apps/update_lights/color_to_kelvin.py:
--------------------------------------------------------------------------------
1 | """Color to kelvin methods."""
2 | KELVIN_TABLE = {
3 | 1000: [255, 56, 0],
4 | 1100: [255, 71, 0],
5 | 1200: [255, 83, 0],
6 | 1300: [255, 93, 0],
7 | 1400: [255, 101, 0],
8 | 1500: [255, 109, 0],
9 | 1600: [255, 115, 0],
10 | 1700: [255, 121, 0],
11 | 1800: [255, 126, 0],
12 | 1900: [255, 131, 0],
13 | 2000: [255, 138, 18],
14 | 2100: [255, 142, 33],
15 | 2200: [255, 147, 44],
16 | 2300: [255, 152, 54],
17 | 2400: [255, 157, 63],
18 | 2500: [255, 161, 72],
19 | 2600: [255, 165, 79],
20 | 2700: [255, 169, 87],
21 | 2800: [255, 173, 94],
22 | 2900: [255, 177, 101],
23 | 3000: [255, 180, 107],
24 | 3100: [255, 184, 114],
25 | 3200: [255, 187, 120],
26 | 3300: [255, 190, 126],
27 | 3400: [255, 193, 132],
28 | 3500: [255, 196, 137],
29 | 3600: [255, 199, 143],
30 | 3700: [255, 201, 148],
31 | 3800: [255, 204, 153],
32 | 3900: [255, 206, 159],
33 | 4000: [255, 209, 163],
34 | 4100: [255, 211, 168],
35 | 4200: [255, 213, 173],
36 | 4300: [255, 215, 177],
37 | 4400: [255, 217, 182],
38 | 4500: [255, 219, 186],
39 | 4600: [255, 221, 190],
40 | 4700: [255, 223, 194],
41 | 4800: [255, 225, 198],
42 | 4900: [255, 227, 202],
43 | 5000: [255, 228, 206],
44 | 5100: [255, 230, 210],
45 | 5200: [255, 232, 213],
46 | 5300: [255, 233, 217],
47 | 5400: [255, 235, 220],
48 | 5500: [255, 236, 224],
49 | 5600: [255, 238, 227],
50 | 5700: [255, 239, 230],
51 | 5800: [255, 240, 233],
52 | 5900: [255, 242, 236],
53 | 6000: [255, 243, 239],
54 | 6100: [255, 244, 242],
55 | 6200: [255, 245, 245],
56 | 6300: [255, 246, 247],
57 | 6400: [255, 248, 251],
58 | 6500: [255, 249, 253],
59 | 6600: [254, 249, 255],
60 | 6700: [252, 247, 255],
61 | 6800: [249, 246, 255],
62 | 6900: [247, 245, 255],
63 | 7000: [245, 243, 255],
64 | 7100: [243, 242, 255],
65 | 7200: [240, 241, 255],
66 | 7300: [239, 240, 255],
67 | 7400: [237, 239, 255],
68 | 7500: [235, 238, 255],
69 | 7600: [233, 237, 255],
70 | 7700: [231, 236, 255],
71 | 7800: [230, 235, 255],
72 | 7900: [228, 234, 255],
73 | 8000: [227, 233, 255],
74 | 8100: [225, 232, 255],
75 | 8200: [224, 231, 255],
76 | 8300: [222, 230, 255],
77 | 8400: [221, 230, 255],
78 | 8500: [220, 229, 255],
79 | 8600: [218, 229, 255],
80 | 8700: [217, 227, 255],
81 | 8800: [216, 227, 255],
82 | 8900: [215, 226, 255],
83 | 9000: [214, 225, 255],
84 | 9100: [212, 225, 255],
85 | 9200: [211, 224, 255],
86 | 9300: [210, 223, 255],
87 | 9400: [209, 223, 255],
88 | 9500: [208, 222, 255],
89 | 9600: [207, 221, 255],
90 | 9700: [207, 221, 255],
91 | 9800: [206, 220, 255],
92 | 9900: [205, 220, 255],
93 | 10000: [207, 218, 255],
94 | 10100: [207, 218, 255],
95 | 10200: [206, 217, 255],
96 | 10300: [205, 217, 255],
97 | 10400: [204, 216, 255],
98 | 10500: [204, 216, 255],
99 | 10600: [203, 215, 255],
100 | 10700: [202, 215, 255],
101 | 10800: [202, 214, 255],
102 | 10900: [201, 214, 255],
103 | 11000: [200, 213, 255],
104 | 11100: [200, 213, 255],
105 | 11200: [199, 212, 255],
106 | 11300: [198, 212, 255],
107 | 11400: [198, 212, 255],
108 | 11500: [197, 211, 255],
109 | 11600: [197, 211, 255],
110 | 11700: [197, 210, 255],
111 | 11800: [196, 210, 255],
112 | 11900: [195, 210, 255],
113 | 12000: [195, 209, 255]}
114 |
115 | KELVIN_LIST = [1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900,
116 | 2000, 2100, 2200, 2300, 2400, 2500, 2600, 2700, 2800, 2900,
117 | 3000, 3100, 3200, 3300, 3400, 3500, 3600, 3700, 3800, 3900,
118 | 4000, 4100, 4200, 4300, 4400, 4500, 4600, 4700, 4800, 4900,
119 | 5000, 5100, 5200, 5300, 5400, 5500, 5600, 5700, 5800, 5900,
120 | 6000, 6100, 6200, 6300, 6400, 6500, 6600, 6700, 6800, 6900,
121 | 7000, 7100, 7200, 7300, 7400, 7500, 7600, 7700, 7800, 7900,
122 | 8000, 8100, 8200, 8300, 8400, 8500, 8600, 8700, 8800, 8900,
123 | 9000, 9100, 9200, 9300, 9400, 9500, 9600, 9700, 9800, 9900,
124 | 10000, 10100, 10200, 10300, 10400, 10500, 10600, 10700, 10800, 10900,
125 | 11000, 11100, 11200, 11300, 11400, 11500, 11600, 11700, 11800, 11900,
126 | 12000]
127 |
128 | def color_RGB_to_kelvin (RGB=[255,255,255]):
129 | """ Find the best match between current rgb color and color temperature.
130 | By definition it cannot be an exact match. """
131 | min_list = []
132 | for i in range(0, len(KELVIN_LIST)):
133 | tmp = [x1-x2 for x1,x2 in zip(RGB,KELVIN_TABLE[KELVIN_LIST[i]])]
134 | res = [abs(ele) for ele in tmp]
135 | min_list.append(res)
136 | minrgb = min_list.index(min(min_list))
137 | return KELVIN_LIST[minrgb]
138 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Periodic lights
2 |
3 | Note this repository is archived, please use the [custom integration](https://github.com/haberda/periodic-lights-integration).
4 |
5 | ## Introduction
6 |
7 | Periodic lights (formally update lights) is an automatic light brightness and color temperature adjustment tool for AppDaemon. This code will act on a provided list of lights to keep them in sync with the current light parameters. What makes this app different from others (namely custom components Circadian Lighting, Adaptive Lighting or the built-in Flux component) is the implementation of brightness change thresholds; this allows for manual adjustment of a light outside of the threshold range that the app will then ignore until and unless the light is either manually adjusted to the current threshold range, or the light is toggled. The brightness/color temperature is calculated by determining how far from the middle point of the start and end time the current time is. All light types can be mixed (e.g. you can have a list with RGB, color temp, and brightness only lights together). There are numerous options that can be configured to suit your needs.
8 |
9 | ## Options
10 | ---
11 |
12 | Key | Required | Description | Default | Unit
13 | ------------ | ------------- | ------------- | ------------- | -------------
14 | entities | True | List of lights | None | List
15 | run_every | False | Time interval in seconds to run the code, set to 0 to disable time-based updates | 180 | Seconds
16 | event_subscription | False | Home-assistant event to listen for, forces lights to update, can take transition and threshold variables | None | string
17 | start_time | False | Time in format 'HH:MM:SS' to start; also can be 'sunset - HH:MM:SS' | sunset | Time
18 | end_time | False | Time in format 'HH:MM:SS' to start; also can be 'sunrise - HH:MM:SS' | sunrise | Time
19 | start_index | False | With this option you can push the middle point left or right and increase or decrease the brightness change gradient and point of minimum brightness/temp, takes time the same was as start/end times | None | Time
20 | end_index | False | Same as start index but changes the end time rather than start both can be configured to have 2 minimum brightness points | None | Time
21 | brightness_threshold | False | Residual threshold between calculated brightness and current brightness if residual > threshold no change | 255 or 100 | Bit or percent
22 | brightness_unit | False | percent or bit | bit | None
23 | max_brightness_level | False | Max brightness level | 255 or 100 | Bit or percent
24 | min_brightness_level | False | Min brightness level | 3 or 1 | Bit or percent
25 | color_temp_unit | False | Kelvin or mired color temp unit | kelvin |
26 | color_temp_max | False | Maximum color temp | 4000 | kelvin
27 | color_temp_min | False | Min color temp | 2200 | kelvin
28 | perfer_rgb | False | Prefer RGB or xy over color temperature | False | Boolean
29 | disable_entity | False | List of entities that when active disable the functionality of this code. Can take a comma separated condition rather than disable condition key below (e.g. input_boolean.party_mode,on) | None | List
30 | disable_condition | False | Override default condition check for disable_entity | on, True, or Home | Boolean or string in list form
31 | sleep_entity | False | List of entities that track whether a 'sleep mode' has been enabled this immediatly brings lights to the lowest brightness and color temp defined. Can take a comma separated condition rather than disable condition key below (e.g. input_boolean.sleep_mode,on) | None | List
32 | sleep_condition | False | Override default condition check for sleep_entity | on, True, or Home | Boolean or string in list form
33 | sleep_color_temp | False | Color temperature when sleep_mode is True | None | Color temperature in mired or kelvin
34 | sleep_color | False | Color in string format (e.g. 'red') | red | String
35 | color_unit | False | Color unit if you intend to use XY colors (set to 'xy' if you intend to use xy color) | None | String
36 | color_max | False | Color value for xy max (required if using xy colors) | None | list
37 | color_min | False | Color value for xy min (required if using xy colors) | None | list
38 | sleep_xy_color | False | Color value for xy sleep mode | None | list
39 | transition | False | Light transition time in seconds | 5 | Seconds
40 | companion_script | False | Script to execute before changing lights, useful to force Zwave lights to update state | None |
41 | sensor_log | False | Creates a sensor to track the dimming percentage, mostly for diagnostic purposes, format: sensor.my_sensor | None |
42 | sensor_only | False | Only creates a sensor that tracks the brightness and color temperature, will not adjust lights. | False | Boolean
43 | watch_light_state | False | Whether or not to watch individual lights and adjust them when they are turned on | True | Boolean
44 | keep_lights_on | False | Forces the light to turn on, in other words ignores that it is off | False | Boolean
45 | start_lights_on | False | Turn on the lights at the start time | False | Boolean
46 | stop_lights_off | False | Turn off the lights at the stop time | False | Boolean
47 |
48 | AppDaemon constraints can be used as well, see AppDaemon API Docs https://appdaemon.readthedocs.io/en/latest/APPGUIDE.html#callback-constraints
49 |
50 | ## Algorithm explanation
51 |
52 | This app works by calculating the time that occurs exactly in the middle of the start_time and end_time. The current time is then compared to the middle point to determine at what point in the day the current time is relative to the middle point. This is then fit to a sin function (running from 0 to pi in the x direction). This returns a percentage, if your defined light brightness is from 0-100 then the direct reading from the sin function will be used. In practice this is calculated by:
53 |
54 | 
55 |
56 | The color temperature is calculated the same way as the brightness.
57 |
58 | The values are updated 24 hours a day, therefore, setting the run_every variable to a very short time will not result in the lights updating faster. There are 256 brightness bit values, assuming the maximum is set to 100% brightness and the minimum is set to 0%. This means there are only 512 brightness steps that can be taken in 1 day, or in other words, about 1 every 3 minutes. Therefore, in terms of brightness, the app should be set to update about once every 3 minutes. A similar calculation can be made for color temperature, assuming the default range in mired. Using the default settings, the brightness of the lights would look like this over the course of a day:
59 |
60 | 
61 |
62 | Both brightness and color temperature are subject to the ranges provided by the user or the default values described above.
63 |
64 | ## Understanding start/end index
65 |
66 | This is a fine tuning feature that allows for the lights to be dimmer or brighter close to the start or end than they otherwise would by extending the middle-point. Using these effectively creates two middle points during the start and end window. A start_index value effects the result after the middle point, an end_index effects the result before the middle-point. If the lights are watched closely one would observe the lights dim to the lowest point from the start->middlepoint1 then hold at the minimum between middlepoint1->middlepoint2; after middlepoint2 the lights will become brighter as usual.
67 |
68 | This should be tested by setting up a sensor only configuration and observing the behavior to see if the desired result is achieved.
69 |
70 | This is an example of the behavior of the light brighness with sunset->sunrise start and end times and the index settings below:
71 |
72 | 
73 |
74 | ```
75 | start_index: sunset + 02:00:00
76 | end_index: sunrise - 02:00:00
77 | ```
78 | Note the step change in brightness at the start and end times as the code switches from one mid-point to another, and the two hour minimum point in the middle of the night. The brightness step change should be accounted for in your threshold settings if you want the lights that are on to smoothly transition at that point. In the case of this example the step change is about 15%, therefore a brightness threshold above 15% should be sufficient to account for this change.
79 |
80 | ## xy color configuration
81 |
82 | xy colors can be set in place of color temperature. This is set as a list like in the example below. Refer to the xy color chart below to choose your color range:
83 |
84 | 
85 |
86 | ## Sensor only configuration
87 |
88 | The sensor only option allows you to create a sensor only configuration. This will not adjust any lights and will ignore any lights defined in the app, instead it will simply create a Home Assistant sensor. This can be used to observe the app behavior, or to use the sensor data with another automation or app.
89 |
90 | ## Example apps.yaml
91 |
92 | ```
93 | main_periodic_lights:
94 | module: update_lights
95 | class: update_lights
96 | run_every: 180
97 | event_subscription: main_update_lights
98 | entities:
99 | - light.back_hallway
100 | - light.coffee_bar
101 | - light.dans_bedside
102 | - light.erins_bedside
103 | - light.group_family_room
104 | - light.guest_room
105 | - light.kitchen2
106 | - light.kitchen_spotlight
107 | - light.kitchen_spotlight_left
108 | - light.kitchen_spotlight_right
109 | - light.living_room_dimmer
110 | - light.living_room_lamp
111 | - light.living_room_lamp_2
112 | - light.main_cabinets
113 | - light.mb_fan
114 | brightness_threshold: 25
115 | color_temp_max: 250
116 | color_temp_min: 500
117 | color_temp_unit: 'mired'
118 | max_brightness_level: 100
119 | min_brightness_level: 1
120 | brightness_unit: 'percent'
121 | sleep_entity:
122 | - input_boolean.bedtime
123 | - switch.dan_bedtime
124 | - switch.erin_bedtime
125 | red_hour: '21:00:00'
126 | start_time: sunset - 3:00:00
127 | end_time: sunrise + 2:00:00
128 | start_index: '17:00:00'
129 | end_index: '08:00:00'
130 | transition: 5
131 | keep_lights_on: False
132 | stop_lights_off: True
133 | watch_light_state: False
134 | disable_entity:
135 | - input_boolean.party_mode,on
136 | - input_boolean.hold_lights,on
137 | - input_boolean.disco,on
138 | - sensor.arbitrary_sensor,arbitrary_condition
139 | sensor_log: sensor.main_lights
140 |
141 | exterior_periodic_lights:
142 | module: update_lights
143 | class: update_lights
144 | run_every: 180
145 | entities:
146 | - light.group_backyard
147 | - light.group_exterior_garage
148 | min_brightness_level: 102
149 | start_time: sunset - 0:20:00
150 | end_time: sunrise
151 | transition: 0
152 | start_lights_on: True
153 | stop_lights_off: True
154 | ```
155 |
156 | ## Example of xy color configuration
157 |
158 | ```
159 | xy_colors:
160 | module: update_lights
161 | class: update_lights
162 | entities:
163 | - light.living_room_lamp
164 | - light.living_room_lamp_2
165 | color_unit: 'xy'
166 | color_max:
167 | - 0.3
168 | - 0.35
169 | color_min:
170 | - 0.45
171 | - 0.45
172 | ```
173 | ## Example script/automation for event subscription
174 |
175 | ```
176 | script:
177 | - force_light_update:
178 | sequence:
179 | - event: main_periodic_lights
180 | event_data:
181 | threshold: 255
182 | transition: 0
183 | ```
184 |
185 | ## Example sensor only configuration
186 | ```
187 | sensor_only_periodic_lights:
188 | module: update_lights
189 | class: update_lights
190 | run_every: 30
191 | sensor_only: True
192 | start_index: sunset + 02:00:00
193 | end_index: sunrise - 02:00:00
194 | ```
195 |
--------------------------------------------------------------------------------
/apps/update_lights/update_lights.py:
--------------------------------------------------------------------------------
1 | import hassapi as hass
2 | import datetime
3 | import color as color_utils
4 | import color_to_kelvin
5 | from datetime import timedelta
6 | import math
7 |
8 | class update_lights(hass.Hass):
9 | def initialize(self):
10 | now = datetime.datetime.now()
11 | # Import all user settings
12 | lights = self.args.get('entities', [])
13 | areas = self.args.get('areas', [])
14 | reject = self.args.get('reject',[])
15 | self.disable_entity = self.args.get('disable_entity', [])
16 | self.disable_condition = self.args.get('disable_condition', [])
17 | self.sleep_entity = self.args.get('sleep_entity', [])
18 | self.sleep_condition = self.args.get('sleep_condition', [])
19 | self.sleep_color = str(self.args.get('sleep_color', 'red'))
20 | self.sleep_xy_color = self.args.get('sleep_xy_color',None)
21 | self.max_brightness_level = int(self.args.get('max_brightness_level', 255))
22 | self.min_brightness_level = int(self.args.get('min_brightness_level', 3))
23 | self.brightness_unit = str(self.args.get('brightness_unit', 'bit'))
24 | self.brightness_threshold = int(self.args.get('brightness_threshold', 255))
25 | self.brightness_only = bool(self.args.get('brightness_only', False))
26 | self.transition = int(self.args.get('transition', 5))
27 | self.start_time = str(self.args.get('start_time', 'sunset'))
28 | self.end_time = str(self.args.get('end_time', 'sunrise'))
29 | self.perfer_rgb = self.args.get('perfer_rgb', False)
30 | self.start_index = str(self.args.get('start_index', self.start_time))
31 | self.end_index = str(self.args.get('end_index', self.end_time))
32 | self.color_temp_unit = str(self.args.get('color_temp_unit', 'kelvin'))
33 | self.color_temp_max = int(self.args.get('color_temp_max', 4000))
34 | self.color_temp_min = int(self.args.get('color_temp_min', 2200))
35 | # Support for xy color
36 | self.color_unit = str(self.args.get('color_unit', self.color_temp_unit))
37 | self.color_max = self.args.get('color_max', self.color_temp_max)
38 | self.color_min = self.args.get('color_min', self.color_temp_min)
39 | self.sleep_color_temp = int(self.args.get('sleep_color_temp', self.color_temp_min))
40 | self.watch_light_state = self.args.get('watch_light_state', True)
41 | self.keep_lights_on = self.args.get('keep_lights_on', False)
42 | self.start_lights_on = self.args.get('start_lights_on', False)
43 | self.stop_lights_off = self.args.get('stop_lights_off', False)
44 | self.sensor_only = self.args.get('sensor_only', False)
45 | self.event = self.args.get('event_subscription', None)
46 |
47 | self.all_lights = lights
48 | rejectFilter = ""
49 | if reject:
50 | for item in reject:
51 | rejectFilter = rejectFilter + "| rejectattr('entity_id', 'contains','" + item + "')"
52 | if areas:
53 | areaLights = []
54 | for area in areas:
55 | templateString = "{{ area_entities('"+area+"')| reject('is_hidden_entity') | expand |selectattr('entity_id', 'match','light')" + rejectFilter + " | rejectattr('state', 'eq', 'unavailable') | rejectattr('attributes.supported_color_modes','eq',['onoff']) | map(attribute='entity_id') | list }}"
56 | areaLights = areaLights + self.render_template(templateString)
57 | self.all_lights = self.all_lights + areaLights
58 | self.log(self.all_lights)
59 | interval = int(self.args.get('run_every', 180))
60 | target = now + timedelta(seconds=interval)
61 |
62 | if self.sensor_only and self.sensor_only != 'false':
63 | # Sensor only is specified
64 | self.run_every(self.time_change, target, interval)
65 | return
66 | else:
67 | self.sensor_only = False
68 | if isinstance(self.all_lights, str):
69 | self.all_lights = self.all_lights.split(',')
70 | if isinstance(self.disable_entity, str):
71 | self.disable_entity = self.disable_entity.split('*')
72 | if isinstance(self.disable_condition, str):
73 | self.disable_condition = self.disable_condition.split(',')
74 | if isinstance(self.sleep_entity, str):
75 | self.sleep_entity = self.sleep_entity.split('*')
76 | if isinstance(self.sleep_condition, str):
77 | self.sleep_condition = self.sleep_condition.split(',')
78 | # Basic error checking
79 | if not isinstance(self.transition, int) or self.transition > 300:
80 | self.transition = 5
81 |
82 | if self.brightness_unit == 'percent':
83 | # Convert to bit
84 | self.brightness_threshold = int(self.brightness_threshold * 2.55)
85 | self.max_brightness_level = int(self.max_brightness_level * 2.55)
86 | self.min_brightness_level = int(self.min_brightness_level * 2.55)
87 | if not isinstance(self.brightness_threshold, int) or self.brightness_threshold > 255:
88 | self.brightness_threshold = 255
89 | if not isinstance(self.max_brightness_level, int) or self.max_brightness_level > 255:
90 | self.max_brightness_level = 255
91 | if not isinstance(self.min_brightness_level, int) or self.min_brightness_level > 255 or self.min_brightness_level > self.max_brightness_level:
92 | self.min_brightness_level = 3
93 |
94 | if str(self.perfer_rgb).lower() == 'false':
95 | self.perfer_rgb = False
96 | else:
97 | self.perfer_rgb = True
98 | if str(self.keep_lights_on).lower() == 'false':
99 | self.keep_lights_on = False
100 | else:
101 | self.keep_lights_on = True
102 |
103 | if str(self.start_lights_on).lower() == 'false':
104 | self.start_lights_on = False
105 | else:
106 | self.start_lights_on = True
107 | self.run_daily(self.lights_on, self.parse_time(self.start_time))
108 |
109 | if str(self.stop_lights_off).lower() == 'false':
110 | self.stop_lights_off = False
111 | else:
112 | self.stop_lights_off = True
113 | self.run_daily(self.lights_off, self.parse_time(self.end_time))
114 |
115 | # Set callbacks for time interval, and subscribe to individual lights and disable/sleep entities
116 | if self.all_lights is not None:
117 | if self.disable_entity is not None:
118 | for entity in self.disable_entity:
119 | if len(entity.split(',')) > 1:
120 | entity = entity.split(',')[0]
121 | self.listen_state(self.state_change, entity)
122 | if self.sleep_entity is not None:
123 | for entity in self.sleep_entity:
124 | if len(entity.split(',')) > 1:
125 | entity = entity.split(',')[0]
126 | self.listen_state(self.state_change, entity)
127 | if self.watch_light_state:
128 | for light in self.all_lights:
129 | self.listen_state(self.state_change, light, oneshot = True)
130 | if interval > 0:
131 | self.run_every(self.time_change, target, interval)
132 | if self.event is not None:
133 | self.listen_event(self.event_subscription, self.event)
134 | else:
135 | self.log('No lights defined', log='error_log')
136 |
137 | def time_change(self, kwargs):
138 | threshold = self.brightness_threshold
139 | transition = self.transition
140 | entities = self.all_lights
141 | self.adjust_light(entities, threshold, transition)
142 |
143 | def event_subscription(self, event, data, kwargs):
144 | self.log('Event fired')
145 | threshold = 255
146 | if 'threshold' in data:
147 | threshold = data['threshold']
148 | transition = 0
149 | if 'transition' in data:
150 | transition = data['transition']
151 | entities = self.all_lights
152 | self.adjust_light(entities, threshold, transition)
153 |
154 | def state_change(self, entity, attribute, old, new, kwargs):
155 | threshold = 255
156 | transition = 0
157 | if entity in self.all_lights:
158 | if new == "on":
159 | self.adjust_light(entity, threshold, transition)
160 | self.run_in(self.resubscribe, 2, entity = entity)
161 | return
162 | if self.disable_entity is not None:
163 | for check_entity in self.disable_entity:
164 | if entity == check_entity.split(',')[0] and not self.condition_query(self.disable_entity, self.disable_condition):
165 | self.adjust_light(self.all_lights, threshold, transition)
166 | return
167 | if self.sleep_entity is not None:
168 | for check_entity in self.sleep_entity:
169 | if entity == check_entity.split(',')[0]:
170 | self.adjust_light(self.all_lights, threshold, transition)
171 | return
172 |
173 | def resubscribe (self, kwargs):
174 | self.listen_state(self.state_change, kwargs['entity'], oneshot = True)
175 |
176 | def lights_on(self, kwargs):
177 | #Turn on all lights
178 | check = self.condition_query(self.disable_entity, self.disable_condition)
179 | if not check:
180 | for entity in self.all_lights:
181 | self.turn_on(entity)
182 |
183 | def lights_off(self, kwargs):
184 | #Turn off all lights
185 | check = self.condition_query(self.disable_entity, self.disable_condition)
186 | if not check:
187 | for entity in self.all_lights:
188 | self.turn_off(entity)
189 |
190 | def pct(self):
191 | """Calculate percentage through day"""
192 | dt = datetime.datetime.now()
193 | now_time = dt.timestamp()
194 |
195 | start = datetime.datetime.combine(self.date(), self.parse_time(self.start_time))
196 | end = datetime.datetime.combine(self.date(), self.parse_time(self.end_time))
197 | midnight = '0:00:00'
198 | if end > start and (self.now_is_between(self.end_time, self.start_time) or self.now_is_between(midnight, self.end_time)):
199 | self.log('Start and end occur in the same day. No time delta.')
200 | elif self.now_is_between(midnight, self.end_time) and not self.now_is_between(self.start_time, midnight):
201 | #We are past midnight and the start time was the day before
202 | #self.log('Time delta start -1 day')
203 | start = start + timedelta(days=-1)
204 | elif self.now_is_between(self.end_time, midnight) and start > end:
205 | #We are before midnight and the end time is after midnight
206 | #self.log('Time delta end +1 day')
207 | end = end + timedelta(days=1)
208 | # Get index times
209 | start_i = datetime.datetime.combine(start.date(), self.parse_time(self.start_index))
210 | end_i = datetime.datetime.combine(end.date(), self.parse_time(self.end_index))
211 | if start_i > end_i:
212 | #End is before midnight but end index is after
213 | end_i = end_i + timedelta(days=1)
214 | #Figure out midpoint
215 | half_seconds = (end - start).total_seconds() / 2
216 | half = start + timedelta(seconds=half_seconds)
217 | #Figure out start index midpoint
218 | half_seconds = (end - start_i).total_seconds() / 2
219 | midpoint_start = start_i + timedelta(seconds=half_seconds)
220 | #Figure out end index midpoint
221 | half_seconds = (end_i - start).total_seconds() / 2
222 | midpoint_end = start + timedelta(seconds=half_seconds)
223 | #Calculate the midpoint between start and end time incorpertaing the indexed times
224 | if (dt > midpoint_start and dt < midpoint_end) or (dt < midpoint_start and dt > midpoint_end):
225 | #self.log('In the middle of the midpoints')
226 | pct = 0
227 | else:
228 | if dt < midpoint_start:
229 | # midpoint = midpoint_start.timestamp()
230 | midpoint = midpoint_end.timestamp()
231 | else:
232 | midpoint = midpoint_start.timestamp()
233 | # midpoint = midpoint_end.timestamp()
234 | pct = abs(float(math.sin(math.pi*((now_time - midpoint) / (86400)))))
235 | return pct, half, midpoint_start, midpoint_end
236 |
237 | def color_temp(self, pct):
238 | color_max = self.color_temp_max
239 | color_min = self.color_temp_min
240 | if self.color_temp_unit != 'kelvin' and self.color_temp_unit != 'mired':
241 | #Catch the case where the user entered bad information or had a typo
242 | color_max = 4000
243 | self.color_temp_max = 4000
244 | color_min = 2200
245 | self.color_temp_min = 2200
246 | self.color_temp_unit = 'kelvin'
247 | elif self.color_temp_unit == 'mired':
248 | # Switch to kelvin for the calculation
249 | color_max = color_utils.color_temperature_mired_to_kelvin(color_max)
250 | color_min = color_utils.color_temperature_mired_to_kelvin(color_min)
251 | # Calculate desired color temp
252 | desired_temp_kelvin = round(int(color_min) + (abs(int(color_max) - int(color_min))* float(pct)))
253 | desired_temp_mired = color_utils.color_temperature_kelvin_to_mired(desired_temp_kelvin)
254 | return int(desired_temp_kelvin), int(desired_temp_mired)
255 |
256 | def color_xy(self,pct):
257 | color_max = self.color_max
258 | color_min = self.color_min
259 | # Calculate desired color
260 | slope = (float(color_max[1])-float(color_min[1]))/(float(color_max[0])-float(color_min[0]))
261 | b = float(color_max[1]) - float(slope) * float(color_max[0])
262 | desired_x_color = (float(color_min[0])+(float(color_max[0])-float(color_min[0]))*float(pct))
263 | desired_y_color = slope * desired_x_color + b
264 | return (desired_x_color, desired_y_color)
265 |
266 | def brightness(self, pct):
267 | max_brightness_level = self.max_brightness_level
268 | min_brightness_level = self.min_brightness_level
269 | brightness_unit = self.brightness_unit
270 | # Calculate brightness level in the defined range
271 | brightness_level = int(min_brightness_level) + round(int(max_brightness_level - min_brightness_level) * pct)
272 | sleep_state = self.condition_query(self.sleep_entity, self.sleep_condition)
273 | if int(brightness_level) > int(max_brightness_level) and sleep_state != True:
274 | # If we are above 255 correct for that
275 | return int(max_brightness_level)
276 | elif int(brightness_level) < int(min_brightness_level) or sleep_state == True:
277 | # If we are below min or are in sleep state
278 | return int(min_brightness_level)
279 | return brightness_level
280 |
281 | def condition_query (self, entities, condition = None):
282 | value = False
283 | condition_states = ['on', 'Home', 'home', 'True', 'true']
284 | if condition is not None:
285 | condition_states.append(condition)
286 | if entities is not None:
287 | for entity in entities:
288 | if len(entity.split(',')) > 1:
289 | if entity.split(',')[1] == self.get_state(entity.split(',')[0]):
290 | value = True
291 | elif self.get_state(entity) == True or self.get_state(entity) in condition_states:
292 | value = True
293 | return value
294 |
295 | def adjust_light(self, entities, threshold, transition):
296 | """ Change light temp and brightness if conditions are met """
297 | #Calculate our percentage and midpoints
298 | pct, half, midpoint_start, midpoint_end = self.pct()
299 | #Calculate brightness, temp, and colors, based on percentage
300 | brightness_level = self.brightness(pct)
301 | #Check if sleep conditions are met
302 | sleep_state = self.condition_query(self.sleep_entity, self.sleep_condition)
303 | perfer_rgb = self.perfer_rgb
304 | if self.color_unit == 'xy':
305 | perfer_rgb = True
306 | if sleep_state:
307 | tmp_red, tmp_green, tmp_blue = color_utils.color_name_to_rgb (self.sleep_color)
308 | xy_color = color_utils.color_RGB_to_xy(tmp_red, tmp_green, tmp_blue)
309 | else:
310 | xy_color = self.color_xy(pct)
311 | tmp_red, tmp_green, tmp_blue = color_utils.color_xy_to_RGB(xy_color[0],xy_color[1])
312 | desired_temp_kelvin = color_to_kelvin.color_RGB_to_kelvin((tmp_red, tmp_green, tmp_blue))
313 | desired_temp_mired = color_utils.color_temperature_kelvin_to_mired(desired_temp_kelvin)
314 | else:
315 | if sleep_state:
316 | tmp_red, tmp_green, tmp_blue = color_utils.color_name_to_rgb (self.sleep_color)
317 | if self.color_temp_unit == 'kelvin':
318 | desired_temp_kelvin = self.sleep_color_temp
319 | desired_temp_mired = color_utils.color_temperature_kelvin_to_mired(desired_temp_kelvin)
320 | else:
321 | desired_temp_mired = self.sleep_color_temp
322 | desired_temp_kelvin = color_utils.color_temperature_mired_to_kelvin(desired_temp_mired)
323 | else:
324 | desired_temp_kelvin, desired_temp_mired = self.color_temp(pct)
325 | tmp_red, tmp_green, tmp_blue = color_utils.color_temperature_to_rgb(desired_temp_kelvin)
326 | xy_color = color_utils.color_RGB_to_xy(tmp_red, tmp_green, tmp_blue)
327 | xyb_color = color_utils.color_RGB_to_xy_brightness(tmp_red, tmp_green, tmp_blue)
328 | hsv_color = color_utils.color_RGB_to_hsv(tmp_red, tmp_green, tmp_blue)
329 | hs_color = color_utils.color_RGB_to_hs(tmp_red, tmp_green, tmp_blue)
330 |
331 | """Output sensor log"""
332 | if 'sensor_log' in self.args:
333 | sensor_log = self.args['sensor_log']
334 | else:
335 | sensor_log = 'sensor.' + self.name
336 | self.set_state(sensor_log, state=(round(brightness_level/2.55,2)), attributes = {"unit_of_measurement":"%", "note":"Light brightness",
337 | "Kelvin temperature": desired_temp_kelvin,
338 | "Mired temperature": desired_temp_mired,
339 | "RGB": [int(tmp_red), int(tmp_green), int(tmp_blue)],
340 | "XY Color": [round(xy_color[0],3), round(xy_color[1],3)],
341 | "XY Brightness Color": xyb_color,
342 | "HS Color": hs_color,
343 | "Midpoint": half, "Start index midpoint": midpoint_start, "End index midpoint": midpoint_end})
344 |
345 | """Check if any disable entities are blocking"""
346 | override = self.condition_query(self.disable_entity, self.disable_condition)
347 | if override or self.sensor_only:
348 | return None
349 |
350 | # Run companion script if defined
351 | if 'companion_script' in self.args:
352 | self.turn_on(entity_id=self.args['companion_script'])
353 | if isinstance(entities, str):
354 | entities = entities.split(',')
355 | color_temp_list = []
356 | rgb_list = []
357 | brightness_only_list = []
358 | """Create service data structures for each light type"""
359 | rgb_service_data = {"brightness": brightness_level, "transition": transition}
360 | color_temp_service_data = {"brightness": brightness_level, "transition": transition}
361 | brightness_only_service_data = {"brightness": brightness_level, "transition": transition}
362 | color_modes = ['rgb', 'rgbw', 'hs', 'xy']
363 | for entity_id in entities:
364 | """Loop through lights, checking the condition and supported color modes for each one.
365 | Append each compliant light to a list depending on what type of adjustment the light is capable of."""
366 | cur_state = self.get_state(entity_id)
367 | if (cur_state == 'on' or (self.keep_lights_on and self.now_is_between(self.start_time, self.end_time))):
368 | brightness = self.get_state(entity_id, attribute="brightness")
369 | if (brightness is not None and (abs(int(brightness) - int(brightness_level)) < int(threshold)) and int(brightness) != int(brightness_level)) or self.keep_lights_on or sleep_state:
370 | supported_color_modes = self.get_state(entity_id, attribute='supported_color_modes')
371 | if any(item in color_modes for item in supported_color_modes) and ('color_temp' not in supported_color_modes or sleep_state or perfer_rgb) and not self.brightness_only:
372 | rgb_list.append(entity_id)
373 | elif 'color_temp' in supported_color_modes and not self.brightness_only:
374 | color_temp_list.append(entity_id)
375 | else:
376 | brightness_only_list.append(entity_id)
377 |
378 | if len(rgb_list) != 0:
379 | rgb_service_data['rgb_color'] = [int(tmp_red), int(tmp_green), int(tmp_blue)]
380 | rgb_service_data['entity_id'] = rgb_list
381 | self.call_service("light/turn_on", **rgb_service_data)
382 |
383 | if len(color_temp_list) != 0:
384 | color_temp_service_data['entity_id'] = color_temp_list
385 | color_temp_service_data['color_temp'] = desired_temp_mired
386 | self.call_service("light/turn_on", **color_temp_service_data)
387 |
388 | if len(brightness_only_list) != 0:
389 | brightness_only_service_data['entity_id'] = brightness_only_list
390 | self.call_service("light/turn_on", **brightness_only_service_data)
391 |
392 |
--------------------------------------------------------------------------------
/apps/update_lights/color.py:
--------------------------------------------------------------------------------
1 | """Color util methods from Home Assistant Core."""
2 | from __future__ import annotations
3 |
4 | import colorsys
5 | import math
6 |
7 | import attr
8 |
9 | # Official CSS3 colors from w3.org:
10 | # https://www.w3.org/TR/2010/PR-css3-color-20101028/#html4
11 | # names do not have spaces in them so that we can compare against
12 | # requests more easily (by removing spaces from the requests as well).
13 | # This lets "dark seagreen" and "dark sea green" both match the same
14 | # color "darkseagreen".
15 | COLORS = {
16 | "aliceblue": (240, 248, 255),
17 | "antiquewhite": (250, 235, 215),
18 | "aqua": (0, 255, 255),
19 | "aquamarine": (127, 255, 212),
20 | "azure": (240, 255, 255),
21 | "beige": (245, 245, 220),
22 | "bisque": (255, 228, 196),
23 | "black": (0, 0, 0),
24 | "blanchedalmond": (255, 235, 205),
25 | "blue": (0, 0, 255),
26 | "blueviolet": (138, 43, 226),
27 | "brown": (165, 42, 42),
28 | "burlywood": (222, 184, 135),
29 | "cadetblue": (95, 158, 160),
30 | "chartreuse": (127, 255, 0),
31 | "chocolate": (210, 105, 30),
32 | "coral": (255, 127, 80),
33 | "cornflowerblue": (100, 149, 237),
34 | "cornsilk": (255, 248, 220),
35 | "crimson": (220, 20, 60),
36 | "cyan": (0, 255, 255),
37 | "darkblue": (0, 0, 139),
38 | "darkcyan": (0, 139, 139),
39 | "darkgoldenrod": (184, 134, 11),
40 | "darkgray": (169, 169, 169),
41 | "darkgreen": (0, 100, 0),
42 | "darkgrey": (169, 169, 169),
43 | "darkkhaki": (189, 183, 107),
44 | "darkmagenta": (139, 0, 139),
45 | "darkolivegreen": (85, 107, 47),
46 | "darkorange": (255, 140, 0),
47 | "darkorchid": (153, 50, 204),
48 | "darkred": (139, 0, 0),
49 | "darksalmon": (233, 150, 122),
50 | "darkseagreen": (143, 188, 143),
51 | "darkslateblue": (72, 61, 139),
52 | "darkslategray": (47, 79, 79),
53 | "darkslategrey": (47, 79, 79),
54 | "darkturquoise": (0, 206, 209),
55 | "darkviolet": (148, 0, 211),
56 | "deeppink": (255, 20, 147),
57 | "deepskyblue": (0, 191, 255),
58 | "dimgray": (105, 105, 105),
59 | "dimgrey": (105, 105, 105),
60 | "dodgerblue": (30, 144, 255),
61 | "firebrick": (178, 34, 34),
62 | "floralwhite": (255, 250, 240),
63 | "forestgreen": (34, 139, 34),
64 | "fuchsia": (255, 0, 255),
65 | "gainsboro": (220, 220, 220),
66 | "ghostwhite": (248, 248, 255),
67 | "gold": (255, 215, 0),
68 | "goldenrod": (218, 165, 32),
69 | "gray": (128, 128, 128),
70 | "green": (0, 128, 0),
71 | "greenyellow": (173, 255, 47),
72 | "grey": (128, 128, 128),
73 | "honeydew": (240, 255, 240),
74 | "hotpink": (255, 105, 180),
75 | "indianred": (205, 92, 92),
76 | "indigo": (75, 0, 130),
77 | "ivory": (255, 255, 240),
78 | "khaki": (240, 230, 140),
79 | "lavender": (230, 230, 250),
80 | "lavenderblush": (255, 240, 245),
81 | "lawngreen": (124, 252, 0),
82 | "lemonchiffon": (255, 250, 205),
83 | "lightblue": (173, 216, 230),
84 | "lightcoral": (240, 128, 128),
85 | "lightcyan": (224, 255, 255),
86 | "lightgoldenrodyellow": (250, 250, 210),
87 | "lightgray": (211, 211, 211),
88 | "lightgreen": (144, 238, 144),
89 | "lightgrey": (211, 211, 211),
90 | "lightpink": (255, 182, 193),
91 | "lightsalmon": (255, 160, 122),
92 | "lightseagreen": (32, 178, 170),
93 | "lightskyblue": (135, 206, 250),
94 | "lightslategray": (119, 136, 153),
95 | "lightslategrey": (119, 136, 153),
96 | "lightsteelblue": (176, 196, 222),
97 | "lightyellow": (255, 255, 224),
98 | "lime": (0, 255, 0),
99 | "limegreen": (50, 205, 50),
100 | "linen": (250, 240, 230),
101 | "magenta": (255, 0, 255),
102 | "maroon": (128, 0, 0),
103 | "mediumaquamarine": (102, 205, 170),
104 | "mediumblue": (0, 0, 205),
105 | "mediumorchid": (186, 85, 211),
106 | "mediumpurple": (147, 112, 219),
107 | "mediumseagreen": (60, 179, 113),
108 | "mediumslateblue": (123, 104, 238),
109 | "mediumspringgreen": (0, 250, 154),
110 | "mediumturquoise": (72, 209, 204),
111 | "mediumvioletred": (199, 21, 133),
112 | "midnightblue": (25, 25, 112),
113 | "mintcream": (245, 255, 250),
114 | "mistyrose": (255, 228, 225),
115 | "moccasin": (255, 228, 181),
116 | "navajowhite": (255, 222, 173),
117 | "navy": (0, 0, 128),
118 | "navyblue": (0, 0, 128),
119 | "oldlace": (253, 245, 230),
120 | "olive": (128, 128, 0),
121 | "olivedrab": (107, 142, 35),
122 | "orange": (255, 165, 0),
123 | "orangered": (255, 69, 0),
124 | "orchid": (218, 112, 214),
125 | "palegoldenrod": (238, 232, 170),
126 | "palegreen": (152, 251, 152),
127 | "paleturquoise": (175, 238, 238),
128 | "palevioletred": (219, 112, 147),
129 | "papayawhip": (255, 239, 213),
130 | "peachpuff": (255, 218, 185),
131 | "peru": (205, 133, 63),
132 | "pink": (255, 192, 203),
133 | "plum": (221, 160, 221),
134 | "powderblue": (176, 224, 230),
135 | "purple": (128, 0, 128),
136 | "red": (255, 0, 0),
137 | "rosybrown": (188, 143, 143),
138 | "royalblue": (65, 105, 225),
139 | "saddlebrown": (139, 69, 19),
140 | "salmon": (250, 128, 114),
141 | "sandybrown": (244, 164, 96),
142 | "seagreen": (46, 139, 87),
143 | "seashell": (255, 245, 238),
144 | "sienna": (160, 82, 45),
145 | "silver": (192, 192, 192),
146 | "skyblue": (135, 206, 235),
147 | "slateblue": (106, 90, 205),
148 | "slategray": (112, 128, 144),
149 | "slategrey": (112, 128, 144),
150 | "snow": (255, 250, 250),
151 | "springgreen": (0, 255, 127),
152 | "steelblue": (70, 130, 180),
153 | "tan": (210, 180, 140),
154 | "teal": (0, 128, 128),
155 | "thistle": (216, 191, 216),
156 | "tomato": (255, 99, 71),
157 | "turquoise": (64, 224, 208),
158 | "violet": (238, 130, 238),
159 | "wheat": (245, 222, 179),
160 | "white": (255, 255, 255),
161 | "whitesmoke": (245, 245, 245),
162 | "yellow": (255, 255, 0),
163 | "yellowgreen": (154, 205, 50),
164 | # And...
165 | "homeassistant": (3, 169, 244),
166 | }
167 |
168 |
169 | @attr.s()
170 | class XYPoint:
171 | """Represents a CIE 1931 XY coordinate pair."""
172 |
173 | x: float = attr.ib() # pylint: disable=invalid-name
174 | y: float = attr.ib() # pylint: disable=invalid-name
175 |
176 |
177 | @attr.s()
178 | class GamutType:
179 | """Represents the Gamut of a light."""
180 |
181 | # ColorGamut = gamut(xypoint(xR,yR),xypoint(xG,yG),xypoint(xB,yB))
182 | red: XYPoint = attr.ib()
183 | green: XYPoint = attr.ib()
184 | blue: XYPoint = attr.ib()
185 |
186 |
187 | def color_name_to_rgb(color_name: str) -> tuple[int, int, int]:
188 | """Convert color name to RGB hex value."""
189 | # COLORS map has no spaces in it, so make the color_name have no
190 | # spaces in it as well for matching purposes
191 | hex_value = COLORS.get(color_name.replace(" ", "").lower())
192 | if not hex_value:
193 | raise ValueError("Unknown color")
194 |
195 | return hex_value
196 |
197 |
198 | # pylint: disable=invalid-name
199 |
200 |
201 | def color_RGB_to_xy(
202 | iR: int, iG: int, iB: int, Gamut: GamutType | None = None
203 | ) -> tuple[float, float]:
204 | """Convert from RGB color to XY color."""
205 | return color_RGB_to_xy_brightness(iR, iG, iB, Gamut)[:2]
206 |
207 |
208 | # Taken from:
209 | # http://www.developers.meethue.com/documentation/color-conversions-rgb-xy
210 | # License: Code is given as is. Use at your own risk and discretion.
211 | def color_RGB_to_xy_brightness(
212 | iR: int, iG: int, iB: int, Gamut: GamutType | None = None
213 | ) -> tuple[float, float, int]:
214 | """Convert from RGB color to XY color."""
215 | if iR + iG + iB == 0:
216 | return 0.0, 0.0, 0
217 |
218 | R = iR / 255
219 | B = iB / 255
220 | G = iG / 255
221 |
222 | # Gamma correction
223 | R = pow((R + 0.055) / (1.0 + 0.055), 2.4) if (R > 0.04045) else (R / 12.92)
224 | G = pow((G + 0.055) / (1.0 + 0.055), 2.4) if (G > 0.04045) else (G / 12.92)
225 | B = pow((B + 0.055) / (1.0 + 0.055), 2.4) if (B > 0.04045) else (B / 12.92)
226 |
227 | # Wide RGB D65 conversion formula
228 | X = R * 0.664511 + G * 0.154324 + B * 0.162028
229 | Y = R * 0.283881 + G * 0.668433 + B * 0.047685
230 | Z = R * 0.000088 + G * 0.072310 + B * 0.986039
231 |
232 | # Convert XYZ to xy
233 | x = X / (X + Y + Z)
234 | y = Y / (X + Y + Z)
235 |
236 | # Brightness
237 | Y = 1 if Y > 1 else Y
238 | brightness = round(Y * 255)
239 |
240 | # Check if the given xy value is within the color-reach of the lamp.
241 | if Gamut:
242 | in_reach = check_point_in_lamps_reach((x, y), Gamut)
243 | if not in_reach:
244 | xy_closest = get_closest_point_to_point((x, y), Gamut)
245 | x = xy_closest[0]
246 | y = xy_closest[1]
247 |
248 | return round(x, 3), round(y, 3), brightness
249 |
250 |
251 | def color_xy_to_RGB(
252 | vX: float, vY: float, Gamut: GamutType | None = None
253 | ) -> tuple[int, int, int]:
254 | """Convert from XY to a normalized RGB."""
255 | return color_xy_brightness_to_RGB(vX, vY, 255, Gamut)
256 |
257 |
258 | # Converted to Python from Obj-C, original source from:
259 | # http://www.developers.meethue.com/documentation/color-conversions-rgb-xy
260 | def color_xy_brightness_to_RGB(
261 | vX: float, vY: float, ibrightness: int, Gamut: GamutType | None = None
262 | ) -> tuple[int, int, int]:
263 | """Convert from XYZ to RGB."""
264 | if Gamut and not check_point_in_lamps_reach((vX, vY), Gamut):
265 | xy_closest = get_closest_point_to_point((vX, vY), Gamut)
266 | vX = xy_closest[0]
267 | vY = xy_closest[1]
268 |
269 | brightness = ibrightness / 255.0
270 | if brightness == 0.0:
271 | return (0, 0, 0)
272 |
273 | Y = brightness
274 |
275 | if vY == 0.0:
276 | vY += 0.00000000001
277 |
278 | X = (Y / vY) * vX
279 | Z = (Y / vY) * (1 - vX - vY)
280 |
281 | # Convert to RGB using Wide RGB D65 conversion.
282 | r = X * 1.656492 - Y * 0.354851 - Z * 0.255038
283 | g = -X * 0.707196 + Y * 1.655397 + Z * 0.036152
284 | b = X * 0.051713 - Y * 0.121364 + Z * 1.011530
285 |
286 | # Apply reverse gamma correction.
287 | r, g, b = map(
288 | lambda x: (12.92 * x)
289 | if (x <= 0.0031308)
290 | else ((1.0 + 0.055) * pow(x, (1.0 / 2.4)) - 0.055),
291 | [r, g, b],
292 | )
293 |
294 | # Bring all negative components to zero.
295 | r, g, b = map(lambda x: max(0, x), [r, g, b])
296 |
297 | # If one component is greater than 1, weight components by that value.
298 | max_component = max(r, g, b)
299 | if max_component > 1:
300 | r, g, b = map(lambda x: x / max_component, [r, g, b])
301 |
302 | ir, ig, ib = map(lambda x: int(x * 255), [r, g, b])
303 |
304 | return (ir, ig, ib)
305 |
306 |
307 | def color_hsb_to_RGB(fH: float, fS: float, fB: float) -> tuple[int, int, int]:
308 | """Convert a hsb into its rgb representation."""
309 | if fS == 0.0:
310 | fV = int(fB * 255)
311 | return fV, fV, fV
312 |
313 | r = g = b = 0
314 | h = fH / 60
315 | f = h - float(math.floor(h))
316 | p = fB * (1 - fS)
317 | q = fB * (1 - fS * f)
318 | t = fB * (1 - (fS * (1 - f)))
319 |
320 | if int(h) == 0:
321 | r = int(fB * 255)
322 | g = int(t * 255)
323 | b = int(p * 255)
324 | elif int(h) == 1:
325 | r = int(q * 255)
326 | g = int(fB * 255)
327 | b = int(p * 255)
328 | elif int(h) == 2:
329 | r = int(p * 255)
330 | g = int(fB * 255)
331 | b = int(t * 255)
332 | elif int(h) == 3:
333 | r = int(p * 255)
334 | g = int(q * 255)
335 | b = int(fB * 255)
336 | elif int(h) == 4:
337 | r = int(t * 255)
338 | g = int(p * 255)
339 | b = int(fB * 255)
340 | elif int(h) == 5:
341 | r = int(fB * 255)
342 | g = int(p * 255)
343 | b = int(q * 255)
344 |
345 | return (r, g, b)
346 |
347 |
348 | def color_RGB_to_hsv(iR: float, iG: float, iB: float) -> tuple[float, float, float]:
349 | """Convert an rgb color to its hsv representation.
350 |
351 | Hue is scaled 0-360
352 | Sat is scaled 0-100
353 | Val is scaled 0-100
354 | """
355 | fHSV = colorsys.rgb_to_hsv(iR / 255.0, iG / 255.0, iB / 255.0)
356 | return round(fHSV[0] * 360, 3), round(fHSV[1] * 100, 3), round(fHSV[2] * 100, 3)
357 |
358 |
359 | def color_RGB_to_hs(iR: float, iG: float, iB: float) -> tuple[float, float]:
360 | """Convert an rgb color to its hs representation."""
361 | return color_RGB_to_hsv(iR, iG, iB)[:2]
362 |
363 |
364 | def color_hsv_to_RGB(iH: float, iS: float, iV: float) -> tuple[int, int, int]:
365 | """Convert an hsv color into its rgb representation.
366 |
367 | Hue is scaled 0-360
368 | Sat is scaled 0-100
369 | Val is scaled 0-100
370 | """
371 | fRGB = colorsys.hsv_to_rgb(iH / 360, iS / 100, iV / 100)
372 | return (int(fRGB[0] * 255), int(fRGB[1] * 255), int(fRGB[2] * 255))
373 |
374 |
375 | def color_hs_to_RGB(iH: float, iS: float) -> tuple[int, int, int]:
376 | """Convert an hsv color into its rgb representation."""
377 | return color_hsv_to_RGB(iH, iS, 100)
378 |
379 |
380 | def color_xy_to_hs(
381 | vX: float, vY: float, Gamut: GamutType | None = None
382 | ) -> tuple[float, float]:
383 | """Convert an xy color to its hs representation."""
384 | h, s, _ = color_RGB_to_hsv(*color_xy_to_RGB(vX, vY, Gamut))
385 | return h, s
386 |
387 |
388 | def color_hs_to_xy(
389 | iH: float, iS: float, Gamut: GamutType | None = None
390 | ) -> tuple[float, float]:
391 | """Convert an hs color to its xy representation."""
392 | return color_RGB_to_xy(*color_hs_to_RGB(iH, iS), Gamut)
393 |
394 |
395 | def _match_max_scale(input_colors: tuple, output_colors: tuple) -> tuple:
396 | """Match the maximum value of the output to the input."""
397 | max_in = max(input_colors)
398 | max_out = max(output_colors)
399 | if max_out == 0:
400 | factor = 0.0
401 | else:
402 | factor = max_in / max_out
403 | return tuple(int(round(i * factor)) for i in output_colors)
404 |
405 |
406 | def color_rgb_to_rgbw(r: int, g: int, b: int) -> tuple[int, int, int, int]:
407 | """Convert an rgb color to an rgbw representation."""
408 | # Calculate the white channel as the minimum of input rgb channels.
409 | # Subtract the white portion from the remaining rgb channels.
410 | w = min(r, g, b)
411 | rgbw = (r - w, g - w, b - w, w)
412 |
413 | # Match the output maximum value to the input. This ensures the full
414 | # channel range is used.
415 | return _match_max_scale((r, g, b), rgbw) # type: ignore
416 |
417 |
418 | def color_rgbw_to_rgb(r: int, g: int, b: int, w: int) -> tuple[int, int, int]:
419 | """Convert an rgbw color to an rgb representation."""
420 | # Add the white channel to the rgb channels.
421 | rgb = (r + w, g + w, b + w)
422 |
423 | # Match the output maximum value to the input. This ensures the
424 | # output doesn't overflow.
425 | return _match_max_scale((r, g, b, w), rgb) # type: ignore
426 |
427 |
428 | def color_rgb_to_rgbww(
429 | r: int, g: int, b: int, min_mireds: int, max_mireds: int
430 | ) -> tuple[int, int, int, int, int]:
431 | """Convert an rgb color to an rgbww representation."""
432 | # Find the color temperature when both white channels have equal brightness
433 | mired_range = max_mireds - min_mireds
434 | mired_midpoint = min_mireds + mired_range / 2
435 | color_temp_kelvin = color_temperature_mired_to_kelvin(mired_midpoint)
436 | w_r, w_g, w_b = color_temperature_to_rgb(color_temp_kelvin)
437 |
438 | # Find the ratio of the midpoint white in the input rgb channels
439 | white_level = min(r / w_r, g / w_g, b / w_b)
440 |
441 | # Subtract the white portion from the rgb channels.
442 | rgb = (r - w_r * white_level, g - w_g * white_level, b - w_b * white_level)
443 | rgbww = (*rgb, round(white_level * 255), round(white_level * 255))
444 |
445 | # Match the output maximum value to the input. This ensures the full
446 | # channel range is used.
447 | return _match_max_scale((r, g, b), rgbww) # type: ignore
448 |
449 |
450 | def color_rgbww_to_rgb(
451 | r: int, g: int, b: int, cw: int, ww: int, min_mireds: int, max_mireds: int
452 | ) -> tuple[int, int, int]:
453 | """Convert an rgbww color to an rgb representation."""
454 | # Calculate color temperature of the white channels
455 | mired_range = max_mireds - min_mireds
456 | try:
457 | ct_ratio = ww / (cw + ww)
458 | except ZeroDivisionError:
459 | ct_ratio = 0.5
460 | color_temp_mired = min_mireds + ct_ratio * mired_range
461 | color_temp_kelvin = color_temperature_mired_to_kelvin(color_temp_mired)
462 | w_r, w_g, w_b = color_temperature_to_rgb(color_temp_kelvin)
463 | white_level = max(cw, ww) / 255
464 |
465 | # Add the white channels to the rgb channels.
466 | rgb = (r + w_r * white_level, g + w_g * white_level, b + w_b * white_level)
467 |
468 | # Match the output maximum value to the input. This ensures the
469 | # output doesn't overflow.
470 | return _match_max_scale((r, g, b, cw, ww), rgb) # type: ignore
471 |
472 |
473 | def color_rgb_to_hex(r: int, g: int, b: int) -> str:
474 | """Return a RGB color from a hex color string."""
475 | return f"{round(r):02x}{round(g):02x}{round(b):02x}"
476 |
477 |
478 | def rgb_hex_to_rgb_list(hex_string: str) -> list[int]:
479 | """Return an RGB color value list from a hex color string."""
480 | return [
481 | int(hex_string[i : i + len(hex_string) // 3], 16)
482 | for i in range(0, len(hex_string), len(hex_string) // 3)
483 | ]
484 |
485 |
486 | def color_temperature_to_hs(color_temperature_kelvin: float) -> tuple[float, float]:
487 | """Return an hs color from a color temperature in Kelvin."""
488 | return color_RGB_to_hs(*color_temperature_to_rgb(color_temperature_kelvin))
489 |
490 |
491 | def color_temperature_to_rgb(
492 | color_temperature_kelvin: float,
493 | ) -> tuple[float, float, float]:
494 | """
495 | Return an RGB color from a color temperature in Kelvin.
496 |
497 | This is a rough approximation based on the formula provided by T. Helland
498 | http://www.tannerhelland.com/4435/convert-temperature-rgb-algorithm-code/
499 | """
500 | # range check
501 | if color_temperature_kelvin < 1000:
502 | color_temperature_kelvin = 1000
503 | elif color_temperature_kelvin > 40000:
504 | color_temperature_kelvin = 40000
505 |
506 | tmp_internal = color_temperature_kelvin / 100.0
507 |
508 | red = _get_red(tmp_internal)
509 |
510 | green = _get_green(tmp_internal)
511 |
512 | blue = _get_blue(tmp_internal)
513 |
514 | return red, green, blue
515 |
516 |
517 | def _clamp(color_component: float, minimum: float = 0, maximum: float = 255) -> float:
518 | """
519 | Clamp the given color component value between the given min and max values.
520 |
521 | The range defined by the minimum and maximum values is inclusive, i.e. given a
522 | color_component of 0 and a minimum of 10, the returned value is 10.
523 | """
524 | color_component_out = max(color_component, minimum)
525 | return min(color_component_out, maximum)
526 |
527 |
528 | def _get_red(temperature: float) -> float:
529 | """Get the red component of the temperature in RGB space."""
530 | if temperature <= 66:
531 | return 255
532 | tmp_red = 329.698727446 * math.pow(temperature - 60, -0.1332047592) + 50
533 | return _clamp(tmp_red)
534 |
535 |
536 | def _get_green(temperature: float) -> float:
537 | """Get the green component of the given color temp in RGB space."""
538 | if temperature <= 66:
539 | green = 99.4708025861 * math.log(temperature) - 161.1195681661
540 | else:
541 | green = 288.1221695283 * math.pow(temperature - 60, -0.0755148492) + 50
542 | return _clamp(green)
543 |
544 |
545 | def _get_blue(temperature: float) -> float:
546 | """Get the blue component of the given color temperature in RGB space."""
547 | if temperature >= 66:
548 | return 255
549 | if temperature <= 19:
550 | return 0
551 | blue = 138.5177312231 * math.log(temperature - 10) - 305.0447927307
552 | return _clamp(blue)
553 |
554 |
555 | def color_temperature_mired_to_kelvin(mired_temperature: float) -> int:
556 | """Convert absolute mired shift to degrees kelvin."""
557 | return math.floor(1000000 / mired_temperature)
558 |
559 |
560 | def color_temperature_kelvin_to_mired(kelvin_temperature: float) -> int:
561 | """Convert degrees kelvin to mired shift."""
562 | return math.floor(1000000 / kelvin_temperature)
563 |
564 |
565 | # The following 5 functions are adapted from rgbxy provided by Benjamin Knight
566 | # License: The MIT License (MIT), 2014.
567 | # https://github.com/benknight/hue-python-rgb-converter
568 | def cross_product(p1: XYPoint, p2: XYPoint) -> float:
569 | """Calculate the cross product of two XYPoints."""
570 | return float(p1.x * p2.y - p1.y * p2.x)
571 |
572 |
573 | def get_distance_between_two_points(one: XYPoint, two: XYPoint) -> float:
574 | """Calculate the distance between two XYPoints."""
575 | dx = one.x - two.x
576 | dy = one.y - two.y
577 | return math.sqrt(dx * dx + dy * dy)
578 |
579 |
580 | def get_closest_point_to_line(A: XYPoint, B: XYPoint, P: XYPoint) -> XYPoint:
581 | """
582 | Find the closest point from P to a line defined by A and B.
583 |
584 | This point will be reproducible by the lamp
585 | as it is on the edge of the gamut.
586 | """
587 | AP = XYPoint(P.x - A.x, P.y - A.y)
588 | AB = XYPoint(B.x - A.x, B.y - A.y)
589 | ab2 = AB.x * AB.x + AB.y * AB.y
590 | ap_ab = AP.x * AB.x + AP.y * AB.y
591 | t = ap_ab / ab2
592 |
593 | if t < 0.0:
594 | t = 0.0
595 | elif t > 1.0:
596 | t = 1.0
597 |
598 | return XYPoint(A.x + AB.x * t, A.y + AB.y * t)
599 |
600 |
601 | def get_closest_point_to_point(
602 | xy_tuple: tuple[float, float], Gamut: GamutType
603 | ) -> tuple[float, float]:
604 | """
605 | Get the closest matching color within the gamut of the light.
606 |
607 | Should only be used if the supplied color is outside of the color gamut.
608 | """
609 | xy_point = XYPoint(xy_tuple[0], xy_tuple[1])
610 |
611 | # find the closest point on each line in the CIE 1931 'triangle'.
612 | pAB = get_closest_point_to_line(Gamut.red, Gamut.green, xy_point)
613 | pAC = get_closest_point_to_line(Gamut.blue, Gamut.red, xy_point)
614 | pBC = get_closest_point_to_line(Gamut.green, Gamut.blue, xy_point)
615 |
616 | # Get the distances per point and see which point is closer to our Point.
617 | dAB = get_distance_between_two_points(xy_point, pAB)
618 | dAC = get_distance_between_two_points(xy_point, pAC)
619 | dBC = get_distance_between_two_points(xy_point, pBC)
620 |
621 | lowest = dAB
622 | closest_point = pAB
623 |
624 | if dAC < lowest:
625 | lowest = dAC
626 | closest_point = pAC
627 |
628 | if dBC < lowest:
629 | lowest = dBC
630 | closest_point = pBC
631 |
632 | # Change the xy value to a value which is within the reach of the lamp.
633 | cx = closest_point.x
634 | cy = closest_point.y
635 |
636 | return (cx, cy)
637 |
638 |
639 | def check_point_in_lamps_reach(p: tuple[float, float], Gamut: GamutType) -> bool:
640 | """Check if the provided XYPoint can be recreated by a Hue lamp."""
641 | v1 = XYPoint(Gamut.green.x - Gamut.red.x, Gamut.green.y - Gamut.red.y)
642 | v2 = XYPoint(Gamut.blue.x - Gamut.red.x, Gamut.blue.y - Gamut.red.y)
643 |
644 | q = XYPoint(p[0] - Gamut.red.x, p[1] - Gamut.red.y)
645 | s = cross_product(q, v2) / cross_product(v1, v2)
646 | t = cross_product(v1, q) / cross_product(v1, v2)
647 |
648 | return (s >= 0.0) and (t >= 0.0) and (s + t <= 1.0)
649 |
650 |
651 | def check_valid_gamut(Gamut: GamutType) -> bool:
652 | """Check if the supplied gamut is valid."""
653 | # Check if the three points of the supplied gamut are not on the same line.
654 | v1 = XYPoint(Gamut.green.x - Gamut.red.x, Gamut.green.y - Gamut.red.y)
655 | v2 = XYPoint(Gamut.blue.x - Gamut.red.x, Gamut.blue.y - Gamut.red.y)
656 | not_on_line = cross_product(v1, v2) > 0.0001
657 |
658 | # Check if all six coordinates of the gamut lie between 0 and 1.
659 | red_valid = (
660 | Gamut.red.x >= 0 and Gamut.red.x <= 1 and Gamut.red.y >= 0 and Gamut.red.y <= 1
661 | )
662 | green_valid = (
663 | Gamut.green.x >= 0
664 | and Gamut.green.x <= 1
665 | and Gamut.green.y >= 0
666 | and Gamut.green.y <= 1
667 | )
668 | blue_valid = (
669 | Gamut.blue.x >= 0
670 | and Gamut.blue.x <= 1
671 | and Gamut.blue.y >= 0
672 | and Gamut.blue.y <= 1
673 | )
674 |
675 | return not_on_line and red_valid and green_valid and blue_valid
676 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------