Giter Site home page Giter Site logo

enwi / hueplusplus Goto Github PK

View Code? Open in Web Editor NEW
53.0 9.0 21.0 13.55 MB

A simple C++ library to control Philips Hue lights on Linux, MacOS, Windows, Espressif ESP32 SDK and Arduino. Full documentation at

Home Page: https://enwi.github.io/hueplusplus/

License: GNU Lesser General Public License v3.0

C++ 98.69% CMake 1.25% C 0.07%
hue-bridge philips-hue hue-lights hue lights philips philips-hue-lights philips-hue-bridge c-plus-plus cpp

hueplusplus's Introduction

enwi's GitHub stats enwi's top languages

hueplusplus's People

Contributors

calcprogrammer1 avatar enwi avatar herbrechtsmeier avatar jojo-1000 avatar sieren avatar wulkop avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hueplusplus's Issues

Beginner guide

Hello,

Am a complete beginner.

Is it possible to upload a complete example for linux?

Am struggling with the finding the bridge (there is not 'LinHttpHandeler') what do i replace it with to run the code to find the Hue bridge?

Compile errors with clang (-Werror)

Describe the bug:
When attempting to compile the library using clang++ the compilation quickly fails due to warnings being treated as errors.

To Reproduce:
Steps to reproduce the behavior:

  1. git clone
  2. install clang
  3. make sure clang is selected by cmake
  4. build

Expected behavior:
The source code compiles with clang out of the box

Console log/Error message:

/home/emily/src/photon-hue/hueplusplus/lib/mbedtls/library/error.c: In function ‘mbedtls_strerror’:
/home/emily/src/photon-hue/hueplusplus/lib/mbedtls/library/error.c:921:47: error: ‘snprintf’ output may be truncated before the last format character [-Werror=format-truncation=]
  921 |             mbedtls_snprintf( buf, buflen, "%s", high_level_error_description );
      |                                               ^
In file included from /home/emily/src/photon-hue/hueplusplus/lib/mbedtls/library/error.c:29:
/home/emily/src/photon-hue/hueplusplus/lib/mbedtls/include/mbedtls/platform.h:76:41: note: ‘snprintf’ output 1 or more bytes (assuming 2) into a destination of size 1
   76 | #define MBEDTLS_PLATFORM_STD_SNPRINTF   snprintf /**< The default \c snprintf function to use.  */
/home/emily/src/photon-hue/hueplusplus/lib/mbedtls/include/mbedtls/platform.h:243:28: note: in expansion of macro ‘MBEDTLS_PLATFORM_STD_SNPRINTF’
  243 | #define mbedtls_snprintf   MBEDTLS_PLATFORM_STD_SNPRINTF
      |                            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/emily/src/photon-hue/hueplusplus/lib/mbedtls/library/error.c:921:13: note: in expansion of macro ‘mbedtls_snprintf’
  921 |             mbedtls_snprintf( buf, buflen, "%s", high_level_error_description );
      |             ^~~~~~~~~~~~~~~~
