I use this to automate the lights in my home while I am away at night (simulating presence). The scheduling of when this runs is handled by my home automation software (Indigo Domotics).
I'm open to any/all critique, but am especially interested in whether doing the randomization within the Light object is the right approach (and if the method of randomizing is good/pythonic/efficient). I'm a self taught programmer as a hobby only and am always trying to refine my thinking around code structure.
#!/usr/bin/python
from datetime import datetime
import random
# (min/max) seconds to delay before light turns on (randomized every time)
start_delay_range = (15, 70)
# (min/max) brightness (0-100, randomized every time)
brightness_range = (50, 85)
# (min/max) duration for light to stay on (randomized every time)
duration_range = (300, 900)
class Light():
'''
Define a light object.
Attributes:
name (str): Name of the light.
device_id (int): The Indigo ID of the device.
dimmable (bool): Set the light as dimmable or not.
'''
def __init__(self, name, device_id, dimmable):
self.name = name
self.device_id = device_id
self.dimmable = dimmable
def brightness(self):
'''Return random brightness within <brightness_range>.'''
return random.randint(brightness_range[0], brightness_range[1])
def duration(self):
'''Return random duration within <duration_range>.'''
return random.randint(duration_range[0], duration_range[1])
def start_delay(self):
'''Return random delay within <start_delay_range>.'''
return random.randint(start_delay_range[0], start_delay_range[1])
def run(self):
'''Turn on the light to <brightness> after <start_delay> for <duration>.'''
if self.dimmable:
# Turn on light
indigo.dimmer.setBrightness(self.device_id,
value = self.brightness(),
delay = self.start_delay())
else:
# Turn on light
indigo.device.turnOn(self.device_id,
self.start_delay())
# Turn off light after <delay>
indigo.device.turnOff(self.device_id,
delay = self.duration())
# List of Light() objects to randomize
lights = [
Light(name='Breakfast Room', device_id=1222428814, dimmable=True),
Light(name='Kitchen Cabinet', device_id=18462733, dimmable=False),
Light(name='Hallway', device_id=93680547, dimmable=True),
Light(name='Living Room Recessed', device_id=7507220, dimmable=True),
Light(name='Stairs', device_id=1842915774, dimmable=True),
Light(name='TV Room', device_id=1569858222, dimmable=True)
]
def main():
for light in lights:
light.run()
if __name__ == '__main__':
main()
startDelay
be added to theduration
? (or renameduration
tostopDelay
) – oliverpool Mar 1 at 6:59