LIFX Developer Zone

First time using python

Hey, this is the first time I’ve coded, and I’m having a few issues. I’ve got a basic script that tells me the name, status (connection and power), and brightness of my bulb, but I have no idea how to convert the color data into a hex code (which is what I want it in).

import requests

token = "token"

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

response = requests.get('https://api.lifx.com/v1/lights/all', headers=headers)


response_json  = response.json()

    #Printing light name and status

response_json2 = response_json[0]

connection_status_bool = response_json2['connected']

if str(connection_status_bool) == 'True':

    connection_status = 'Connected,'
    
else:
    connection_status = 'Disconnected,'
    
brightness = response_json2['brightness']

print ("Name: %s" % response_json2['label'])

print ("Status: %s %s" % (connection_status, response_json2['power']))

print ("Brightness: {:.0%}".format(brightness))    

That comes out with

Name: Bedroom Light
Status: Connected, on
Brightness: 100%

as expected
The json output of color is:

 "color": {
      "hue": 0,
      "saturation": 1,
      "kelvin": 2700    

and I need to turn that into a hex code so I can do:

Name: Bedroom Light
Status: Connected, on
Brightness: 100%
Color: #FFFFF

If someone could help me out with that it would be very much appreciated. :slight_smile:

Hello,

This should be able to help you - https://github.com/delfick/photons/blob/main/modules/photons_control/colour.py#L443

The kelvin makes things a bit tricky, so you can ignore that. You should be able to make what you want by getting the hue, saturation, brightness from the result and take the relevant code from that file.

1 Like

I honestly have no idea how to use that, could you give me an example with the code I’ve written so far? This is my first time coding so I really don’t know what I’m doing. @delfick

Not a problem at all!

You should see some of the posts I made on the internet when I was 17 and only just learning to program :slight_smile:

So here is an over commented example, https://gist.github.com/delfick/869715f70e52d61bc8d1b0d256ebe8bf

And if you’re comfortable with functions work, then here is a version using those

If you want to know about how I’m making those strings, then look up “python f-strings”. It’s much like the % syntax you are using but lets you provide the variables in the string rather than after it.

A more complete version would sort the results so they appear in the same order every time, and take into account devices with multiple zones (strips or tiles for example). But this is a perfectly fine place to start.

Don’t be afraid to ask questions about any of this that is confusing!

1 Like

Thank you so much for that, I’ve just spent ages trying to figure out what .get does lmao, you’ve been a massive help. I’m going to move onto the scenes part of the project, and I’d also like to add some basic commands. I made a command function (module?) which looks like this:

def commandModule():
        #Control Lights
    sleepTime = 1.1
    waiting_on_command = 1

    while waiting_on_command == 1:
        light_command = input("Enter command... ")
        
        powerOn = ['on','On','ON','power on','Power on','POWER ON','Power On']
        powerOff = ['off','Off','OFF','power off','Power off','POWER OFF','Power Off']
        SetBrightness = ['Brightness','brightness','bright']

        if str(light_command) in powerOn:
            payload = {
            "power": "on"
            }
            response = requests.put('https://api.lifx.com/v1/lights/all/state', data=payload, headers=headers)
            time.sleep(sleepTime)
            print_light_info()
        elif str(light_command) in powerOff:
            payload = {
            "power": "off"
            }
            response = requests.put('https://api.lifx.com/v1/lights/all/state', data=payload, headers=headers)
            time.sleep(sleepTime)
            print_light_info()
        elif str(light_command) in SetBrightness:
            brightness_command = input("Enter brightness from 0 to 1... ")

            payload = {
            "brightness": "%s" % brightness_command
            }
            response = requests.put('https://api.lifx.com/v1/lights/all/state', data=payload, headers=headers)
            time.sleep(sleepTime)
            print_light_info()
            
        elif str(light_command) == 'info':
        
            print_light_info()
            
            
        elif str(light_command) == 'exit':
            waiting_on_command = 0
            
            
        elif str(light_command) == 'scenes':

            scenes.listScenes()
        
        else:
            print ("That's not a valid command!")

But I’m sure that’s not a smart way of doing it. Don’t feel obliged to help out with this at all, it’s all a learning experience, I’m just figuring it out as I go. If you have any feedback pass it on.

Thanks again!

That looks pretty good :slight_smile:

So with the get method

# Let's say we have a dictionary
d = {"a": 1, "b": 2}

# We can access the value at 'a' with
value = d["a"]
print(value)  # will print '1'

# But what if we want to get the value at 'c'?
value = d["c"]
# This won't work, it'll raise an exception
# and complain the dictionary does not have a 'c' in it

# There are three ways to deal with this
# First way is to catch the exception, but it's not good
# practise when you can avoid the exception in the first place
try:
    value = d["c"]
except KeyError:
    value = 3

# The second way is to see if "c" is in the dictionary first
if "c" in d:
    value = d["c"]
else:
    value = 3

# And the third way is the other two but in one line
value = d.get("c", 3)

With your example above, you can improve it a little bit by using the “lower()” function.

So for example:

my_string = "hello there"

if my_string == "hello there" or my_string == "HELLO THERE" or my_string = "HelLO TheRE":
    print("yo")

can be shortened with

my_string = "hello there"

if my_string.lower() == "hello there":
    print("yo")

Because the “lower” function on a string will make sure all the characters in the string are lowercase, so when we compare the two strings we only have to compare against the lower case version.

Also, the result from “input” is always a string.

So we can change it to say:

question = input("Enter command: ").lower()

if question in ("on", "power on"):
    ...
elif question in ("off", "power off"):
    ...
else:
    print("Not a valid command!")

Finally, we can use the break statement instead of the waiting_on_command:

while True:
    question = input("Input command: ").lower()

    if question == "exit":
        break

The break will stop whichever loop you’re currently in. Also related is the “continue” statement which says stop here and go to the next iteration of the loop.

I made a command function (module?)

In programming module can refer to all kinds of things. In python you would call what you made a “function” because it’s by itself. If the function is in a class definition then it’s called a “method”. In Python, a module has more to do with a collection of functions across files and folders. But ultimately it’s not a well defined word :slight_smile:

1 Like

In the writing of a script to change the light’s colour, I managed to create this monstrosity.

Choose from white, red, orange, yellow, cyan, green, blue, purple, pink, or enter hex code (#RRGGBB)

Enter color... orange
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connection.py", line 159, in _new_conn
    conn = connection.create_connection(
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\util\connection.py", line 61, in create_connection
    for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\socket.py", line 918, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connectionpool.py", line 670, in urlopen
    httplib_response = self._make_request(
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connectionpool.py", line 381, in _make_request
    self._validate_conn(conn)
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connectionpool.py", line 978, in _validate_conn
    conn.connect()
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connection.py", line 309, in connect
    conn = self._new_conn()
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connection.py", line 171, in _new_conn
    raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x03499718>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\adapters.py", line 439, in send
    resp = conn.urlopen(
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\connectionpool.py", line 726, in urlopen
    retries = retries.increment(
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\urllib3\util\retry.py", line 439, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='api.lifx,com', port=443): Max retries exceeded with url: /v1/lights/all/state (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x03499718>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\User\OneDrive - xxxxxxx\Desktop\Master.py", line 7, in <module>
    lifx_commands.cmdFunct(token)
  File "C:\Users\User\OneDrive - xxxxxxx\Desktop\lifx_commands.py", line 138, in cmdFunct
    requests.put('https://api.lifx,com/v1/lights/all/state', data=payload, headers=headers)
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\api.py", line 134, in put
    return request('put', url, data=data, **kwargs)
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\sessions.py", line 530, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\sessions.py", line 643, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\adapters.py", line 516, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='api.lifx,com', port=443): Max retries exceeded with url: /v1/lights/all/state (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x03499718>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))

I have no idea why it did this, could you please help me out, here’s the code:

    elif light_command in ('colour','color'):
    
        print()
        print("Choose from white, red, orange, yellow, cyan, green, blue, purple, pink, or enter hex code (#RRGGBB)")
        print()
        
        color = input("Enter color... ").lower()
        
        payload = {
        "color": f"{color}",
        "duration": 0
        }
        requests.put('https://api.lifx,com/v1/lights/all/state', data=payload, headers=headers)
        time.sleep(sleepTime)
        print_light_info(token)

Thanks again :slight_smile:

I believe it’s because you have a comma in https://api.lifx,com

1 Like

That would do it lmao, thanks

1 Like