@fredsocial/homebridge-tplink-tapo 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +105 -0
  3. package/config.schema.json +347 -0
  4. package/lib/accessory-information.d.ts +4 -0
  5. package/lib/accessory-information.d.ts.map +1 -0
  6. package/lib/accessory-information.js +26 -0
  7. package/lib/accessory-information.js.map +1 -0
  8. package/lib/characteristics/amperes.d.ts +4 -0
  9. package/lib/characteristics/amperes.d.ts.map +1 -0
  10. package/lib/characteristics/amperes.js +15 -0
  11. package/lib/characteristics/amperes.js.map +1 -0
  12. package/lib/characteristics/default-characteristic.d.ts +3 -0
  13. package/lib/characteristics/default-characteristic.d.ts.map +1 -0
  14. package/lib/characteristics/default-characteristic.js +19 -0
  15. package/lib/characteristics/default-characteristic.js.map +1 -0
  16. package/lib/characteristics/index.d.ts +3 -0
  17. package/lib/characteristics/index.d.ts.map +1 -0
  18. package/lib/characteristics/index.js +25 -0
  19. package/lib/characteristics/index.js.map +1 -0
  20. package/lib/characteristics/kilowatt-hours.d.ts +4 -0
  21. package/lib/characteristics/kilowatt-hours.d.ts.map +1 -0
  22. package/lib/characteristics/kilowatt-hours.js +15 -0
  23. package/lib/characteristics/kilowatt-hours.js.map +1 -0
  24. package/lib/characteristics/kilowatt-volt-ampere-hour.d.ts +4 -0
  25. package/lib/characteristics/kilowatt-volt-ampere-hour.d.ts.map +1 -0
  26. package/lib/characteristics/kilowatt-volt-ampere-hour.js +16 -0
  27. package/lib/characteristics/kilowatt-volt-ampere-hour.js.map +1 -0
  28. package/lib/characteristics/types.d.ts +7 -0
  29. package/lib/characteristics/types.d.ts.map +1 -0
  30. package/lib/characteristics/types.js +4 -0
  31. package/lib/characteristics/types.js.map +1 -0
  32. package/lib/characteristics/volt-amperes.d.ts +4 -0
  33. package/lib/characteristics/volt-amperes.d.ts.map +1 -0
  34. package/lib/characteristics/volt-amperes.js +15 -0
  35. package/lib/characteristics/volt-amperes.js.map +1 -0
  36. package/lib/characteristics/volts.d.ts +4 -0
  37. package/lib/characteristics/volts.d.ts.map +1 -0
  38. package/lib/characteristics/volts.js +15 -0
  39. package/lib/characteristics/volts.js.map +1 -0
  40. package/lib/characteristics/watts.d.ts +4 -0
  41. package/lib/characteristics/watts.d.ts.map +1 -0
  42. package/lib/characteristics/watts.js +15 -0
  43. package/lib/characteristics/watts.js.map +1 -0
  44. package/lib/config.d.ts +180 -0
  45. package/lib/config.d.ts.map +1 -0
  46. package/lib/config.js +167 -0
  47. package/lib/config.js.map +1 -0
  48. package/lib/homekit-device/bulb.d.ts +41 -0
  49. package/lib/homekit-device/bulb.d.ts.map +1 -0
  50. package/lib/homekit-device/bulb.js +307 -0
  51. package/lib/homekit-device/bulb.js.map +1 -0
  52. package/lib/homekit-device/create.d.ts +11 -0
  53. package/lib/homekit-device/create.d.ts.map +1 -0
  54. package/lib/homekit-device/create.js +18 -0
  55. package/lib/homekit-device/create.js.map +1 -0
  56. package/lib/homekit-device/index.d.ts +33 -0
  57. package/lib/homekit-device/index.d.ts.map +1 -0
  58. package/lib/homekit-device/index.js +120 -0
  59. package/lib/homekit-device/index.js.map +1 -0
  60. package/lib/homekit-device/plug.d.ts +43 -0
  61. package/lib/homekit-device/plug.d.ts.map +1 -0
  62. package/lib/homekit-device/plug.js +244 -0
  63. package/lib/homekit-device/plug.js.map +1 -0
  64. package/lib/index.d.ts +4 -0
  65. package/lib/index.d.ts.map +1 -0
  66. package/lib/index.js +10 -0
  67. package/lib/index.js.map +1 -0
  68. package/lib/platform.d.ts +59 -0
  69. package/lib/platform.d.ts.map +1 -0
  70. package/lib/platform.js +301 -0
  71. package/lib/platform.js.map +1 -0
  72. package/lib/settings.d.ts +3 -0
  73. package/lib/settings.d.ts.map +1 -0
  74. package/lib/settings.js +6 -0
  75. package/lib/settings.js.map +1 -0
  76. package/lib/tapo/custom-characteristics/currentConsumptionCharacteristic.d.ts +3 -0
  77. package/lib/tapo/custom-characteristics/currentConsumptionCharacteristic.d.ts.map +1 -0
  78. package/lib/tapo/custom-characteristics/currentConsumptionCharacteristic.js +21 -0
  79. package/lib/tapo/custom-characteristics/currentConsumptionCharacteristic.js.map +1 -0
  80. package/lib/tapo/custom-characteristics/default-characteristic.d.ts +3 -0
  81. package/lib/tapo/custom-characteristics/default-characteristic.d.ts.map +1 -0
  82. package/lib/tapo/custom-characteristics/default-characteristic.js +19 -0
  83. package/lib/tapo/custom-characteristics/default-characteristic.js.map +1 -0
  84. package/lib/tapo/custom-characteristics/index.d.ts +3 -0
  85. package/lib/tapo/custom-characteristics/index.d.ts.map +1 -0
  86. package/lib/tapo/custom-characteristics/index.js +17 -0
  87. package/lib/tapo/custom-characteristics/index.js.map +1 -0
  88. package/lib/tapo/custom-characteristics/resetConsumptionCharacteristic.d.ts +3 -0
  89. package/lib/tapo/custom-characteristics/resetConsumptionCharacteristic.d.ts.map +1 -0
  90. package/lib/tapo/custom-characteristics/resetConsumptionCharacteristic.js +20 -0
  91. package/lib/tapo/custom-characteristics/resetConsumptionCharacteristic.js.map +1 -0
  92. package/lib/tapo/custom-characteristics/totalConsumptionCharacteristic.d.ts +3 -0
  93. package/lib/tapo/custom-characteristics/totalConsumptionCharacteristic.d.ts.map +1 -0
  94. package/lib/tapo/custom-characteristics/totalConsumptionCharacteristic.js +21 -0
  95. package/lib/tapo/custom-characteristics/totalConsumptionCharacteristic.js.map +1 -0
  96. package/lib/tapo/homekit-device/types.d.ts +30 -0
  97. package/lib/tapo/homekit-device/types.d.ts.map +1 -0
  98. package/lib/tapo/homekit-device/types.js +3 -0
  99. package/lib/tapo/homekit-device/types.js.map +1 -0
  100. package/lib/tapo/platform.d.ts +14 -0
  101. package/lib/tapo/platform.d.ts.map +1 -0
  102. package/lib/tapo/platform.js +3 -0
  103. package/lib/tapo/platform.js.map +1 -0
  104. package/lib/tapo/platformL510EAccessory.d.ts +31 -0
  105. package/lib/tapo/platformL510EAccessory.d.ts.map +1 -0
  106. package/lib/tapo/platformL510EAccessory.js +146 -0
  107. package/lib/tapo/platformL510EAccessory.js.map +1 -0
  108. package/lib/tapo/platformL520EAccessory.d.ts +42 -0
  109. package/lib/tapo/platformL520EAccessory.d.ts.map +1 -0
  110. package/lib/tapo/platformL520EAccessory.js +205 -0
  111. package/lib/tapo/platformL520EAccessory.js.map +1 -0
  112. package/lib/tapo/platformL530Accessory.d.ts +84 -0
  113. package/lib/tapo/platformL530Accessory.d.ts.map +1 -0
  114. package/lib/tapo/platformL530Accessory.js +439 -0
  115. package/lib/tapo/platformL530Accessory.js.map +1 -0
  116. package/lib/tapo/platformP100Accessory.d.ts +23 -0
  117. package/lib/tapo/platformP100Accessory.d.ts.map +1 -0
  118. package/lib/tapo/platformP100Accessory.js +72 -0
  119. package/lib/tapo/platformP100Accessory.js.map +1 -0
  120. package/lib/tapo/platformP110Accessory.d.ts +39 -0
  121. package/lib/tapo/platformP110Accessory.d.ts.map +1 -0
  122. package/lib/tapo/platformP110Accessory.js +146 -0
  123. package/lib/tapo/platformP110Accessory.js.map +1 -0
  124. package/lib/tapo/platformTPLinkAccessory.d.ts +29 -0
  125. package/lib/tapo/platformTPLinkAccessory.d.ts.map +1 -0
  126. package/lib/tapo/platformTPLinkAccessory.js +132 -0
  127. package/lib/tapo/platformTPLinkAccessory.js.map +1 -0
  128. package/lib/tapo/utils/energyUsage.d.ts +4 -0
  129. package/lib/tapo/utils/energyUsage.d.ts.map +1 -0
  130. package/lib/tapo/utils/energyUsage.js +8 -0
  131. package/lib/tapo/utils/energyUsage.js.map +1 -0
  132. package/lib/tapo/utils/l510e.d.ts +17 -0
  133. package/lib/tapo/utils/l510e.d.ts.map +1 -0
  134. package/lib/tapo/utils/l510e.js +47 -0
  135. package/lib/tapo/utils/l510e.js.map +1 -0
  136. package/lib/tapo/utils/l520e.d.ts +20 -0
  137. package/lib/tapo/utils/l520e.d.ts.map +1 -0
  138. package/lib/tapo/utils/l520e.js +65 -0
  139. package/lib/tapo/utils/l520e.js.map +1 -0
  140. package/lib/tapo/utils/l530.d.ts +22 -0
  141. package/lib/tapo/utils/l530.d.ts.map +1 -0
  142. package/lib/tapo/utils/l530.js +135 -0
  143. package/lib/tapo/utils/l530.js.map +1 -0
  144. package/lib/tapo/utils/newTpLinkCipher.d.ts +22 -0
  145. package/lib/tapo/utils/newTpLinkCipher.d.ts.map +1 -0
  146. package/lib/tapo/utils/newTpLinkCipher.js +88 -0
  147. package/lib/tapo/utils/newTpLinkCipher.js.map +1 -0
  148. package/lib/tapo/utils/p100.d.ts +117 -0
  149. package/lib/tapo/utils/p100.d.ts.map +1 -0
  150. package/lib/tapo/utils/p100.js +665 -0
  151. package/lib/tapo/utils/p100.js.map +1 -0
  152. package/lib/tapo/utils/p110.d.ts +16 -0
  153. package/lib/tapo/utils/p110.d.ts.map +1 -0
  154. package/lib/tapo/utils/p110.js +68 -0
  155. package/lib/tapo/utils/p110.js.map +1 -0
  156. package/lib/tapo/utils/powerUsage.d.ts +7 -0
  157. package/lib/tapo/utils/powerUsage.d.ts.map +1 -0
  158. package/lib/tapo/utils/powerUsage.js +10 -0
  159. package/lib/tapo/utils/powerUsage.js.map +1 -0
  160. package/lib/tapo/utils/tpLinkCipher.d.ts +12 -0
  161. package/lib/tapo/utils/tpLinkCipher.d.ts.map +1 -0
  162. package/lib/tapo/utils/tpLinkCipher.js +35 -0
  163. package/lib/tapo/utils/tpLinkCipher.js.map +1 -0
  164. package/lib/tapo/utils/tplinkAccessory.d.ts +22 -0
  165. package/lib/tapo/utils/tplinkAccessory.d.ts.map +1 -0
  166. package/lib/tapo/utils/tplinkAccessory.js +3 -0
  167. package/lib/tapo/utils/tplinkAccessory.js.map +1 -0
  168. package/lib/tapo/utils/usage.d.ts +6 -0
  169. package/lib/tapo/utils/usage.d.ts.map +1 -0
  170. package/lib/tapo/utils/usage.js +10 -0
  171. package/lib/tapo/utils/usage.js.map +1 -0
  172. package/lib/utils.d.ts +29 -0
  173. package/lib/utils.d.ts.map +1 -0
  174. package/lib/utils.js +129 -0
  175. package/lib/utils.js.map +1 -0
  176. package/package.json +116 -0
