hueplusplus  1.0.0
Utils.h
Go to the documentation of this file.
1 
23 #ifndef INCLUDE_HUEPLUSPLUS_UTILS_H
24 #define INCLUDE_HUEPLUSPLUS_UTILS_H
25 
26 #include "json/json.hpp"
27 
28 namespace hueplusplus
29 {
31 namespace utils
32 {
33 namespace detail
34 {
35 // Forward declaration
36 template <typename KeyT, typename... Paths>
37 nlohmann::json safeGetMemberHelper(const nlohmann::json& json, std::size_t index, Paths&&... otherPaths);
38 
39 inline nlohmann::json safeGetMemberHelper(const nlohmann::json& json)
40 {
41  return json;
42 }
43 
44 template <typename KeyT, typename... Paths,
45  std::enable_if_t<!std::is_integral<std::remove_reference_t<KeyT>>::value>* = nullptr>
46 nlohmann::json safeGetMemberHelper(const nlohmann::json& json, KeyT&& key, Paths&&... otherPaths)
47 {
48  auto memberIt = json.find(std::forward<KeyT>(key));
49  if (memberIt == json.end())
50  {
51  return nullptr;
52  }
53  return safeGetMemberHelper(*memberIt, std::forward<Paths>(otherPaths)...);
54 }
55 
56 // Needs to be after the other safeGetMemberHelper, otherwise another forward declaration is needed
57 template <typename... Paths>
58 nlohmann::json safeGetMemberHelper(const nlohmann::json& json, std::size_t index, Paths&&... otherPaths)
59 {
60  if (!json.is_array() || json.size() <= index)
61  {
62  return nullptr;
63  }
64  return safeGetMemberHelper(json[index], std::forward<Paths>(otherPaths)...);
65 }
66 } // namespace detail
67 
74 bool validatePUTReply(const std::string& path, const nlohmann::json& request, const nlohmann::json& reply);
75 
76 bool validateReplyForLight(const nlohmann::json& request, const nlohmann::json& reply, int lightId);
77 
81 inline bool floatEquals(float lhs, float rhs)
82 {
83  return std::abs(lhs - rhs) <= 1E-4f;
84 }
85 
91 template <typename... Paths>
92 nlohmann::json safeGetMember(const nlohmann::json& json, Paths&&... paths)
93 {
94  return detail::safeGetMemberHelper(json, std::forward<Paths>(paths)...);
95 }
96 
97 } // namespace utils
98 
99 namespace detail
100 {
106 template <typename T>
107 class MakeCopyable : public T
108 {
109 public:
110  // Make copy constructor and assignment operator public
111  using T::T;
112  using T::operator=;
113 };
114 } // namespace detail
115 } // namespace hueplusplus
116 
117 #endif
Namespace for the hueplusplus library.
Definition: Action.h:27
bool validateReplyForLight(const nlohmann::json &request, const nlohmann::json &reply, int lightId)
Definition: Utils.cpp:89
bool validatePUTReply(const std::string &path, const nlohmann::json &request, const nlohmann::json &reply)
Function for validating that a request was executed correctly.
Definition: Utils.cpp:31
bool floatEquals(float lhs, float rhs)
Checks equality to 4 decimal places.
Definition: Utils.h:81
nlohmann::json safeGetMember(const nlohmann::json &json, Paths &&... paths)
Returns the object/array member or null if it does not exist.
Definition: Utils.h:92