-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSmartThingsManager.cpp
More file actions
213 lines (178 loc) · 6.47 KB
/
SmartThingsManager.cpp
File metadata and controls
213 lines (178 loc) · 6.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
#include "SmartThingsManager.h"
#include "Config.h"
#include <Preferences.h>
#include <HTTPClient.h>
#include "base64.h"
#include "Asserts.h"
namespace SA
{
String GetOrCreateToken(NetworkClientSecure& client)
{
const char* tokenKey = "token";
const char* refreshTokenKey = "refreshToken";
const char* expirationTimeKey = "expirationTime";
Preferences prefs;
prefs.begin("SmartArduino");
ON_SCOPE_EXIT( prefs.end(); );
const String expirationTimeStr = prefs.getString(expirationTimeKey, "0");
time_t expirationTime = std::stoll(expirationTimeStr.c_str());
const time_t currentTime = time(nullptr);
const time_t timeBeforeRefresh = 60 * 10;
if (currentTime + timeBeforeRefresh > expirationTime)
{
Serial.println("Token has expired, generating new one...");
const char* url = "https://api.smartthings.com/oauth/token";
HTTPClient https;
if (!https.begin(client, url))
{
Serial.printf("[%hs] Unable to connect to refresh token\n", __FUNCTION__);
return "";
}
ON_SCOPE_EXIT( https.end(); );
String authBase64;
{
char buffer[256];
snprintf(buffer, sizeof(buffer), "%s:%s", SA::Config::c_clientID, SA::Config::c_clientSecret);
authBase64 = base64::encode(buffer);
}
https.addHeader("Authorization", "Basic " + authBase64);
https.addHeader("Content-Type", "application/x-www-form-urlencoded");
char body[256];
snprintf(body, sizeof(body), "grant_type=refresh_token&client_id=%s&refresh_token=%s", SA::Config::c_clientID, prefs.getString(refreshTokenKey, SA::Config::c_initialRefreshToken).c_str());
const int httpCode = https.POST(body);
if (httpCode != HTTP_CODE_OK)
{
Serial.printf("[%hs] POST failed, error: %d | %s | %s\n", __FUNCTION__, httpCode, https.errorToString(httpCode).c_str(), https.getString().c_str());
}
const String result = https.getString();
const StringDict dict(result.c_str(), "/root/");
const auto newToken = dict.GetValue<const char*>("access_token");
ASSERT(newToken);
Serial.printf("NewToken: %s\n", *newToken);
prefs.putString(tokenKey, *newToken);
const auto newRefreshToken = dict.GetValue<const char*>("refresh_token");
ASSERT(newRefreshToken);
Serial.printf("NewRefreshToken: %s\n", *newRefreshToken);
prefs.putString(refreshTokenKey, *newRefreshToken);
{
const auto lifetime = dict.GetValue<int>("expires_in");
ASSERT(lifetime);
char buffer[256];
snprintf(buffer, sizeof(buffer), "%" PRId64, currentTime + *lifetime);
prefs.putString(expirationTimeKey, buffer);
}
}
else
{
const time_t remainingSeconds = expirationTime - (currentTime + timeBeforeRefresh);
const time_t hours = remainingSeconds / 3600;
const time_t minutes = remainingSeconds / 60 - hours * 60;
const time_t seconds = remainingSeconds - hours * 3600 - minutes * 60;
//Serial.printf("Token is valid for the next %" PRId64 "h %" PRId64 "m %" PRId64 "s \n", hours, minutes, seconds);
}
return prefs.getString(tokenKey, "");
}
SmartThingsManager::Cache& SmartThingsManager::GetCache()
{
if (!m_cache.has_value())
{
m_cache = Cache();
m_cache->m_client.setCACert(SA::Config::c_smartThingsRootCA);
m_cache->m_authToken = GetOrCreateToken(m_cache->m_client);
}
return *m_cache;
}
void SmartThingsManager::SendCommand(const char* deviceID, const char* component, const char* capability, const char* command)
{
HTTPClient https;
{
char urlBuffer[256];
snprintf(urlBuffer, sizeof(urlBuffer), "%s/devices/%s/commands", Config::c_smartThingsURL, deviceID);
if (!https.begin(GetClient(), urlBuffer))
{
Serial.printf("[%hs] Unable to connect to commands\n", __FUNCTION__);
return;
}
}
ON_SCOPE_EXIT( https.end(); );
{
char headerBuffer[256];
snprintf(headerBuffer, sizeof(headerBuffer), "Bearer %s", GetToken());
https.addHeader("Authorization", headerBuffer);
}
https.addHeader("Content-Type", "application/json");
const char* body = R"rl(
{
"commands": [
{
"component": "%s",
"capability": "%s",
"command": "%s"
}
]
}
)rl";
char bodyBuffer[512];
snprintf(bodyBuffer, sizeof(bodyBuffer), body, component, capability, command);
const int httpCode = https.POST(bodyBuffer);
if (httpCode != HTTP_CODE_OK)
{
Serial.printf("[%hs] POST failed, error: %d | %s | %s\n", __FUNCTION__, httpCode, https.errorToString(httpCode).c_str(), https.getString().c_str());
}
}
StringDict SmartThingsManager::GetDeviceStatus(const char* deviceID, bool forceDataRefresh)
{
HTTPClient https;
if (forceDataRefresh)
{
RefreshDevice(deviceID);
delay(100);
}
char buffer[256];
snprintf(buffer, sizeof(buffer), "%s/devices/%s/status", Config::c_smartThingsURL, deviceID);
if (!https.begin(GetClient(), buffer))
{
Serial.printf("[%hs] Unable to connect to status\n", __FUNCTION__);
return {};
}
{
char headerBuffer[256];
snprintf(headerBuffer, sizeof(headerBuffer), "Bearer %s", GetToken());
https.addHeader("Authorization", headerBuffer);
}
https.addHeader("Content-Type", "application/json");
ON_SCOPE_EXIT( https.end(); );
const int httpCode = https.GET();
if (httpCode != HTTP_CODE_OK)
{
Serial.printf("[%hs] GET failed, error: %d | %s | %s\n", __FUNCTION__, httpCode, https.errorToString(httpCode).c_str(), https.getString().c_str());
return {};
}
String payload = https.getString();
return StringDict(payload.c_str(), "/root/components/main/");
}
void SmartThingsManager::RefreshDevice(const char* deviceID)
{
SendCommand(deviceID, "main", "refresh", "refresh");
}
void SmartThingsManager::SetSwitchValue(const char* deviceID, bool value)
{
SendCommand(deviceID, "main", "switch", value ? "on" : "off");
}
bool SmartThingsManager::IsSwitchEnabled(const char* deviceID, bool forceDataRefresh)
{
if (auto switchValue = GetDeviceValue<bool>(deviceID, "switch/switch/value", forceDataRefresh))
{
return *switchValue;
}
return false;
}
NetworkClientSecure& SmartThingsManager::GetClient()
{
return GetCache().m_client;
}
const char* SmartThingsManager::GetToken()
{
return GetCache().m_authToken.c_str();
}
}