@@ -0,0 +1,665 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const tpLinkCipher_1 = __importDefault(require("./tpLinkCipher"));
7
+ const uuid_1 = require("uuid");
8
+ const newTpLinkCipher_1 = __importDefault(require("./newTpLinkCipher"));
9
+ const axios_1 = __importDefault(require("axios"));
10
+ const crypto_1 = __importDefault(require("crypto"));
11
+ const utf8_1 = __importDefault(require("utf8"));
12
+ class P100 {
13
+ log;
14
+ ipAddress;
15
+ email;
16
+ password;
17
+ timeout;
18
+ _crypto = crypto_1.default;
19
+ _axios = axios_1.default;
20
+ _utf8 = utf8_1.default;
21
+ is_klap = true;
22
+ encodedPassword;
23
+ encodedEmail;
24
+ privateKey;
25
+ publicKey;
26
+ ip;
27
+ cookie;
28
+ tplink_timeout;
29
+ token;
30
+ terminalUUID;
31
+ _plugSysInfo;
32
+ _reconnect_counter;
33
+ _timeout;
34
+ tpLinkCipher;
35
+ newTpLinkCipher;
36
+ ERROR_CODES = {
37
+ '0': 'Success',
38
+ '-1010': 'Invalid Public Key Length',
39
+ '-1012': 'Invalid terminalUUID',
40
+ '-1501': 'Invalid Request or Credentials',
41
+ '1002': 'Incorrect Request',
42
+ '-1003': 'JSON formatting error ',
43
+ '9999': 'Session Timeout',
44
+ '-1301': 'Device Error',
45
+ '1100': 'Handshake Failed',
46
+ '1111': 'Login Failed',
47
+ '1112': 'Http Transport Failed',
48
+ '1200': 'Multiple Requests Failed',
49
+ '-1004': 'JSON Encode Failed',
50
+ '-1005': 'AES Decode Failed',
51
+ '-1006': 'Request Length Error',
52
+ '-2101': 'Account Error',
53
+ '-1': 'ERR_COMMON_FAILED',
54
+ '1000': 'ERR_NULL_TRANSPORT',
55
+ '1001': 'ERR_CMD_COMMAND_CANCEL',
56
+ '-1001': 'ERR_UNSPECIFIC',
57
+ '-1002': 'ERR_UNKNOWN_METHOD',
58
+ '-1007': 'ERR_CLOUD_FAILED',
59
+ '-1008': 'ERR_PARAMS',
60
+ '-1101': 'ERR_SESSION_PARAM',
61
+ '-1201': 'ERR_QUICK_SETUP',
62
+ '-1302': 'ERR_DEVICE_NEXT_EVENT',
63
+ '-1401': 'ERR_FIRMWARE',
64
+ '-1402': 'ERR_FIRMWARE_VER_ERROR',
65
+ '-1601': 'ERR_TIME',
66
+ '-1602': 'ERR_TIME_SYS',
67
+ '-1603': 'ERR_TIME_SAVE',
68
+ '-1701': 'ERR_WIRELESS',
69
+ '-1702': 'ERR_WIRELESS_UNSUPPORTED',
70
+ '-1801': 'ERR_SCHEDULE',
71
+ '-1802': 'ERR_SCHEDULE_FULL',
72
+ '-1803': 'ERR_SCHEDULE_CONFLICT',
73
+ '-1804': 'ERR_SCHEDULE_SAVE',
74
+ '-1805': 'ERR_SCHEDULE_INDEX',
75
+ '-1901': 'ERR_COUNTDOWN',
76
+ '-1902': 'ERR_COUNTDOWN_CONFLICT',
77
+ '-1903': 'ERR_COUNTDOWN_SAVE',
78
+ '-2001': 'ERR_ANTITHEFT',
79
+ '-2002': 'ERR_ANTITHEFT_CONFLICT',
80
+ '-2003': 'ERR_ANTITHEFT_SAVE',
81
+ '-2201': 'ERR_STAT',
82
+ '-2202': 'ERR_STAT_SAVE',
83
+ '-2301': 'ERR_DST',
84
+ '-2302': 'ERR_DST_SAVE',
85
+ '1003': 'KLAP',
86
+ };
87
+ constructor(log, ipAddress, email, password, timeout) {
88
+ this.log = log;
89
+ this.ipAddress = ipAddress;
90
+ this.email = email;
91
+ this.password = password;
92
+ this.timeout = timeout;
93
+ this.log.debug('Constructing P100 on host: ' + ipAddress);
94
+ this.ip = ipAddress;
95
+ this.encryptCredentials(email, password);
96
+ this.createKeyPair();
97
+ this.terminalUUID = (0, uuid_1.v4)();
98
+ this._reconnect_counter = 0;
99
+ this._timeout = timeout;
100
+ }
101
+ encryptCredentials(email, password) {
102
+ //Password Encoding
103
+ this.encodedPassword = tpLinkCipher_1.default.mime_encoder(password);
104
+ //Email Encoding
105
+ this.encodedEmail = this.sha_digest_username(email);
106
+ this.encodedEmail = tpLinkCipher_1.default.mime_encoder(this.encodedEmail);
107
+ }
108
+ sha_digest_username(data) {
109
+ const digest = this._crypto.createHash('sha1').update(data).digest('hex');
110
+ return digest;
111
+ }
112
+ calc_auth_hash(username, password) {
113
+ const usernameDigest = this._crypto.createHash('sha1').update(Buffer.from(username.normalize('NFKC'))).digest();
114
+ const passwordDigest = this._crypto.createHash('sha1').update(Buffer.from(password.normalize('NFKC'))).digest();
115
+ const digest = this._crypto.createHash('sha256').update((Buffer.concat([usernameDigest, passwordDigest]))).digest();
116
+ return digest;
117
+ }
118
+ createKeyPair() {
119
+ // Including publicKey and privateKey from
120
+ // generateKeyPairSync() method with its
121
+ // parameters
122
+ const { publicKey, privateKey } = this._crypto.generateKeyPairSync('rsa', {
123
+ publicKeyEncoding: {
124
+ type: 'spki',
125
+ format: 'pem',
126
+ },
127
+ privateKeyEncoding: {
128
+ type: 'pkcs1',
129
+ format: 'pem',
130
+ },
131
+ modulusLength: 1024,
132
+ });
133
+ this.privateKey = privateKey;
134
+ //@ts-ignore
135
+ this.publicKey = publicKey.toString('utf8');
136
+ }
137
+ //old tapo requests
138
+ async handshake() {
139
+ const URL = 'http://' + this.ip + '/app';
140
+ const payload = {
141
+ 'method': 'handshake',
142
+ 'params': {
143
+ 'key': this.publicKey,
144
+ 'requestTimeMils': Math.round(Date.now() * 1000),
145
+ },
146
+ };
147
+ this.log.debug('Handshake P100 on host: ' + this.ip);
148
+ const headers = {
149
+ 'Connection': 'Keep-Alive',
150
+ };
151
+ const config = {
152
+ timeout: 5000,
153
+ headers: headers,
154
+ };
155
+ await this._axios.post(URL, payload, config)
156
+ .then((res) => {
157
+ this.log.debug('Received Handshake P100 on host response: ' + this.ip);
158
+ if (res.data.error_code || res.status !== 200) {
159
+ return this.handleError(res.data.error_code ? res.data.error_code : res.status, '172');
160
+ }
161
+ try {
162
+ const encryptedKey = res.data.result.key.toString('utf8');
163
+ this.decode_handshake_key(encryptedKey);
164
+ if (res.headers['set-cookie']) {
165
+ this.cookie = res.headers['set-cookie'][0].split(';')[0];
166
+ }
167
+ return;
168
+ }
169
+ catch (error) {
170
+ return this.handleError(res.data.error_code, '106');
171
+ }
172
+ })
173
+ .catch((error) => {
174
+ this.log.error('111 Error: ' + error.message);
175
+ return error;
176
+ });
177
+ }
178
+ async login() {
179
+ const URL = 'http://' + this.ip + '/app';
180
+ const payload = '{' +
181
+ '"method": "login_device",' +
182
+ '"params": {' +
183
+ '"username": "' + this.encodedEmail + '",' +
184
+ '"password": "' + this.encodedPassword + '"' +
185
+ '},' +
186
+ '"requestTimeMils": ' + Math.round(Date.now() * 1000) + '' +
187
+ '};';
188
+ const headers = {
189
+ 'Cookie': this.cookie,
190
+ 'Connection': 'Keep-Alive',
191
+ };
192
+ if (this.tpLinkCipher) {
193
+ const encryptedPayload = this.tpLinkCipher.encrypt(payload);
194
+ const securePassthroughPayload = {
195
+ 'method': 'securePassthrough',
196
+ 'params': {
197
+ 'request': encryptedPayload,
198
+ },
199
+ };
200
+ const config = {
201
+ headers: headers,
202
+ timeout: this._timeout * 1000,
203
+ };
204
+ await this._axios.post(URL, securePassthroughPayload, config)
205
+ .then((res) => {
206
+ if (res.data.error_code || res.status !== 200) {
207
+ return this.handleError(res.data.error_code ? res.data.error_code : res.status, '226');
208
+ }
209
+ const decryptedResponse = this.tpLinkCipher.decrypt(res.data.result.response);
210
+ try {
211
+ const response = JSON.parse(decryptedResponse);
212
+ if (response.error_code !== 0) {
213
+ return this.handleError(res.data.error_code, '152');
214
+ }
215
+ this.token = response.result.token;
216
+ return;
217
+ }
218
+ catch (error) {
219
+ return this.handleError(JSON.parse(decryptedResponse).error_code, '157');
220
+ }
221
+ })
222
+ .catch((error) => {
223
+ this.log.error('Error: ' + error.message);
224
+ return error;
225
+ });
226
+ }
227
+ }
228
+ async raw_request(path, data, responseType, params) {
229
+ const URL = 'http://' + this.ip + '/app/' + path;
230
+ const headers = {
231
+ 'Connection': 'Keep-Alive',
232
+ Host: this.ip,
233
+ Accept: '*/*',
234
+ 'Content-Type': 'application/octet-stream',
235
+ };
236
+ if (this.cookie) {
237
+ //@ts-ignore
238
+ headers.Cookie = this.cookie;
239
+ }
240
+ const config = {
241
+ timeout: 5000,
242
+ responseType: responseType,
243
+ headers: headers,
244
+ params: params,
245
+ };
246
+ //@ts-ignore
247
+ return this._axios.post(URL, data, config)
248
+ .then((res) => {
249
+ this.log.debug('Received request on host response: ' + this.ip);
250
+ if (res.data.error_code || res.status !== 200) {
251
+ return this.handleError(res.data.error_code ? res.data.error_code : res.status, '273');
252
+ }
253
+ try {
254
+ if (res.headers && res.headers['set-cookie']) {
255
+ this.log.debug('Handshake 1 cookie: ' + JSON.stringify(res.headers['set-cookie'][0]));
256
+ this.cookie = res.headers['set-cookie'][0].split(';')[0];
257
+ this.tplink_timeout = Number(res.headers['set-cookie'][0].split(';')[1]);
258
+ }
259
+ return res.data;
260
+ }
261
+ catch (error) {
262
+ return this.handleError(res.data.error_code, '318');
263
+ }
264
+ })
265
+ .catch((error) => {
266
+ this.log.error('276 Error: ' + error.message + ', on ip: ' + this.ip);
267
+ if (error.message && error.message.indexOf('403') > -1) {
268
+ this.reAuthenticate();
269
+ }
270
+ throw new Error('Request failed: ' + (error instanceof Error ? error.message : String(error)));
271
+ });
272
+ }
273
+ decode_handshake_key(key) {
274
+ const buff = Buffer.from(key, 'base64');
275
+ const decoded = this._crypto.privateDecrypt({
276
+ key: this.privateKey,
277
+ padding: this._crypto.constants.RSA_PKCS1_PADDING,
278
+ }, buff);
279
+ const b_arr = decoded.slice(0, 16);
280
+ const b_arr2 = decoded.slice(16, 32);
281
+ this.tpLinkCipher = new tpLinkCipher_1.default(this.log, b_arr, b_arr2);
282
+ }
283
+ //new tapo klap requests
284
+ async handshake_new() {
285
+ this.log.debug('Trying new habdshake');
286
+ const local_seed = this._crypto.randomBytes(16);
287
+ await this.raw_request('handshake1', local_seed, 'arraybuffer').then((res) => {
288
+ const remote_seed = res.subarray(0, 16);
289
+ const server_hash = res.subarray(16);
290
+ let auth_hash = undefined;
291
+ const ah = this.calc_auth_hash(this.email, this.password);
292
+ const local_seed_auth_hash = this._crypto.createHash('sha256').update(Buffer.concat([local_seed, remote_seed, ah])).digest();
293
+ if (local_seed_auth_hash.toString('hex') === server_hash.toString('hex')) {
294
+ this.log.debug('Handshake 1 successful');
295
+ auth_hash = ah;
296
+ }
297
+ const req = this._crypto.createHash('sha256').update(Buffer.concat([remote_seed, local_seed, auth_hash])).digest();
298
+ return this.raw_request('handshake2', req, 'text').then((res) => {
299
+ this.log.debug('Handshake 2 successful: ' + res);
300
+ this.newTpLinkCipher = new newTpLinkCipher_1.default(local_seed, remote_seed, auth_hash, this.log);
301
+ this.log.debug('Init cipher successful');
302
+ return;
303
+ });
304
+ });
305
+ }
306
+ async turnOff() {
307
+ const payload = '{' +
308
+ '"method": "set_device_info",' +
309
+ '"params": {' +
310
+ '"device_on": false' +
311
+ '},' +
312
+ '"terminalUUID": "' + this.terminalUUID + '",' +
313
+ '"requestTimeMils": ' + Math.round(Date.now() * 1000) + '' +
314
+ '};';
315
+ return this.sendRequest(payload);
316
+ }
317
+ async turnOn() {
318
+ const payload = '{' +
319
+ '"method": "set_device_info",' +
320
+ '"params": {' +
321
+ '"device_on": true' +
322
+ '},' +
323
+ '"terminalUUID": "' + this.terminalUUID + '",' +
324
+ '"requestTimeMils": ' + Math.round(Date.now() * 1000) + '' +
325
+ '};';
326
+ return this.sendRequest(payload);
327
+ }
328
+ async setPowerState(state) {
329
+ if (state) {
330
+ return this.turnOn();
331
+ }
332
+ else {
333
+ return this.turnOff();
334
+ }
335
+ }
336
+ async getDeviceInfo(force) {
337
+ if (!force) {
338
+ return new Promise((resolve) => {
339
+ resolve(this.getSysInfo());
340
+ });
341
+ }
342
+ const URL = 'http://' + this.ip + '/app?token=' + this.token;
343
+ const payload = '{' +
344
+ '"method": "get_device_info",' +
345
+ '"requestTimeMils": ' + Math.round(Date.now() * 1000) + '' +
346
+ '};';
347
+ const headers = {
348
+ 'Cookie': this.cookie,
349
+ };
350
+ if (this.tpLinkCipher) {
351
+ const encryptedPayload = this.tpLinkCipher.encrypt(payload);
352
+ const securePassthroughPayload = {
353
+ 'method': 'securePassthrough',
354
+ 'params': {
355
+ 'request': encryptedPayload,
356
+ },
357
+ };
358
+ const config = {
359
+ headers: headers,
360
+ timeout: this._timeout * 1000,
361
+ };
362
+ //@ts-ignore
363
+ return this._axios.post(URL, securePassthroughPayload, config)
364
+ .then((res) => {
365
+ if (res.data.error_code) {
366
+ if ((res.data.error_code === '9999' || res.data.error_code === 9999) && this._reconnect_counter <= 3) {
367
+ //@ts-ignore
368
+ this.log.error(' Error Code: ' + res.data.error_code + ', ' + this.ERROR_CODES[res.data.error_code]);
369
+ this.log.debug('Trying to reconnect...');
370
+ return this.reconnect().then(() => {
371
+ return this.getDeviceInfo();
372
+ });
373
+ }
374
+ this._reconnect_counter = 0;
375
+ return this.handleError(res.data.error_code, '326');
376
+ }
377
+ const decryptedResponse = this.tpLinkCipher.decrypt(res.data.result.response);
378
+ try {
379
+ const response = JSON.parse(decryptedResponse);
380
+ if (response.error_code !== 0) {
381
+ return this.handleError(response.error_code, '333');
382
+ }
383
+ this.setSysInfo(response.result);
384
+ this.log.debug('Device Info: ', response.result);
385
+ return this.getSysInfo();
386
+ }
387
+ catch (error) {
388
+ return this.handleError(JSON.parse(decryptedResponse).error_code, '340');
389
+ }
390
+ })
391
+ .catch((error) => {
392
+ this.log.error('371 Error: ' + error.message);
393
+ throw new Error('Get device info failed: ' + (error instanceof Error ? error.message : String(error)));
394
+ });
395
+ }
396
+ else if (this.newTpLinkCipher) {
397
+ const data = this.newTpLinkCipher.encrypt(payload);
398
+ const URL = 'http://' + this.ip + '/app/' + 'request';
399
+ const headers = {
400
+ 'Connection': 'Keep-Alive',
401
+ Host: this.ip,
402
+ Accept: '*/*',
403
+ 'Content-Type': 'application/octet-stream',
404
+ };
405
+ if (this.cookie) {
406
+ //@ts-ignore
407
+ headers.Cookie = this.cookie;
408
+ }
409
+ const config = {
410
+ timeout: 5000,
411
+ responseType: 'arraybuffer',
412
+ headers: headers,
413
+ params: { seq: data.seq.toString() },
414
+ };
415
+ //@ts-ignore
416
+ return this._axios.post(URL, data.encryptedPayload, config)
417
+ .then((res) => {
418
+ if (res.data.error_code) {
419
+ return this.handleError(res.data.error_code, '309');
420
+ }
421
+ try {
422
+ if (res.headers && res.headers['set-cookie']) {
423
+ this.cookie = res.headers['set-cookie'][0].split(';')[0];
424
+ }
425
+ const response = JSON.parse(this.newTpLinkCipher.decrypt(res.data));
426
+ if (response.error_code !== 0) {
427
+ return this.handleError(response.error_code, '333');
428
+ }
429
+ this.setSysInfo(response.result);
430
+ this.log.debug('Device Info: ', response.result);
431
+ return this.getSysInfo();
432
+ }
433
+ catch (error) {
434
+ this.log.debug(this.newTpLinkCipher.decrypt(res.data));
435
+ this.log.debug('Status: ' + res.status);
436
+ return this.handleError(res.data.error_code, '480');
437
+ }
438
+ })
439
+ .catch((error) => {
440
+ this.log.debug('469 Error: ' + JSON.stringify(error) + ', on ip: ' + this.ip);
441
+ this.log.error('469 Error: ' + error.message + ', on ip: ' + this.ip);
442
+ if (error.message && error.message.indexOf('403') > -1) {
443
+ this.reAuthenticate();
444
+ }
445
+ throw new Error('Get device info KLAP failed: ' + (error instanceof Error ? error.message : String(error)));
446
+ });
447
+ }
448
+ else {
449
+ return new Promise((resolve, reject) => {
450
+ reject(new Error('Device not authenticated - handshake required'));
451
+ });
452
+ }
453
+ }
454
+ /**
455
+ * Cached value of `sysinfo.device_id` if set.
456
+ */
457
+ get id() {
458
+ if (this.getSysInfo()) {
459
+ return this.getSysInfo().device_id;
460
+ }
461
+ return '';
462
+ }
463
+ /**
464
+ * Cached value of `sysinfo.device_id` if set.
465
+ */
466
+ get name() {
467
+ if (this.getSysInfo()) {
468
+ return Buffer.from(this.getSysInfo().nickname, 'base64').toString('utf8');
469
+ }
470
+ return '';
471
+ }
472
+ get model() {
473
+ if (this.getSysInfo()) {
474
+ return this.getSysInfo().model;
475
+ }
476
+ return '';
477
+ }
478
+ get serialNumber() {
479
+ if (this.getSysInfo()) {
480
+ return this.getSysInfo().hw_id;
481
+ }
482
+ return '';
483
+ }
484
+ get firmwareRevision() {
485
+ if (this.getSysInfo()) {
486
+ return this.getSysInfo().fw_ver;
487
+ }
488
+ return '';
489
+ }
490
+ get hardwareRevision() {
491
+ if (this.getSysInfo()) {
492
+ return this.getSysInfo().hw_ver;
493
+ }
494
+ return '';
495
+ }
496
+ setSysInfo(sysInfo) {
497
+ this._plugSysInfo = sysInfo;
498
+ this._plugSysInfo.last_update = Date.now();
499
+ }
500
+ getSysInfo() {
501
+ return this._plugSysInfo;
502
+ }
503
+ handleError(errorCode, line) {
504
+ //@ts-ignore
505
+ const errorMessage = this.ERROR_CODES[errorCode];
506
+ if (typeof errorCode === 'number' && errorCode === 1003) {
507
+ this.log.info('Trying KLAP Auth');
508
+ this.is_klap = true;
509
+ }
510
+ else {
511
+ this.log.error(line + ' Error Code: ' + errorCode + ', ' + errorMessage + ' ' + this.ip);
512
+ }
513
+ return false;
514
+ }
515
+ async sendRequest(payload) {
516
+ if (this.tpLinkCipher) {
517
+ return this.handleRequest(payload).then((result) => {
518
+ return result ? true : false;
519
+ }).catch((error) => {
520
+ if (error.message && error.message.indexOf('9999') > 0 && this._reconnect_counter <= 3) {
521
+ return this.reconnect().then(() => {
522
+ return this.handleRequest(payload);
523
+ }).then((result) => {
524
+ return result ? true : false;
525
+ }).catch(() => false);
526
+ }
527
+ this._reconnect_counter = 0;
528
+ return false;
529
+ });
530
+ }
531
+ else {
532
+ return this.handleKlapRequest(payload).then((result) => {
533
+ return result ? true : false;
534
+ }).catch((error) => {
535
+ if (error.message && error.message.indexOf('9999') > 0 && this._reconnect_counter <= 3) {
536
+ return this.newReconnect().then(() => {
537
+ return this.handleKlapRequest(payload);
538
+ }).then((result) => {
539
+ return result ? true : false;
540
+ }).catch(() => false);
541
+ }
542
+ this._reconnect_counter = 0;
543
+ return false;
544
+ });
545
+ }
546
+ }
547
+ handleRequest(payload) {
548
+ const URL = 'http://' + this.ip + '/app?token=' + this.token;
549
+ const headers = {
550
+ 'Cookie': this.cookie,
551
+ 'Connection': 'Keep-Alive',
552
+ };
553
+ if (this.tpLinkCipher) {
554
+ const encryptedPayload = this.tpLinkCipher.encrypt(payload);
555
+ const securePassthroughPayload = {
556
+ 'method': 'securePassthrough',
557
+ 'params': {
558
+ 'request': encryptedPayload,
559
+ },
560
+ };
561
+ const config = {
562
+ headers: headers,
563
+ timeout: this._timeout * 1000,
564
+ };
565
+ return this._axios.post(URL, securePassthroughPayload, config)
566
+ .then((res) => {
567
+ if (res.data.error_code) {
568
+ if (res.data.error_code === '9999' || res.data.error_code === 9999 && this._reconnect_counter <= 3) {
569
+ //@ts-ignore
570
+ this.log.error(' Error Code: ' + res.data.error_code + ', ' + this.ERROR_CODES[res.data.error_code]);
571
+ this.log.debug('Trying to reconnect...');
572
+ return this.reconnect().then(() => {
573
+ return this.getDeviceInfo();
574
+ });
575
+ }
576
+ this._reconnect_counter = 0;
577
+ return this.handleError(res.data.error_code, '357');
578
+ }
579
+ const decryptedResponse = this.tpLinkCipher.decrypt(res.data.result.response);
580
+ try {
581
+ const response = JSON.parse(decryptedResponse);
582
+ this.log.debug(response);
583
+ if (response.error_code !== 0) {
584
+ return this.handleError(response.error_code, '364');
585
+ }
586
+ return response;
587
+ }
588
+ catch (error) {
589
+ return this.handleError(JSON.parse(decryptedResponse).error_code, '368');
590
+ }
591
+ })
592
+ .catch((error) => {
593
+ return this.handleError(error.message, '656');
594
+ });
595
+ }
596
+ return new Promise((resolve, reject) => {
597
+ reject();
598
+ });
599
+ }
600
+ handleKlapRequest(payload) {
601
+ if (this.newTpLinkCipher) {
602
+ const data = this.newTpLinkCipher.encrypt(payload);
603
+ return this.raw_request('request', data.encryptedPayload, 'arraybuffer', { seq: data.seq.toString() }).then((res) => {
604
+ return JSON.parse(this.newTpLinkCipher.decrypt(res));
605
+ }).catch(async (error) => {
606
+ if (error.message.indexOf('403') > -1) {
607
+ this.log.info('Got 403, re-authenticating and retrying...');
608
+ try {
609
+ await this.newReconnect();
610
+ this.log.info('Re-authenticated, retrying request...');
611
+ if (!this.newTpLinkCipher) {
612
+ throw new Error('KLAP cipher not initialized after reconnect');
613
+ }
614
+ const retryData = this.newTpLinkCipher.encrypt(payload);
615
+ const retryRes = await this.raw_request('request', retryData.encryptedPayload, 'arraybuffer', { seq: retryData.seq.toString() });
616
+ return JSON.parse(this.newTpLinkCipher.decrypt(retryRes));
617
+ }
618
+ catch (retryError) {
619
+ this.log.error('Retry after 403 failed: ' + (retryError instanceof Error ? retryError.message : String(retryError)));
620
+ throw retryError instanceof Error ? retryError : new Error(String(retryError));
621
+ }
622
+ }
623
+ throw error instanceof Error ? error : new Error(String(error));
624
+ });
625
+ }
626
+ return new Promise((resolve, reject) => {
627
+ reject(new Error('KLAP cipher not initialized'));
628
+ });
629
+ }
630
+ async reconnect() {
631
+ this._reconnect_counter++;
632
+ return this.handshake().then(() => {
633
+ this.login().then(() => {
634
+ return;
635
+ });
636
+ });
637
+ }
638
+ async newReconnect() {
639
+ this._reconnect_counter++;
640
+ return this.handshake_new().then(() => {
641
+ return;
642
+ });
643
+ }
644
+ reAuthenticate() {
645
+ if (this.is_klap) {
646
+ this.handshake_new().then(() => {
647
+ this.log.info('KLAP Authenticated successfully');
648
+ }).catch(() => {
649
+ this.log.error('KLAP Handshake failed');
650
+ this.is_klap = false;
651
+ });
652
+ }
653
+ else {
654
+ this.handshake().then(() => {
655
+ this.login().then(() => {
656
+ this.log.info('Authenticated successfully');
657
+ }).catch(() => {
658
+ this.log.error('Login failed');
659
+ });
660
+ });
661
+ }
662
+ }
663
+ }
664
+ exports.default = P100;
665
+ //# sourceMappingURL=p100.js.map