-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
TuyaApi.cs
243 lines (224 loc) · 9.91 KB
/
TuyaApi.cs
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace com.clusterrr.TuyaNet
{
/// <summary>
/// Provides access to Tuya Cloud API.
/// </summary>
public class TuyaApi
{
private readonly Region region;
private readonly string accessId;
private readonly string apiSecret;
private readonly HttpClient httpClient;
private TuyaToken token = null;
private DateTime tokenTime = new DateTime();
public string TokenUid { get => token?.Uid;}
private class TuyaToken
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("expire_time")]
public int ExpireTime { get; set; }
[JsonProperty("refresh_token")]
public string RefreshToken { get; set; }
[JsonProperty("uid")]
public string Uid { get; set; }
}
/// <summary>
/// Creates a new instance of the TuyaApi class.
/// </summary>
/// <param name="region">Region of server.</param>
/// <param name="accessId">Access ID/Client ID from https://iot.tuya.com/ .</param>
/// <param name="apiSecret">API secret from https://iot.tuya.com/ .</param>
public TuyaApi(Region region, string accessId, string apiSecret)
{
this.region = region;
this.accessId = accessId;
this.apiSecret = apiSecret;
httpClient = new HttpClient();
}
/// <summary>
/// Region of server.
/// </summary>
public enum Region
{
China,
WesternAmerica,
EasternAmerica,
CentralEurope,
WesternEurope,
India
}
/// <summary>
/// Request method.
/// </summary>
public enum Method
{
GET,
POST,
PUT,
DELETE
}
private static string RegionToHost(Region region)
{
string urlHost = null;
switch (region)
{
case Region.China:
urlHost = "openapi.tuyacn.com";
break;
case Region.WesternAmerica:
urlHost = "openapi.tuyaus.com";
break;
case Region.EasternAmerica:
urlHost = "openapi-ueaz.tuyaus.com";
break;
case Region.CentralEurope:
urlHost = "openapi.tuyaeu.com";
break;
case Region.WesternEurope:
urlHost = "openapi-weaz.tuyaeu.com";
break;
case Region.India:
urlHost = "openapi.tuyain.com";
break;
}
return urlHost;
}
/// <summary>
/// Request to official API.
/// </summary>
/// <param name="uri">Method URI.</param>
/// <param name="body">Body of request if any.</param>
/// <param name="headers">Additional headers.</param>
/// <param name="noToken">Execute query without token.</param>
/// <param name="forceTokenRefresh">Refresh access token even it's not expired.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>JSON string with response.</returns>
public async Task<string> RequestAsync(Method method, string uri, string body = null, Dictionary<string, string> headers = null, bool noToken = false, bool forceTokenRefresh = false, CancellationToken cancellationToken = default)
{
while (uri.StartsWith("/")) uri = uri.Substring(1);
var urlHost = RegionToHost(region);
var url = new Uri($"https://{urlHost}/{uri}");
var now = (DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalMilliseconds.ToString("0");
string headersStr = "";
if (headers == null)
{
headers = new Dictionary<string, string>();
}
else
{
headersStr = string.Concat(headers.Select(kv => $"{kv.Key}:{kv.Value}\n"));
headers.Add("Signature-Headers", string.Join(":", headers.Keys));
}
string payload = accessId;
if (noToken)
{
payload += now;
headers["secret"] = apiSecret;
}
else
{
await RefreshAccessTokenAsync(forceTokenRefresh, cancellationToken);
payload += token.AccessToken + now;
}
using (var sha256 = SHA256.Create())
{
payload += $"{method}\n" +
string.Concat(sha256.ComputeHash(Encoding.UTF8.GetBytes(body ?? "")).Select(b => $"{b:x2}")) + '\n' +
headersStr + '\n' +
url.PathAndQuery;
}
string signature;
using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(apiSecret)))
{
signature = string.Concat(hmac.ComputeHash(Encoding.UTF8.GetBytes(payload)).Select(b => $"{b:X2}"));
}
headers["client_id"] = accessId;
headers["sign"] = signature;
headers["t"] = now;
headers["sign_method"] = "HMAC-SHA256";
if (!noToken)
headers["access_token"] = token.AccessToken;
var httpRequestMessage = new HttpRequestMessage
{
Method = method switch
{
Method.GET => HttpMethod.Get,
Method.POST => HttpMethod.Post,
Method.PUT => HttpMethod.Put,
Method.DELETE => HttpMethod.Delete,
_ => throw new NotSupportedException($"Unknow method - {method}")
},
RequestUri = url,
};
foreach (var h in headers)
httpRequestMessage.Headers.Add(h.Key, h.Value);
if (body != null)
httpRequestMessage.Content = new StringContent(body, Encoding.UTF8, "application/json");
using (var response = await httpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false))
{
var responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var root = JObject.Parse(responseString);
var success = root.GetValue("success").Value<bool>();
if (!success) throw new InvalidDataException(root.ContainsKey("msg") ? root.GetValue("msg").Value<string>() : null);
var result = root.GetValue("result").ToString();
return result;
}
}
/// <summary>
/// Request access token if it's expired or not requested yet.
/// </summary>
private async Task RefreshAccessTokenAsync(bool force = false, CancellationToken cancellationToken = default)
{
if (force || (token == null) || (tokenTime.AddSeconds(token.ExpireTime) >= DateTime.Now)
// For some weird reason token expires sooner than it should
|| (tokenTime.AddMinutes(30) >= DateTime.Now))
{
var uri = "v1.0/token?grant_type=1";
var response = await RequestAsync(Method.GET, uri, noToken: true, cancellationToken: cancellationToken);
token = JsonConvert.DeserializeObject<TuyaToken>(response);
tokenTime = DateTime.Now;
}
}
/// <summary>
/// Requests info about device by it's ID.
/// </summary>
/// <param name="deviceId">Device ID.</param>
/// <param name="forceTokenRefresh">Refresh access token even it's not expired.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Device info.</returns>
public async Task<TuyaDeviceApiInfo> GetDeviceInfoAsync(string deviceId, bool forceTokenRefresh = false, CancellationToken cancellationToken = default)
{
var uri = $"v1.0/devices/{deviceId}";
var response = await RequestAsync(Method.GET, uri, forceTokenRefresh: forceTokenRefresh, cancellationToken: cancellationToken);
var device = JsonConvert.DeserializeObject<TuyaDeviceApiInfo>(response);
return device;
}
/// <summary>
/// Requests info about all registered devices, requires ID of any registered device.
/// </summary>
/// <param name="anyDeviceId">ID of any registered device.</param>
/// <param name="forceTokenRefresh">Refresh access token even it's not expired.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Array of devices info.</returns>
public async Task<TuyaDeviceApiInfo[]> GetAllDevicesInfoAsync(string anyDeviceId, bool forceTokenRefresh = false, CancellationToken cancellationToken = default)
{
var userId = (await GetDeviceInfoAsync(anyDeviceId, forceTokenRefresh: forceTokenRefresh, cancellationToken: cancellationToken)).UserId;
var uri = $"v1.0/users/{userId}/devices";
var response = await RequestAsync(Method.GET, uri, forceTokenRefresh: false, cancellationToken: cancellationToken); // Token already refreshed
var devices = JsonConvert.DeserializeObject<TuyaDeviceApiInfo[]>(response);
return devices;
}
}
}