/home/emily/src/photon-hue/hueplusplus/lib/mbedtls/library/error.c:919:46: error: ‘UNKNOWN ERROR CODE (’ directive output truncated writing 20 bytes into a region of size 1 [-Werror=format-truncation=]
  919 |             mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", (unsigned int) use_ret );
      |                                             ~^~~~~~~~~~~~~~~~~~~
/home/emily/src/photon-hue/hueplusplus/lib/mbedtls/library/error.c:919:44: note: directive argument in the range [1, 65408]
  919 |             mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", (unsigned int) use_ret );
      |                                            ^~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /home/emily/src/photon-hue/hueplusplus/lib/mbedtls/library/error.c:29:
/home/emily/src/photon-hue/hueplusplus/lib/mbedtls/include/mbedtls/platform.h:76:41: note: ‘snprintf’ output 26 bytes into a destination of size 1
   76 | #define MBEDTLS_PLATFORM_STD_SNPRINTF   snprintf /**< The default \c snprintf function to use.  */
/home/emily/src/photon-hue/hueplusplus/lib/mbedtls/include/mbedtls/platform.h:243:28: note: in expansion of macro ‘MBEDTLS_PLATFORM_STD_SNPRINTF’
  243 | #define mbedtls_snprintf   MBEDTLS_PLATFORM_STD_SNPRINTF
      |                            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/emily/src/photon-hue/hueplusplus/lib/mbedtls/library/error.c:919:13: note: in expansion of macro ‘mbedtls_snprintf’
  919 |             mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", (unsigned int) use_ret );
      |             ^~~~~~~~~~~~~~~~
/home/emily/src/photon-hue/hueplusplus/lib/mbedtls/library/error.c:958:43: error: ‘snprintf’ output may be truncated before the last format character [-Werror=format-truncation=]
  958 |         mbedtls_snprintf( buf, buflen, "%s", low_level_error_description );
      |                                           ^
In file included from /home/emily/src/photon-hue/hueplusplus/lib/mbedtls/library/error.c:29:
/home/emily/src/photon-hue/hueplusplus/lib/mbedtls/include/mbedtls/platform.h:76:41: note: ‘snprintf’ output 1 or more bytes (assuming 2) into a destination of size 1
   76 | #define MBEDTLS_PLATFORM_STD_SNPRINTF   snprintf /**< The default \c snprintf function to use.  */
/home/emily/src/photon-hue/hueplusplus/lib/mbedtls/include/mbedtls/platform.h:243:28: note: in expansion of macro ‘MBEDTLS_PLATFORM_STD_SNPRINTF’
  243 | #define mbedtls_snprintf   MBEDTLS_PLATFORM_STD_SNPRINTF
      |                            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/emily/src/photon-hue/hueplusplus/lib/mbedtls/library/error.c:958:9: note: in expansion of macro ‘mbedtls_snprintf’
  958 |         mbedtls_snprintf( buf, buflen, "%s", low_level_error_description );
      |         ^~~~~~~~~~~~~~~~
/home/emily/src/photon-hue/hueplusplus/lib/mbedtls/library/error.c:956:42: error: ‘UNKNOWN ERROR CODE (’ directive output truncated writing 20 bytes into a region of size 1 [-Werror=format-truncation=]
  956 |         mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", (unsigned int) use_ret );
      |                                         ~^~~~~~~~~~~~~~~~~~~
/home/emily/src/photon-hue/hueplusplus/lib/mbedtls/library/error.c:956:40: note: directive argument in the range [1, 2147418239]
  956 |         mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", (unsigned int) use_ret );
      |                                        ^~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /home/emily/src/photon-hue/hueplusplus/lib/mbedtls/library/error.c:29:
/home/emily/src/photon-hue/hueplusplus/lib/mbedtls/include/mbedtls/platform.h:76:41: note: ‘snprintf’ output between 26 and 30 bytes into a destination of size 1
   76 | #define MBEDTLS_PLATFORM_STD_SNPRINTF   snprintf /**< The default \c snprintf function to use.  */
/home/emily/src/photon-hue/hueplusplus/lib/mbedtls/include/mbedtls/platform.h:243:28: note: in expansion of macro ‘MBEDTLS_PLATFORM_STD_SNPRINTF’
  243 | #define mbedtls_snprintf   MBEDTLS_PLATFORM_STD_SNPRINTF
      |                            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/emily/src/photon-hue/hueplusplus/lib/mbedtls/library/error.c:956:9: note: in expansion of macro ‘mbedtls_snprintf’
  956 |         mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", (unsigned int) use_ret );
      |         ^~~~~~~~~~~~~~~~
cc1: all warnings being treated as errors

Desktop (please complete the following information):

  • OS: Linux
  • Clang 12.0.1

Visual Studio generates warnings on 'C' style enum definitions. Maybe new C++ enum class definitions would be better in the long term.

In C, code all of the values in an enum have global scope. E.g.
enum ColorType
{
UNDEFINED, //!< ColorType for this light is unknown or undefined
NONE, //!< light has no specific ColorType
GAMUT_A,
GAMUT_B,
GAMUT_C,
TEMPERATURE,
GAMUT_A_TEMPERATURE,
GAMUT_B_TEMPERATURE,
GAMUT_C_TEMPERATURE
};

i.e. UNDEFINED has global scope anywhere huelight.h is included.
If you change the first line of the declaration to:
enum class ColorType
the warning dissappears, but then you have to write ColorType.UNDEFINED to reference the value.

This certainly isn't essential, but could be done at the same time as some more essential changes. Also it is a breaking change in the sense that some user code might stop working, so could make you unpopular.

On Windows 10 (current version) you cannot close the socket and continue to read data

I am writing a home automation system for a Raspberry Pi (linux) but using a PC with Visual Studio as my development system.
I experience a runtime error using the following block of code in WinHttpHandler.cpp at line 144:

// shutdown the connection for sending since no more data will be sent
// the client can still use the ConnectSocket for receiving data
if (shutdown(connect_socket, SD_SEND) == SOCKET_ERROR)
{
    int err = WSAGetLastError();
    std::cerr << "WinHttpHandler: shutdown failed: " << err << std::endl;
    throw(std::system_error(err, std::system_category(), "WinHttpHandler: shutdown failed"));
}

It transpires you can not (or no longer) do this with Windows 10.
I moved the block else where as shown in the attached file.
I also added a couple of #defines to cut down on the ridiculously large number of warning messages.

#define _WINSOCK_DEPRECATED_NO_WARNINGS 1
#define _CRT_SECURE_NO_WARNINGS 1

I have pasted the block of code as shown:

// Send an initial buffer
if (::send(connect_socket, msg.c_str(), msg.size(), 0) == SOCKET_ERROR)
{
    int err = WSAGetLastError();
    std::cerr << "WinHttpHandler: send failed: " << err << std::endl;
    throw(std::system_error(err, std::system_category(), "WinHttpHandler: send failed"));
}

// shutdown the connection for sending since no more data will be sent
// the client can still use the ConnectSocket for receiving data
if (shutdown(connect_socket, SD_SEND) == SOCKET_ERROR)
{
    int err = WSAGetLastError();
    std::cerr << "WinHttpHandler: shutdown failed: " << err << std::endl;
    throw(std::system_error(err, std::system_category(), "WinHttpHandler: shutdown failed"));
}

winhttphandler

Entertainment Group creation fails with API error

Describe the bug:
When creating a new Entertainment Group, the bridge responds with error 5 ("missing parameters in body").

To Reproduce:
Steps to reproduce the behavior:

  1. Instantiate and authenticate with a bridge.
  2. Attempt to create a new entertainment group like:
bridge.groups().create(hueplusplus::CreateGroup::Entertainment({"1"}, "my group"));
  1. Observe the HueAPIResponseException (details below).

Expected behavior:
The group is created.

Console log/Error message:
The exceptions what() returns:

HueApiResponseException from create in /usr/local/include/hueplusplus/ResourceList.h:304 5 /groups/class invalid/missing parameters in body

Desktop (please complete the following information):

  • OS: Kubuntu 21.10

Additional context

  • Bridge software: 1.49.1949203030

Unhandled exception

Describe the bug:
I built a QT5 light bulb manager program which provides a way to control my outdoor Hue and LIFX bulbs using the same logic. This program runs s small set of schedules to turn these bulbs on/off but also on holidays provide some color. It's all local LAN control and most of the time just some version of white + brightness for simple on/off. Some holidays I add some color. This has been true for several years now using your library for the Hue bulbs without much trouble. Last night, for the first time, I hit the following exception. Note, the terminate on the throw doesn't seem to have gotten back to my application.

LinHttpHandler: Failed to connect socket: No route to host
LinHttpHandler: Failed to connect socket: No route to host
terminate called after throwing an instance of 'std::system_error'
  what():  LinHttpHandler: Failed to connect socket: No route to host
Aborted (core dumped)

To Reproduce:
I have a timer set to a random value between 1 and 5 seconds running which calls

try {
    m_hue->at(index).setColorXY(hc.getXYB());
}
catch (std::exception &e)
{
    qWarning() << QDateTime::currentDateTime() << ": Hue did not respond correctly for bulb" << QString::fromStdString(m_hue->at(index).getName());
    qWarning() << e.what();
}

Where m_hue is a std::vector<hueplusplus::Light> *m_hue container for the Hue bulbs I am controlling and hc is a wrapper container of hueplusplus::XYBrightness.

I expect if you simply reboot the router while calling this API, you probably get the issue, though I don't have a simple way to test that right now.

Expected behavior:
If this is an exception that can be handled, it should be forwarded through so the top level caller can handle it. Based on the print, it looks a if the library tries/fails and dies instead of attempting to send it to the parent.

Console log/Error message:

LinHttpHandler: Failed to connect socket: No route to host
LinHttpHandler: Failed to connect socket: No route to host
terminate called after throwing an instance of 'std::system_error'
  what():  LinHttpHandler: Failed to connect socket: No route to host
Aborted (core dumped)

Desktop (please complete the following information):

  • OS: Linux Ubuntu
  • 22.04 LTS

Additional context
It looks as if my router hit some turbulence roughly when this happened, and network had some trouble. The logs show wifi issues, but the network stayed up (Hue bridge and this app are both on the wired network) and the first sign is about 90 seconds AFTER this, but it's probably related and the router logs are the router trying to recover from some fault at 3:00:00 AM.

I'm going to see if I can put some code in to handle this in the library later today, but am wondering if this can be more generic to the library itself.

If I can find it and handle it, I'll submit a patch if you choose to want it.

LinHttpHandler.cpp:108. LinHttpHandler: Failed to read response from socket: 104

LinHttpHandler.cpp:108

LinHttpHandler: Failed to read response from socket: 104
terminate called after throwing an instance of 'std::runtime_error'
what(): LinHttpHandler: Failed to read response from socket

my code is:

auto handler = std::make_shared<LinHttpHandler>();
HueFinder finder(handler);
std::vector<HueFinder::HueIdentification> bridges = finder.FindBridges();
if (bridges.empty())
{
	bridges.push_back({ HUE_IP, HUE_MAC});
}

finder.AddUsername(bridges[0].mac, HUE_USER_NAME);
Hue bridge = finder.GetBridge(bridges[0]);

auto m_lights = bridge.getAllLights();

for (auto light : m_lights)
	light.get().On();

NOTE: it works sometimes, and sometimes throws an error.

LinHttpHandler.cpp:105 ssize_t bytes = read(socketFD, buffer, 127);
I do not kow why but read() returns -1.

Bridge reconnect

Hello, is there in library some functionality which reconnect to Bridge is it was disconnected during operation? Thanks.

I'm getting a error when running code snippet

Describe the bug:
When attempting to run the code snippet provided in the readme I get an error.

Expected behavior:
To not get an error.

Console log/Error message:
error: undefined reference to`hueplusplus::BridgeFinder::BridgeFinder(std::shared_ptr<hueplusplus::IHttpHandler const>)'

AND

undefined reference to `hueplusplus::BridgeFinder::findBridges() const'

AND

error: undefined reference to `vtable for hueplusplus::BaseHttpHandler'

Desktop (please complete the following information):

  • OS: Manjaro Linux
  • Version NA

Additional context
I was trying to connect to the bridge using the provide code snipet

auto handler = std::make_shared<hueplusplus::LinHttpHandler>();
hue::BridgeFinder finder(handler);
std::vector<hueplusplus::BridgeFinder::BridgeIdentification> bridges = finder.findBridges();
if (bridges.empty())
{
    //std::cerr << "No bridges found\n";

}

Thankyou BOB450

Users of the library cannot detect and act on auth failures

While testing my code with deliberately bad username (API key) I ran into the following:

Answer in Hue::refreshState of http_handler->GETJson(...) is not expected!
Answer:
	[
   {
      "error" : {
         "address" : "/",
         "description" : "unauthorized user",
         "type" : 1
      }
   }
]

Which comes from here:

std::cout << "Answer in Hue::refreshState of http_handler->GETJson(...) is "
"not expected!\nAnswer:\n\t"
<< answer.toStyledString() << std::endl;

The above means that as a user of the library, it's not possible for me to detect the invalid API key and stop my application or handle it by reverting to requesting the user to push the button.

Hue bridge not responding to GET /description.xml

Thank you for this project/library!

I'm trying to get the BridgeSetup.cpp example working on Windows 7/Visual Studio 2019. I have the project building and linking against the static library, but it claims not to see any bridges.

I have confirmed (using Wireshark) that a GET request is issued to the bridge, and there is an ACK in response, but the bridge does not send any Html/Xml in response.

The packet trace looks like this:

  1. My local machine issues the GET /description.xml HTTP/1.0 request (wireshark is calling this a continuation in the Info field)
  2. My local machine then issues an [FIN/ACK]
  3. The hue bridge ACK's the Get request in (1)
  4. The hue bridge ACK's the [FIN/ACK] from (2)
  5. My local machine ACK's the [FIN/ACK] from (4)

The bridge never appears to make any attempt to send the Xml data....

By comparison, if I use a browser (Chrome) to get http://192.168.0.102/description.xml, it returns an Http/Xml response.

I do notice that the browser is using Http 1.1, whereas the BaseHttpServer is using Http 1.0.

Could this be the issue?

Any help would be greatly appreciated. If this is the wrong place to post this sort of question, please let me know where I should be posting....

Thanks again; looking forward to getting this working!

Hue.cpp does not compile on Raspberry Pi (Debian Linux I think)

Just to emphasise this package is really good. It has saved me a huge amount of time. So I thought that I would contribute back to the project with the following.

In Hue.cpp the following line (line 186 in requestUsername does not compile on Raspberry Pi (linux):
not working:
username = jsonUser;
working:
username = jsonUser.getstd::string();

Whilst the bonnet is open, also at line 173 the declaration
nlohmann::json answer;
can be moved to be with the assignment at line 180 for a slightly tidier result. (Picked out by Visual Studio/C# resharper)
nlohmann::json answer = http_handler->POSTJson("/api", request, ip, port);

Support Hue Entertainment API

I'm going to have a shot at implementing the Entertainment API. I will have a V2.1 bridge by the end of this week. The V2 bridge is required for the Entertainment API (meaning it is unsupported on the V1 bridge I already have). The API is documented here (requires login):

https://developers.meethue.com/develop/hue-entertainment/philips-hue-entertainment-api/

It looks to be a UDP protocol where one UDP packet contains up to 10 lights worth of data and can be sent up to 25 times per second. You have to request a client key when pairing with the bridge (not just a username):

POST http://<ip-address>/api:

{
    "devicetype":"myapplication#myiphone",
    "generateclientkey":true
}

Response:

[
    {
         "success":{
              "username":"myzFXhsLU5Wg10eBithGE-LFikgjC7Q7SEGZsoEf",
              "clientkey":"E3B550C65F78022EFD9E52E28378583"
                   }
     }
]

The Entertainment API uses DTLS encrypted UDP messages. The message format looks like this:

image

It looks like this API allows true RGB control of the lights.

Before sending UDP messages you must enable the streaming mode on the group with a JSON message:

Set the enable streaming flag to true, using PUT to

HTTP://<ip-address>/api/<username>/groups/<identifier of entertainment group>

With body:

{"stream":{"active":true}}

Only one stream can be active for an entertainment area, the owner field in the entertainment area indicates the application which activated the stream and is streaming towards the area.
I will edit this issue description with more information as I research it. Priorities are to figure out what DTLS encryption entails and find a simple library that can perform it, then dig into the bridge setup code to make sure we can get that client key. After that I will write a function for sending Entertainment Mode packets and hook it into my OpenRGB application to get a demonstration working.

OpenRGB is my open source, cross-platform application for synchronizing gaming peripherals and hardware and it would be awesome to synchronize Hue lights with other RGB hardware and integrate with game effects, music visualization, and more.

Tasks:

  • Add function to request API version from bridge
  • ✅ Add capability to generate a client key when requesting a username
  • ✅ Add capability to load a saved client key along with username
  • ✅ Add capability to determine if a bridge contains one or more Entertainment groups (possible without changes in library code)
  • ✅ Add function to set streaming flag to true (JSON request to bridge)
  • ✅ Add new file to contain Entertainment API code (EntertainmentMode.cpp/.h)
  • ✅ Find a library for DTLS encryption (mbedtls)
  • ✅ Implement DTLS handshaking (handled by mbedtls)
  • ✅ Add function to send stream start and stop request to bridge
  • ✅ Add function to generate and send UDP Entertainment API packet (EntertainmentMode.cpp)

All tasks required to get Entertainment Mode working complete and pull request opened, but code is in need of a lot of cleanup still.

[FR] Allow linking against external mbedtsl

Hi,

I started packaging this library for debian as prerequisite for openrgb. I encountered a few issues stemming from the embedding dependencies. No package in debian should depend/ship external libraries.

  • json.hpp : Could you maybe add a check to find the system version first, then defaulting to the included copy ?
  • mbed-tls: same issue basically. Otherwise I get the following warnings during the build:
dpkg-shlibdeps: warning: symbol mbedtls_ctr_drbg_random used by debian/libhueplusplus-dev/usr/lib/libhueplusplusshared.so found in none of the libraries
dpkg-shlibdeps: warning: symbol mbedtls_entropy_func used by debian/libhueplusplus-dev/usr/lib/libhueplusplusshared.so found in none of the libraries
dpkg-shlibdeps: warning: symbol mbedtls_timing_set_delay used by debian/libhueplusplus-dev/usr/lib/libhueplusplusshared.so found in none of the libraries
dpkg-shlibdeps: warning: symbol mbedtls_timing_get_delay used by debian/libhueplusplus-dev/usr/lib/libhueplusplusshared.so found in none of the libraries
dpkg-shlibdeps: warning: symbol mbedtls_x509_crt_init used by debian/libhueplusplus-dev/usr/lib/libhueplusplusshared.so found in none of the libraries
dpkg-shlibdeps: warning: symbol mbedtls_entropy_free used by debian/libhueplusplus-dev/usr/lib/libhueplusplusshared.so found in none of the libraries
dpkg-shlibdeps: warning: symbol mbedtls_ctr_drbg_init used by debian/libhueplusplus-dev/usr/lib/libhueplusplusshared.so found in none of the libraries
dpkg-shlibdeps: warning: symbol mbedtls_entropy_init used by debian/libhueplusplus-dev/usr/lib/libhueplusplusshared.so found in none of the libraries
dpkg-shlibdeps: warning: symbol mbedtls_ctr_drbg_seed used by debian/libhueplusplus-dev/usr/lib/libhueplusplusshared.so found in none of the libraries
dpkg-shlibdeps: warning: symbol mbedtls_ctr_drbg_free used by debian/libhueplusplus-dev/usr/lib/libhueplusplusshared.so found in none of the libraries

because the mbdedtls library from debian isn't picked up (and linked).

The tests aren't buildable offline either. I'd appreciate if you could employ a similar check because gtest and gmock are both in debian.

Missing support for new Bluetooth (Gen4) lights

I got a new Hue light yesterday with bluetooth support (gen4) with the identifier LTA001. This caused hueplusplus to crash on enumerating the lights with:

Oct 28 11:49:37 raspberrypi photon-hue-service[24287]: terminate called after throwing an instance of 'std::runtime_error'
Oct 28 11:49:37 raspberrypi photon-hue-service[24287]:   what():  Could not determine HueLight type!

This is caused by the string "LTA001" missing from the check here:

else if (type == "LLM010" || type == "LLM011" || type == "LLM012" || type == "LTW001" || type == "LTW004"

Presumably there are other new lights that are also missing that I don't know of.

In general I believe that the approach of enumerating all product IDs here to determine their capabilities is going to cause this class on sins of omission to continue appearing as new products are created by Philips. Is there no way to query the lights to get their capabilities from the API so that a hard coded list like this isn't needed?

Getting errors messages when I try and run make(linux)

Describe the bug:
When I go to make it only gets to 18 percent then spits out errors something about output being truncated.

To Reproduce:
Steps to reproduce the behavior:
System manjaro Linux.

  1. clone repo
  2. cd hueplusplus
  3. mkdir build
  4. cd build
  5. cmake .. (Runs fine with no errors)
  6. make (getts to 18 percent then gives a bunch of errors I have tried multiple times on fresh clones of repo always the same.)

Expected behavior:
I expected the step 6 to finish without errors

Desktop (please complete the following information):

  • OS: Linux(manjaro)
  • Version NA(new)

Additional context
If it is me that is doing something wrong let me know I am happy to give more info if necessary.
Thankyou -BOB450

Console log/Error message:

[ 3%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/aria.c.o
[ 3%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/aesni.c.o
[ 3%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/arc4.c.o
[ 3%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/aes.c.o
[ 3%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/asn1parse.c.o
[ 3%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/asn1write.c.o
[ 3%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/base64.c.o
[ 7%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/bignum.c.o
[ 7%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/blowfish.c.o
[ 7%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/camellia.c.o
[ 7%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/ccm.c.o
[ 7%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/chacha20.c.o
[ 7%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/chachapoly.c.o
[ 11%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/cipher.c.o
[ 11%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/cipher_wrap.c.o
[ 11%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/cmac.c.o
[ 11%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/ctr_drbg.c.o
[ 11%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/des.c.o
[ 11%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/dhm.c.o
[ 14%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/ecdh.c.o
[ 14%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/ecdsa.c.o
[ 14%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/ecjpake.c.o
[ 14%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/ecp.c.o
[ 14%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/ecp_curves.c.o
[ 18%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/entropy.c.o
[ 18%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/entropy_poll.c.o
[ 18%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/error.c.o
[ 18%] Building C object lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/gcm.c.o
/home/user1/hueplusplus/lib/mbedtls/library/error.c: In function ‘mbedtls_strerror’:
/home/user1/hueplusplus/lib/mbedtls/library/error.c:921:47: error: ‘snprintf’ output may be truncated before the last format character [-Werror=format-truncation=]
921 | mbedtls_snprintf( buf, buflen, "%s", high_level_error_description );
| ^
In file included from /home/user1/hueplusplus/lib/mbedtls/library/error.c:29:
/home/user1/hueplusplus/lib/mbedtls/include/mbedtls/platform.h:76:41: note: ‘snprintf’ output 1 or more bytes (assuming 2) into a destination of size 1
76 | #define MBEDTLS_PLATFORM_STD_SNPRINTF snprintf /< The default \c snprintf function to use. */
/home/user1/hueplusplus/lib/mbedtls/include/mbedtls/platform.h:243:28: note: in expansion of macro ‘MBEDTLS_PLATFORM_STD_SNPRINTF’
243 | #define mbedtls_snprintf MBEDTLS_PLATFORM_STD_SNPRINTF
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/user1/hueplusplus/lib/mbedtls/library/error.c:921:13: note: in expansion of macro ‘mbedtls_snprintf’
921 | mbedtls_snprintf( buf, buflen, "%s", high_level_error_description );
| ^~~~~~~~~~~~~~~~
/home/user1/hueplusplus/lib/mbedtls/library/error.c:919:46: error: ‘UNKNOWN ERROR CODE (’ directive output truncated writing 20 bytes into a region of size 1 [-Werror=format-truncation=]
919 | mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", (unsigned int) use_ret );
| ~^~~~~~~~~~~~~~~~~~~
/home/user1/hueplusplus/lib/mbedtls/library/error.c:919:44: note: directive argument in the range [1, 65408]
919 | mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", (unsigned int) use_ret );
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /home/user1/hueplusplus/lib/mbedtls/library/error.c:29:
/home/user1/hueplusplus/lib/mbedtls/include/mbedtls/platform.h:76:41: note: ‘snprintf’ output 26 bytes into a destination of size 1
76 | #define MBEDTLS_PLATFORM_STD_SNPRINTF snprintf /
< The default \c snprintf function to use. */
/home/user1/hueplusplus/lib/mbedtls/include/mbedtls/platform.h:243:28: note: in expansion of macro ‘MBEDTLS_PLATFORM_STD_SNPRINTF’
243 | #define mbedtls_snprintf MBEDTLS_PLATFORM_STD_SNPRINTF
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/user1/hueplusplus/lib/mbedtls/library/error.c:919:13: note: in expansion of macro ‘mbedtls_snprintf’
919 | mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", (unsigned int) use_ret );
| ^~~~~~~~~~~~~~~~
/home/user1/hueplusplus/lib/mbedtls/library/error.c:958:43: error: ‘snprintf’ output may be truncated before the last format character [-Werror=format-truncation=]
958 | mbedtls_snprintf( buf, buflen, "%s", low_level_error_description );
| ^
In file included from /home/user1/hueplusplus/lib/mbedtls/library/error.c:29:
/home/user1/hueplusplus/lib/mbedtls/include/mbedtls/platform.h:76:41: note: ‘snprintf’ output 1 or more bytes (assuming 2) into a destination of size 1
76 | #define MBEDTLS_PLATFORM_STD_SNPRINTF snprintf /< The default \c snprintf function to use. */
/home/user1/hueplusplus/lib/mbedtls/include/mbedtls/platform.h:243:28: note: in expansion of macro ‘MBEDTLS_PLATFORM_STD_SNPRINTF’
243 | #define mbedtls_snprintf MBEDTLS_PLATFORM_STD_SNPRINTF
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/user1/hueplusplus/lib/mbedtls/library/error.c:958:9: note: in expansion of macro ‘mbedtls_snprintf’
958 | mbedtls_snprintf( buf, buflen, "%s", low_level_error_description );
| ^~~~~~~~~~~~~~~~
/home/user1/hueplusplus/lib/mbedtls/library/error.c:956:42: error: ‘UNKNOWN ERROR CODE (’ directive output truncated writing 20 bytes into a region of size 1 [-Werror=format-truncation=]
956 | mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", (unsigned int) use_ret );
| ~^~~~~~~~~~~~~~~~~~~
/home/user1/hueplusplus/lib/mbedtls/library/error.c:956:40: note: directive argument in the range [1, 2147418239]
956 | mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", (unsigned int) use_ret );
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /home/user1/hueplusplus/lib/mbedtls/library/error.c:29:
/home/user1/hueplusplus/lib/mbedtls/include/mbedtls/platform.h:76:41: note: ‘snprintf’ output between 26 and 30 bytes into a destination of size 1
76 | #define MBEDTLS_PLATFORM_STD_SNPRINTF snprintf /
< The default \c snprintf function to use. */
/home/user1/hueplusplus/lib/mbedtls/include/mbedtls/platform.h:243:28: note: in expansion of macro ‘MBEDTLS_PLATFORM_STD_SNPRINTF’
243 | #define mbedtls_snprintf MBEDTLS_PLATFORM_STD_SNPRINTF
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/user1/hueplusplus/lib/mbedtls/library/error.c:956:9: note: in expansion of macro ‘mbedtls_snprintf’
956 | mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", (unsigned int) use_ret );
| ^~~~~~~~~~~~~~~~
cc1: all warnings being treated as errors
make[2]: *** [lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/build.make:440: lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/error.c.o] Error 1
make[2]: *** Waiting for unfinished jobs....
make[1]: *** [CMakeFiles/Makefile2:911: lib/mbedtls/library/CMakeFiles/mbedcrypto.dir/all] Error 2
make: *** [Makefile:136: all] Error 2

Socket being recreated on every network request for every light

I was debugging an issue where my software using hueplusplus stopped working after around a day without fail, running strace on the binary I saw that hueplusplus is repeatedly creating and connecting a socket for each message sent.

After some digging, I found:

int socketFD = socket(AF_INET, SOCK_STREAM, 0);

Is it an intentional design decision to create a socket connection for each message? This seems inefficient to me, there's overhead associated with opening a socket and TCP benefits from keeping the socket open due to slow start behaviour of congestion control. Would it break anything if the socket was reused between requests?

Edit, also I wouldn't be surprised if the bridge was none too happy about being hammered with new TCP connections due to this...

Check whether extended strategies are needed for Hue Color Lights

Check whether extended strategies are needed for Hue Color Lights, because it is not clear, if these lights really have ct mode or not. Also there is no information regarding this in the HueAPI documentation.

This regards light types LST001, LLC006, LLC007, LLC010, LLC011, LLC012 and LLC013.

Switch license from GNU GPLv3 to GNU LGPLv3

As the current license is very strong and does not allow to use the HuePlusPlus library when linking it in another project without dislcosing their source, I am opening this issue to ask all contributors if they approve to change the license of the library.

By that I mean @sieren, @Wulkop, @Jojo-1000 and @EmilyBjoerk.
Please write a comment stating whether you are okay with the license change and give me the right to do so.

I hope that this change will make this library more useful to a wider range of people.

json.exception.parse_error.101 when getting access to lights

Describe the bug:
I created a Bridge object with the IP, Port and username of my bridge. Now I want to get access to the lights of my Hue-system, where a json parse error is thrown.

To Reproduce:
I used some of the code-snippets of the getting-started section and the BridgeSetup.cpp example:

#include <algorithm>
#include <iostream>

#include <hueplusplus/Bridge.h>

#ifdef _MSC_VER
#include <hueplusplus/WinHttpHandler.h>

using SystemHttpHandler = hueplusplus::WinHttpHandler;

#else
#include <hueplusplus/LinHttpHandler.h>

using SystemHttpHandler = hueplusplus::LinHttpHandler;

#endif

namespace hue = hueplusplus;

// Connects to a bridge and returns it.
hue::Bridge connectToBridge()
{
    auto handler = std::make_shared<hueplusplus::WinHttpHandler>();
    hueplusplus::Bridge bridge("MyIP", 80, "<MyUsername>", handler);

    return bridge;
}
int main(int argc, char** argv)
{
    try
    {
        hue::Bridge hue = connectToBridge();
        std::cout << "Connected to bridge. IP: " << hue.getBridgeIP() << ", username: " << hue.getUsername() << '\n';
        std::vector<hueplusplus::Light> lights = hue.lights().getAll();   
    }
    catch (nlohmann::json::parse_error& e)
    {
        std::cout << e.what() << '\n';

    }

    std::cout << "Press enter to exit\n";
    std::cin.get();

    return 0;
}

Expected behavior:
I want to get the vector of the lights in my Hue-system

Console log/Error message:
[json.exception.parse_error.101] parse error at line 1, column 1: syntax error while parsing value - invalid literal; last read: '<'

Desktop (please complete the following information):

  • OS: Windows 11
  • Visual Studio 2022

Issues with using this in a container class

I love the design so far, but have some questions.

  1. Because the Hue object does not have a default constructor, I cannot create a member variable of type Hue very easily. Do you have thoughts about how to work around this? I would suggest changing the library to return pointers to a Hue object, to allow for both bridge IP known AND bridge IP not known situations. Then the member variable could just be a pointer to the Hue object, and created as needed either with FindBridge() or Hue(ip, key, handler). But I get that this would be a departure in design.
  2. I can't seem to find a way to figure out how to track the connection state. Is there a way to figure out the connection is lost or to check if the connection is still good?

I'm working on a RPi touch screen for hue bulbs, and this library solves a lot of problems, specifically because it's up to date and seemingly very easy to use. But I don't see a way to figure out I have to restart the connection and I need a way to maintain the Hue object in class that lets me thread the Hue calls so they don't block the Qt UI.

Thank you.

Improving useful command rate of hueplusplus

Note: I'm filing this bug as general feedback on the API design that you may want to consider (or ignore, up to you). I've already hacked together a fix in my fork to make my application work. Suggested fixes could include a parameter to control refresh behaviour or a configurable staleness tolerance on the last refresh before refreshState() is allowed and possibly making refreshState() always refresh all lights through the appropriate HTTP endpoint.

Related to #64 as I was searching for ways to fix the crash I was experiencing I found that at some point I didn't get a valid response from the hub and an instance of std::system_error was thrown because the response from the bridge wasn't valid (most likely it was a 429 response because of a high amount of connections made (as an aside I'm not sure if throwing is appropriate for a response that is fully expected and not a bug, but my fork is old by now and that might have changed since then).

What was surprising to me was to find that light.refreshState() is called eventually from Ligst::setX functions, e.g. here:

In my usage like so:

int main() {
  auto bridge = find_bridge();

  while (true) {
    try {
      auto t = std::time(nullptr);
      auto* tm = std::localtime(&t);
      auto day_hour = tm->tm_hour + tm->tm_min / real{60};
      auto point = schedule_lerp(schedule, day_hour);

      for (auto& light_ref : bridge.getAllLights()) {
        auto& light = light_ref.get();
        if (light.isOn()) {
          light.setBrightness(c_max_brightness * point.lum);
          light.setColorTemperature(light.KelvinToMired(point.ct));
        }
      }
    } catch (const std::system_error& err){
      std::cout<<"Caught std::system_error, what(): " << err.what()<<std::endl;
    }
    std::this_thread::sleep_for(5s);
  }
}

with 6 lights I ended up calling refreshState() once in getAllLights to update the state for all lights once, then three times for each active light (in isOn() non const, setBrightness and setColorTemperature). This results in 19 calls to GET requests to the hub out of which only the first one in getAllLights was actually needed. Adding the two setX calls per enabled light, this results in a total of 31 connections to the hub in a burst every 5 seconds or 6.2 connections per second on average... When in reality all that was needed was 7 connections (1+2*n) (or 4 connections (1+n) if the API would support writing Brightness and Colour Temperature in one request)...

I have fixed this for myself in my branch by simply removing calls to refreshState() from the various Strategy classes and I'm hoping that this will improve scalability and responsiveness of my application.

Add Philips LCA003 and LCB001 and issues with color conversion

I just bought a Hue bulb to use for developing with this library and it appears to be unsupported. The bulb model shows up as "LCA003". It is a white+color bulb with Bluetooth and ZigBee that I bought at Home Depot. I modified Hue.cpp to add LCA003 to the group starting with LCT001 and it works, but I'm not sure if this is the right place for it (specifically what ColorType it uses).

Performance for multiple attributes (brightness, colour loop & colour) for multiple lamps is a bit slow

I am really pleased that I found this library. It has exactly the functionality I needed for my home automation system.
However when I switch on the the television, I also want to switch on 6 lamps dimmed with different colours to colour loop.
This takes a couple of seconds on my raspberry pi.

To make it go a bit faster I have written a new HueLightHelper class which inherits from HueLight.
This sends a single JSON message to each lamp with brightness, colour and colour loop in the same message.
This roughly halves the time to complete.

Rather than a single call to transfer information, multiple calls are required to initialise, set up each attribute and finally send each message. It's harder to use than the original information, but I thought the performance improvement worthwhile.

My C++ is a bit rusty as I haven't done any commercially for 20 years, so you might feel the need to polish the code, but I thing the idea is sound!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.