LIFX Developer Zone

C# LIifxNet Toggle Light Power


#1

I use a nuget package called LifxNet by dotMorten. I can change the color of the bulb and turn it on and off. I now want to have a button that toggles the power of a bulb. I am trying to use the method GetLightStateAsync() in order to check if the light is on or off.

    private void btnPower_Click(object sender, RoutedEventArgs e)
    {
        var powerState = client.GetLightStateAsync(selectedLight).Result.IsOn;
        if (powerState == false)
        {
            client.SetDevicePowerStateAsync(selectedLight, true);
        }
        if (powerState == true)
        {
            client.SetDevicePowerStateAsync(selectedLight, false);
        }
    }

(Sorry if my formatting on the forum is wrong this is my first post)
when I run this code the entire application hangs. When I pause the code it tells me that the line of code it’s up too is

        var powerState = client.GetLightStateAsync(selectedLight).Result.IsOn;

I have tried running it in different ways and I have figured out that it hangs when you add the .Result to the code. If you remove the .Result.IsOn and comment out the if statements then the program will run fine.
I can’t figure out what is wrong and I would appreciate some help.


#2

Late reply so hopefully you’ve already solved this but thought I’d jump in to see if we can help somebody else in the future.

I’ve not played with dotMorten’s library but would first suggest checking if it’s just a generic task issue?
I’d recommend trying it with .GetAwaiter().GetResult() instead of just calling .Result

On a bit of a side note, if you’re trying to understand how to interface with a basic toggle using the UDP packets, I’ve put together a small example in C# while trying to keep it as really basic as possible… Originally it was for my own testing, but hopefully it can help others better understand how to craft the required UDP packets to accomplish these types of tasks.

https://bitbucket.org/joedm/sample-lifx-udp-protocol-with-linqpad-in-c/src/master/LIFX_UDP_Sample.linq