LIFX Developer Zone

First Script: Scene Cycling with Python3.6

Hey guys, I just started dipping my toes into the HTTP API and spent the day making a little Python script which cycles through scenes. It works pretty well, but the bulb sometimes responds with status: timed out.

I made this script to cycle through all the colors the light can produce, skipping over the ranges in which the light doesn’t change color. This makes for a smoother, constantly changing color — at least most of the time (i.e. skips when the bulb times out).

Please note that this script saves the log to the root of the drive because I’m lazy. Happy to hear recommendations for logging.

Here’s the source code minus my token (I know what you guys would do :stuck_out_tongue:):

import requests
import logging
from time import sleep

def main():

	logging.basicConfig(filename="lifxscript.log", level=logging.INFO)

	token = "PUT YOUR TOKEN HERE"

	headers = {
		"Authorization": "Bearer %s" % token,
	}

	def activate(scene):
	
		response = requests.put('https://api.lifx.com/v1/scenes/scene_id:%s/activate' % scene, headers=headers)
		print(response.content)
		logging.info(response.content)
		
	while(True):
		activate("SCENE UUID GOES HERE")
		sleep(0.5)
		activate("SCENE UUID GOES HERE")
		sleep(3)
		activate("SCENE UUID GOES HERE")
		sleep(0.5)
		activate("SCENE UUID GOES HERE")
		sleep(4)
		activate("SCENE UUID GOES HERE")
		sleep(0.5)
		activate("SCENE UUID GOES HERE")
		sleep(4)

if __name__ == '__main__':
	main()

This code is mostly derived from the examples in the documentation. I plan on eventually porting this over to use LIFX-PHOTONS-CORE to push packets over LAN rather than relying on LIFX webhooks. I’m thinking this may improve the responsiveness of the light and reduce the occurrence of time outs — if you know anything about this, I’d love to get your input.

Please let me know if you have any recommendations! I’m excited to hear what you guys have to say.

P.S. The major downside of this script to me is that it relies on the duration of scenes set from the app. This is a tuning issue because you have to adjust the sleep timers in the code accordingly. I would really like to hear from you if you know of a better way. I already tried using the cycle endpoint to accomplish this, but found it to be quite buggy and not as effective as a result.

Hi,

That’s a good start :slight_smile:

I would use the set states endpoint instead of set scene though https://api.developer.lifx.com/docs/set-states

With the logging, you can log to the console instead of a file by omitting the filename option.

If you want to do this over the LAN, there’s an example script that cycles lights through several colours over at https://github.com/delfick/photons-core/blob/master/examples/cycle_rainbow.py

If you want something more like applying a scene, here’s an example I just made https://gist.github.com/delfick/29dd1fb3ebf31eb92b6a679f052e1a9d

Don’t hesitate to ask more questions!