ESP32用に作成したライブラリをLinux/Windows用に移殖しコマンドライン・アプリとして実行できるようにしてみた。
TP-LINK TAPO P100/P105をESP32から直接制御する
ESP32用からの変更点は、次の通り。
・JSONライブラリをArduino_JSONからPC向けとしては有名なnlohmann-jsonへ変更。
・HTTPライブラリをESP32/library/HTTPClientから独自作成の簡易型HTTPライブラリへ変更。
・MBEDTLSライブラリは、最新版(2.24.0)に差し替え。
base64ライブラリだが現在DL可能な最新版(1.2.1)については何か問題があるようだ。encode&decode或いはdecode&encodeにより元データが正確に復元できないことがある。パディングが不正になることを発見したのでデータバイト数の計算ミスなのかもしれない。結局、ESP32に含まれていたlibb64でないと正しく動作しなかったのでそのまま流用させてもらった。
しかし、未だにmakeの呪文のような記述方法は全く理解できない。とりあえず私の開発環境では動いているのだが何か間違ってるかも...
【対応ファームウェア】
P110M: 1.1.0 Build 231009 Rel.155719 以前
P105: 1.4.1 Build 20231103 Rel. 36519 以前
【修正】
2023-12-28
上記ファームウェア(Build 231009)以降に対応したものは下記を見るべし。
TP-LINK Tapo P105/P110M のKlapプロトコル対応版 (Windows/Linux)
2023-12-12
P110Mの最新ファームウェア(Build 231009)以降では通信プロトコルが変更されため1003エラーが発生します。動作中のP110Mをお持ちの方はTAPOアプリの自動更新をオフに設定することを推奨します。
2023-12-11
ダウンロード用のtapo.exe(tapo.zip)を動的リンクで生成していたために私の開発環境以外では動作しないことが判明。静的リンクに変更したものに差し替えした。気づくの遅すぎ!!m(_ _)m
2023-09-15
P110Mの電力モニター機能(getEnergyUsage)に対応。
2023-09-14
httpclient.hの不具合により[Tapo P110M]が動作しなかったため修正。
【ダウンロード(Download)】
tapo.exe (Windows実行形式 – Microsoft defender スキャン済み)
tapo app (ソースコード)
libraries (参照ライブラリ)
【フォルダ構成】
tapo/
+ json-develop/ … nlohmann-jsonの最新版(3.9.1)
+ libb64/ … ESP32に含まれているものを同梱
+ mbedtls-2.24.0/ … mbedtlsの最新版(2.24.0)
※ libb64は、最新版(1.2.1)では動作しないことに注意すべし!
【コンパイル(Compile)】
Downloadした圧縮ファイル2個を適当なフォルダ内に展開し次の事前準備を行った後にmakeを実行する。
【Linux – コンパイルの事前準備】
mbedtls-2.24.0に移動後、下記コマンドを実行しmbedtlsライブラリを生成する。
make no_test
【Windows(MinGW) – コンパイルの事前準備】
mbedtls-2.24.0に移動後、下記コマンドを実行しmbedtlsライブラリを生成する。
mingw32-make CC=gcc no_test WINDOWS=1
※makeが途中で失敗してもlibrary/libmbedcrypt.aが生成されていればOK。それしか使わないから...(-_-;)
※うまくいかない場合は、最後の参考情報を見て自己解決するべし。
【コマンドライン・アプリ(Command-Line App)】
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 |
/* tapo.cpp - TP-Link TAPO Client for P100/P105/P110 Copyright (c) 2020-2023 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "tapo.h" TAPO tapo; void usage() { fprintf(stderr, "\n"); fprintf(stderr, "TP-Link Tapo Smart Plug Client v1.1\n"); fprintf(stderr, "\n"); fprintf(stderr, "Usage: tapo [-h] ipaddress username password info|on|off|energy\n"); fprintf(stderr, "\n"); fprintf(stderr, "optional arguments:\n"); fprintf(stderr, " -h ... show this help\n"); } int main(int argc, char *argv[]) { const char *hostname = ""; const char *username = ""; const char *password = ""; const char *command = ""; bool help = false; int exitCode = EXIT_SUCCESS; for (int i = 1; i < argc; ++i) { char *p = argv[i]; if (*p == '-') { switch (p[1]) { default: exitCode = EXIT_FAILURE; case 'h': help = true; break; } } else { switch (i) { case 1: hostname = p; break; case 2: username = p; break; case 3: password = p; break; case 4: command = p; break; default: exitCode = EXIT_FAILURE; help = true; break; } } } if (!help) { if (!*hostname || !*username || !*password || !*command) { exitCode = EXIT_FAILURE; help = true; } else { bool rv = false; tapo.begin(hostname, username, password); if (strcmp("energy", command) == 0) { std::string info; rv = tapo.getEnergyUsage(info); if (rv) fprintf(stdout, "%s\n", info.c_str()); } else if (strcmp("info", command) == 0) { std::string info; rv = tapo.getDeviceInfo(info); if (rv) fprintf(stdout, "%s\n", info.c_str()); } else if (strcmp("on", command) == 0) { rv = tapo.setDeviceOn(true); } else if (strcmp("off", command) == 0) { rv = tapo.setDeviceOn(false); } else { fprintf(stderr, "invalid command [%s]\n", command); help = true; } tapo.end(); if (!help && !rv) { exitCode = EXIT_FAILURE; if (tapo.httpStatus() != HTTP_CODE_OK) fprintf(stderr, "HTTP Status: [%d]\n", tapo.httpStatus()); else if (tapo.tapoStatus()) fprintf(stderr, "TAPO Status: [%d]\n", tapo.tapoStatus()); else if (tapo.mbedStatus()) fprintf(stderr, "MBEDTLS Status: -0x[%04X]\n", abs(tapo.mbedStatus())); } } } if (help) usage(); return exitCode; } |
【ライブラリ(Library)】
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 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 |
/* tapo.h - TP-Link TAPO Control Library for P100/P105/P110 Copyright (c) 2020-2023 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __TAPO_H #define __TAPO_H #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <stdint.h> #include <stdbool.h> #include <string.h> #include <time.h> #include <string> #include "httpclient.h" #include "libb64/cencode.h" #include "libb64/cdecode.h" // Requires install. (apt install mbedtls-dev) #include "mbedtls/entropy.h" #include "mbedtls/ctr_drbg.h" #include "mbedtls/cipher.h" #include "mbedtls/pk.h" // Requires download. (https://github.com/nlohmann/json) #include "nlohmann/json.hpp" using json = nlohmann::json; // for convenience typedef enum { TAPO_ERROR_SUCCESS = 0, TAPO_ERROR_INCORRECT_REQUEST = -1002, TAPO_ERROR_JSON_FORMATTING_ERROR = -1003, TAPO_ERROR_INVALID_PUBLIC_KEY_LENGTH = -1010, // invalid cookie TAPO_ERROR_INVALID_TERMINALUUID = -1012, TAPO_ERROR_INVALID_REQUEST_OR_CREDENTIAL = -1501, TAPO_ERROR_DEVICE_BUSY = 9999, } TAPO_ERROR; #define TAPO_SESSION_TIMEOUT(t) ((t) * 60 * 1000) #define TAPO_MD_LENGTH 20 #define TAPO_CIPHER_KEY_BITS 128 #define TAPO_RSA_KEY_BITS 1024 #define TAPO_RSA_EXPONENT 65537 #define TAPO_SEED_PERSONAL "rsa_genkey" #define TAPO_METHOD_HANDSHAKE "handshake" #define TAPO_METHOD_LOGIN_DEVICE "login_device" #define TAPO_METHOD_GET_DEVICE_INFO "get_device_info" #define TAPO_METHOD_SET_DEVICE_INFO "set_device_info" #define TAPO_METHOD_GET_ENERGY_USAGE "get_energy_usage" #define TAPO_METHOD_SECUREPASSTHROUGH "securePassthrough" #define TAPO_DEBUG_PRINTF(format, ...) debug_printf(__FILE__, __LINE__, format, __VA_ARGS__) #define TAPO_DEBUG_MBEDTLS(name, status) mbedtls_status(__FILE__, __LINE__, name, status) class TAPO { private: std::string _hostname; std::string _username; std::string _password; HttpClient _httpClient; HttpResponse _httpResponse; int _httpStatus; int _tapoStatus; int _mbedStatus; std::string _tapoCookie; std::string _tapoToken; std::string _terminalUUID; uint32_t _sessionTimeout; uint32_t _sessionStart; std::string _publicKey; std::string _privateKey; uint8_t _cipherKey[TAPO_CIPHER_KEY_BITS >> 3]; uint8_t _cipherIv [TAPO_CIPHER_KEY_BITS >> 3]; uint8_t _buffer[2048]; void debug_printf(const char *file, int line, const char *format, ...) { printf("[%s:%d] ", file, line); va_list ap; va_start(ap, format); vprintf(format, ap); va_end(ap); } int mbedtls_status(const char *file, int line, const char *name, int status) { _mbedStatus = status; if (status) debug_printf(file, line, "%s = -0x%04X\n", name, abs(status)); return status; } std::string toHEX(uint8_t *buf, uint16_t len) { static const char HEX_DIGITS[] = "0123456789abcdef"; std::string hex; while (len-- > 0) { uint8_t b = *buf++; hex += HEX_DIGITS[b >> 4]; hex += HEX_DIGITS[b & 0x0F]; } return hex; } int b64encode(const uint8_t *bin, int len, uint8_t *b64) { base64_encodestate state; base64_init_encodestate(&state); len = base64_encode_block((const char *)bin, len, (char *)b64, &state); return len + base64_encode_blockend((char *)b64 + len, &state); } int b64decode(const uint8_t *b64, int len, uint8_t *bin) { base64_decodestate state; base64_init_decodestate(&state); return base64_decode_block((const char *)b64, len, (char *)bin, &state); } void replaceAll(std::string &replacedStr, std::string from, std::string to) { if (!from.empty()) { int pos = 0; while ((pos = replacedStr.find(from, pos)) != (int)std::string::npos) { replacedStr.replace(pos, from.length(), to); pos += to.length(); } } } std::string removePemLF(const std::string &pem) { int head = pem.find_first_of('\n'); int tail = pem.find_last_of('\n', pem.length() - 2); std::string body = pem.substr(head + 1, tail - (head + 1)); replaceAll(body, std::string("\n"), std::string("")); return pem.substr(0, head + 1) + body + pem.substr(tail + 1); } bool generateKeyPair(void) { bool rv = false; int olen; mbedtls_pk_context pk; mbedtls_entropy_context entropy; mbedtls_ctr_drbg_context ctr_drbg; _buffer[0] = 0; mbedtls_pk_init(&pk); mbedtls_entropy_init(&entropy); mbedtls_ctr_drbg_init(&ctr_drbg); if (TAPO_DEBUG_MBEDTLS("mbedtls_ctr_drbg_seed()", mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, (uint8_t *)TAPO_SEED_PERSONAL, strlen(TAPO_SEED_PERSONAL)))) ; else if (TAPO_DEBUG_MBEDTLS("mbedtls_pk_setup()", mbedtls_pk_setup(&pk, mbedtls_pk_info_from_type(MBEDTLS_PK_RSA)))) ; else if (TAPO_DEBUG_MBEDTLS("mbedtls_rsa_gen_key()", mbedtls_rsa_gen_key(mbedtls_pk_rsa(pk), mbedtls_ctr_drbg_random, &ctr_drbg, TAPO_RSA_KEY_BITS, TAPO_RSA_EXPONENT))) ; else if (TAPO_DEBUG_MBEDTLS("mbedtls_pk_write_pubkey_pem()", mbedtls_pk_write_pubkey_pem(&pk, _buffer, sizeof(_buffer)))) ; else if ((olen = strlen((char *)_buffer)) == 0) TAPO_DEBUG_PRINTF("invalid public key length = %d\n", olen); else if (TAPO_DEBUG_MBEDTLS("mbedtls_pk_write_key_pem()", mbedtls_pk_write_key_pem(&pk, _buffer + olen + 1, sizeof(_buffer) - olen - 1))) ; else { _publicKey = removePemLF(std::string((char *)_buffer)); _privateKey = (char *)(_buffer + olen + 1); rv = true; } mbedtls_ctr_drbg_free(&ctr_drbg); mbedtls_entropy_free(&entropy); mbedtls_pk_free(&pk); return rv; } bool cipherKey(const std::string &key) { bool rv = false; mbedtls_pk_context pk; mbedtls_entropy_context entropy; mbedtls_ctr_drbg_context ctr_drbg; uint16_t ilen = key.length(); size_t olen = b64decode((uint8_t *)key.c_str(), ilen, _buffer + ilen); mbedtls_pk_init(&pk); mbedtls_entropy_init(&entropy); mbedtls_ctr_drbg_init(&ctr_drbg); if (TAPO_DEBUG_MBEDTLS("mbedtls_ctr_drbg_seed()", mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, (uint8_t *)TAPO_SEED_PERSONAL, strlen(TAPO_SEED_PERSONAL)))) ; else if (TAPO_DEBUG_MBEDTLS("mbedtls_pk_parse_key()", mbedtls_pk_parse_key(&pk, (uint8_t *)_privateKey.c_str(), _privateKey.length() + 1, NULL, 0))) ; else if (TAPO_DEBUG_MBEDTLS("mbedtls_pk_decrypt()", mbedtls_pk_decrypt(&pk, _buffer + ilen, olen, _buffer, &olen, ilen, mbedtls_ctr_drbg_random, &ctr_drbg))) ; else if (olen != sizeof(_cipherKey) + sizeof(_cipherIv)) TAPO_DEBUG_PRINTF("invalid cipher key length = %d\n", olen); else { memcpy(_cipherKey, _buffer, sizeof(_cipherKey)); memcpy(_cipherIv, _buffer + sizeof(_cipherKey), sizeof(_cipherIv)); rv = true; } mbedtls_ctr_drbg_free(&ctr_drbg); mbedtls_entropy_free(&entropy); mbedtls_pk_free(&pk); return rv; } std::string digest(const char *msg) { return TAPO_DEBUG_MBEDTLS("mbedtls_md(mbedtls_md_info_from_type()", mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_SHA1), (const uint8_t *)msg, strlen(msg), _buffer)) ? std::string() : toHEX(_buffer, TAPO_MD_LENGTH); } size_t cipher0(mbedtls_operation_t operation, const uint8_t *input, size_t ilen, uint8_t *output) { size_t olen, olen2; mbedtls_cipher_context_t cipher; mbedtls_cipher_init(&cipher); if (TAPO_DEBUG_MBEDTLS("mbedtls_cipher_setup()", mbedtls_cipher_setup(&cipher, mbedtls_cipher_info_from_values(MBEDTLS_CIPHER_ID_AES, TAPO_CIPHER_KEY_BITS, MBEDTLS_MODE_CBC)))) ; else if (TAPO_DEBUG_MBEDTLS("mbedtls_cipher_set_padding_mode()", mbedtls_cipher_set_padding_mode(&cipher, MBEDTLS_PADDING_PKCS7))) ; else if (TAPO_DEBUG_MBEDTLS("mbedtls_cipher_set_iv()", mbedtls_cipher_set_iv(&cipher, _cipherIv, sizeof(_cipherIv)))) ; else if (TAPO_DEBUG_MBEDTLS("mbedtls_cipher_setkey()", mbedtls_cipher_setkey(&cipher, _cipherKey, TAPO_CIPHER_KEY_BITS, operation))) ; else if (TAPO_DEBUG_MBEDTLS("mbedtls_cipher_update()", mbedtls_cipher_update(&cipher, input, ilen, output, &olen))) ; else if (TAPO_DEBUG_MBEDTLS("mbedtls_cipher_finish()", mbedtls_cipher_finish(&cipher, output + olen, &olen2))) olen = olen2 = 0; mbedtls_cipher_free(&cipher); return _mbedStatus ? 0 : olen + olen2; } std::string encrypt(const std::string &plain) { size_t ilen = plain.length(); size_t olen = cipher0(MBEDTLS_ENCRYPT, (uint8_t *)plain.c_str(), ilen, _buffer + ilen); _buffer[b64encode(_buffer + ilen, olen, _buffer)] = 0; return std::string((char *)_buffer); } std::string decrypt(const std::string &cipher) { size_t ilen = cipher.length(); size_t olen = b64decode((uint8_t *)cipher.c_str(), ilen, _buffer + ilen); _buffer[cipher0(MBEDTLS_DECRYPT, _buffer + ilen, olen, _buffer)] = 0; return std::string((char *)_buffer); } bool request0(const std::string &payload) { _httpStatus = 0; _tapoStatus = 0; _mbedStatus = 0; _httpClient.clear(); if (_tapoToken.length()) _httpClient.addQuery("token", _tapoToken.c_str()); if (_tapoCookie.length()) _httpClient.addHeader("Cookie", _tapoCookie.c_str()); _httpClient.addHeader("Content-Type", "application/json;charset=UTF-8"); _httpStatus = _httpClient.request(_httpResponse, _hostname.c_str(), 80, "app", "POST", payload.c_str()); if (_httpStatus != HTTP_CODE_OK) return false; std::string cookie = _httpResponse.getHeader("Set-Cookie", ""); if (cookie.length()) { _sessionStart = millis(); // parse cookie int left = 0; int right = -1; while (right + 1 < (int)cookie.length()) { left = right + 1; right = cookie.find_first_of(';', left); if (right < 0) right = cookie.length(); int mid = cookie.find_first_of('=', left); if (mid < 0) mid = right; std::string name = cookie.substr(left, mid - left); std::string value = cookie.substr(mid + 1, right - (mid + 1)); if (strcasecmp(name.c_str(), "TP_SESSIONID") == 0) _tapoCookie = cookie.substr(left, right - left); if (strcasecmp(name.c_str(), "TIMEOUT") == 0) _sessionTimeout = TAPO_SESSION_TIMEOUT(atoi(value.c_str()) - 1); } } return true; } const char *request(const std::string &payload) { int retry = 3; while (1) { if (request0(payload)) return _httpResponse.content(); if (--retry == 0) break; delay(1000); } return ""; } bool handshake(void) { json payload; payload["method"] = TAPO_METHOD_HANDSHAKE; payload["params"]["key"] = _publicKey; payload["requestTimeMils"] = millis(); std::string response = request(payload.dump()); if (response.length()) { json res = json::parse(response); _tapoStatus = res["error_code"].get<int>(); if (_tapoStatus == 0) { if (cipherKey(res["result"]["key"].get<std::string>()) && _tapoCookie.length()) return true; } } return false; } bool login(void) { json payload; payload["method"] = TAPO_METHOD_LOGIN_DEVICE; payload["params"]["username"] = _username; payload["params"]["password"] = _password; payload["requestTimeMils"] = millis(); json envelope; envelope["method"] = TAPO_METHOD_SECUREPASSTHROUGH; envelope["params"]["request"] = encrypt(payload.dump()); std::string response = request(envelope.dump()); if (response.length()) { json res = json::parse(response); _tapoStatus = res["error_code"].get<int>(); if (_tapoStatus == 0) { res = json::parse(decrypt(res["result"]["response"].dump())); _tapoStatus = res["error_code"].get<int>(); if (_tapoStatus == 0) { _tapoToken = res["result"]["token"].get<std::string>(); if (_tapoToken.length()) return true; } } } return false; } bool beginSession(void) { if (_tapoCookie.length() && _tapoToken.length()) { if (millis() - _sessionStart < _sessionTimeout) return true; endSession(); } return handshake() && login(); } void endSession(void) { _tapoCookie.clear(); _tapoToken.clear(); _terminalUUID.clear(); } std::string getTerminalUUID(void) { if (_terminalUUID.length() == 0) { std::string info; if (getDeviceInfo(info)) _terminalUUID = json::parse(info)["result"]["mac"].get<std::string>(); } return _terminalUUID; } public: TAPO(void) : _httpStatus(0) , _tapoStatus(0) , _mbedStatus(0) , _sessionTimeout(TAPO_SESSION_TIMEOUT(1440 - 1)) { } virtual ~TAPO(void) { } bool begin(const char *hostname, const char *username, const char *password) { // support for winsock if (!HttpClient::startup()) { TAPO_DEBUG_PRINTF("HttpClient::startup() failed.\n", 0); return false; } if (!generateKeyPair()) { TAPO_DEBUG_PRINTF("generateKeyPair() failed.\n", 0); return false; } // hostname (ipaddress only) _hostname = hostname; // username std::string id = digest(username); _buffer[b64encode((uint8_t *)id.c_str(), id.length(), _buffer)] = 0; _username = (char *)_buffer; // password _buffer[b64encode((uint8_t *)password, strlen(password), _buffer)] = 0; _password = (char *)_buffer; // endSession(); return true; } void end(void) { // support for winsock HttpClient::cleanup(); } int httpStatus(void) { return _httpStatus; } int tapoStatus(void) { return _tapoStatus; } int mbedStatus(void) { return _mbedStatus; } /* * std::string info; * getDeviceInfo(info); * decode(json::parse(info)["result"]["nickname" or "ssid"].get<std::string>()); */ std::string decode(const std::string &str) { _buffer[b64decode((uint8_t *)str.c_str(), str.length(), _buffer)] = 0; return std::string((char *)_buffer); } bool getEnergyUsage(std::string &info) { if (beginSession()) { json payload; payload["method"] = TAPO_METHOD_GET_ENERGY_USAGE; payload["requestTimeMils"] = millis(); json envelope; envelope["method"] = TAPO_METHOD_SECUREPASSTHROUGH; envelope["params"]["request"] = encrypt(payload.dump()); std::string response = request(envelope.dump()); if (response.length()) { json res = json::parse(response); _tapoStatus = res["error_code"].get<int>(); if (_tapoStatus == 0) { info = decrypt(res["result"]["response"].dump()); return true; } } } endSession(); return false; } bool getDeviceInfo(std::string &info) { if (beginSession()) { json payload; payload["method"] = TAPO_METHOD_GET_DEVICE_INFO; payload["requestTimeMils"] = millis(); json envelope; envelope["method"] = TAPO_METHOD_SECUREPASSTHROUGH; envelope["params"]["request"] = encrypt(payload.dump()); std::string response = request(envelope.dump()); if (response.length()) { json res = json::parse(response); _tapoStatus = res["error_code"].get<int>(); if (_tapoStatus == 0) { info = decrypt(res["result"]["response"].dump()); return true; } } } endSession(); return false; } bool setDeviceOn(bool on) { if (beginSession()) { json payload; payload["method"] = TAPO_METHOD_SET_DEVICE_INFO; payload["params"]["device_on"] = on; payload["terminalUUID"] = getTerminalUUID(); payload["requestTimeMils"] = millis(); json envelope; envelope["method"] = TAPO_METHOD_SECUREPASSTHROUGH; envelope["params"]["request"] = encrypt(payload.dump()); std::string response = request(envelope.dump()); if (response.length()) { json res = json::parse(response); _tapoStatus = res["error_code"].get<int>(); if (_tapoStatus == 0) return true; } } endSession(); return false; } static unsigned long micros(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (unsigned long)((unsigned long long)ts.tv_sec * 1000000) + (ts.tv_nsec / 1000); } static unsigned long millis(void) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (unsigned long)((unsigned long long)ts.tv_sec * 1000) + (ts.tv_nsec / 1000000); } static void delay(unsigned long ms) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); ts.tv_sec += (ms / 1000); ts.tv_nsec += (ms % 1000) * 1000000; if (ts.tv_nsec >= 1000000000) { ts.tv_nsec -= 1000000000; ts.tv_sec++; } clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL); } static void delayMicroseconds(unsigned int us) { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); ts.tv_sec += (us / 1000000); ts.tv_nsec += (us % 1000000) * 1000; if (ts.tv_nsec >= 1000000000) { ts.tv_nsec -= 1000000000; ts.tv_sec++; } clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL); } }; #endif |
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 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 |
/* httpclient.h - HTTP Client Library for Linux/Windows Copyright (c) 2020-2023 Sasapea's Lab. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __HTTPCLIENT_H #define __HTTPCLIENT_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string> #include <vector> #include <sstream> #define HTTP_CODE_OK 200 #define HTTP_TIMEOUT 1000 typedef struct { std::string name; std::string value; } http_name_value_t; class HttpHeader { protected: std::vector<http_name_value_t> _headers; void addNameValue(std::vector<http_name_value_t> &vec, const char *name, int value) { addNameValue(vec, name, std::to_string(value).c_str()); } void addNameValue(std::vector<http_name_value_t> &vec, const char *name, const char *value) { for(auto it = vec.begin(); it != vec.end(); ++it) { if (strcasecmp(it->name.c_str(), name) == 0) { it->value = value; return; } } vec.push_back({name, value}); } const char *getNameValue(std::vector<http_name_value_t> &vec, const char *name, const char *defval = "") { for(auto it = vec.begin(); it != vec.end(); ++it) { if (strcasecmp(it->name.c_str(), name) == 0) return it->value.c_str(); } return defval; } std::string listNameValue(std::vector<http_name_value_t> &vec, const char *sep, const char *dlm, bool last) { std::string list; for(auto it = vec.begin(); it != vec.end(); ++it) { if (list.size()) list += dlm; list += it->name; list += sep; list += it->value; } if (last && list.size()) list += dlm; return list; } public: void addHeader(const char *name, const char *value) { addNameValue(_headers, name, value); } void addHeader(const char *name, int value) { addNameValue(_headers, name, value); } const char *getHeader(const char *name, const char *defval = "") { return getNameValue(_headers, name, defval); } static const char *HTTP_METHOD_GET; static const char *HTTP_METHOD_POST; static const char *HTTP_HOST; static const char *HTTP_CONNECTION; static const char *HTTP_CONTENT_TYPE; static const char *HTTP_CONTENT_LENGTH; static const char *HTTP_MIME_TEXT_PLAIN; static const char *HTTP_MIME_X_WWW_FORM_URLENCODED; static const char *HTTP_LF; }; const char *HttpHeader::HTTP_METHOD_GET = "GET"; const char *HttpHeader::HTTP_METHOD_POST = "POST"; const char *HttpHeader::HTTP_HOST = "Host"; const char *HttpHeader::HTTP_CONNECTION = "Connection"; const char *HttpHeader::HTTP_CONTENT_TYPE = "Content-Type"; const char *HttpHeader::HTTP_CONTENT_LENGTH = "Content-Length"; const char *HttpHeader::HTTP_MIME_TEXT_PLAIN = "text/plain"; const char *HttpHeader::HTTP_MIME_X_WWW_FORM_URLENCODED = "application/x-www-form-urlencoded"; const char *HttpHeader::HTTP_LF = "\r\n"; class HttpRequest : public HttpHeader { private: std::vector<http_name_value_t> _queries; std::string _request; public: void clear(void) { _headers.clear(); _queries.clear(); addHeader(HTTP_CONNECTION, "close"); } void addQuery(const char *name, const char *value) { addNameValue(_queries, name, value); } const char *getHttpString(const char *host, const char *path, const char *method, const char *content = "") { std::vector<http_name_value_t> headers = _headers; std::string queries = listNameValue(_queries, "=", "&", false); std::string type = getNameValue(headers, HTTP_CONTENT_TYPE, ""); std::string data = content; if (type.size() == 0) type = ((data.size() == 0) && queries.size() ? HTTP_MIME_X_WWW_FORM_URLENCODED : HTTP_MIME_TEXT_PLAIN); if (type == HTTP_MIME_X_WWW_FORM_URLENCODED) data = queries; _request = method; _request += " /"; _request += path; if (strcasecmp(type.c_str(), HTTP_MIME_X_WWW_FORM_URLENCODED) && queries.size()) { _request += '?'; _request += queries; } _request += " HTTP/"; if (host && *host) { _request += "1.1"; addNameValue(headers, HTTP_HOST, host); } else _request += "1.0"; _request += HTTP_LF; addNameValue(headers, HTTP_CONTENT_TYPE , type.c_str()); addNameValue(headers, HTTP_CONTENT_LENGTH, data.size()); _request += listNameValue(headers, ": ", HTTP_LF, true); _request += HTTP_LF; _request += data; return _request.c_str(); } }; class HttpResponse : public HttpHeader { private: std::string _content; std::string _result[3]; public: void clear(void) { _headers.clear(); _content.clear(); _result[0] = ""; _result[1] = "-1"; _result[2] = ""; } void parse(const char *response) { std::string issstr = response; std::istringstream iss(issstr); std::string line; clear(); while (std::getline(iss, line)) { int len = line.length(); if ((len > 0) && (line[len - 1] == '\r')) line.resize(--len); if (len == 0) break; if (line.find("HTTP/") == 0) { int cnt = 0; int pos = 5; while (pos < len) { int sep = pos; while ((pos < len) && (line[pos] != ' ')) ++pos; _result[cnt++] = line.substr(sep, pos - sep); while ((pos < len) && (line[pos] == ' ')) ++pos; if (cnt == sizeof(_result) / sizeof(_result[0]) - 1) { _result[cnt] = line.substr(pos); break; } } } else { int pos = 0; while ((pos < len) && (line[pos] != ':')) ++pos; int sep = pos++; while ((pos < len) && (line[pos] == ' ')) ++pos; addHeader(line.substr(0, sep).c_str(), line.substr(pos).c_str()); } } _content = issstr.substr((int)iss.tellg()); } const char *getHttpVersion(void) { return _result[0].c_str(); } int getHttpStatus(void) { return std::stoi(_result[1]); } const char *getHttpMessage(void) { return _result[2].c_str(); } const char *getContentType(void) { return getHeader(HTTP_CONTENT_TYPE, ""); } int getContentLength(void) { return std::stoi(getHeader(HTTP_CONTENT_LENGTH, "-1"), nullptr, 10); } const char *content(void) { return _content.c_str(); } std::string toString() { std::string str = listNameValue(_headers, ": ", "\n", true); str += "\n"; str += _content.c_str(); return str; } }; #if defined(_MSC_VER) || defined(__MINGW32__) || defined(__MINGW64__) #define __WINSOCK__ #endif // socket #ifdef __WINSOCK__ #include <ws2tcpip.h> #define MSG_NOSIGNAL 0 #define ssize_t int #else #include <time.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define closesocket(s) close(s) #endif class HttpClient : public HttpRequest { public: int request(HttpResponse &response, const char *host, int port, const char *path, const char *method, const char *content = "") { struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = inet_addr(host); response.clear(); int sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if (sock != -1) { if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) != -1) { const char *http = getHttpString(host, path, method, content); ssize_t len = strlen(http); if (send(sock, http, len, MSG_NOSIGNAL) == len) { int len, cnt = 0; char *buf = (char *)malloc(len = 1024); if (buf) { struct timeval tov = { HTTP_TIMEOUT / 1000, (HTTP_TIMEOUT % 1000) * 1000 }; while (1) { char tmp[256]; fd_set rdfds; int n; FD_ZERO(&rdfds); FD_SET(sock, &rdfds); if ((n = select(sock + 1, &rdfds, NULL, NULL, &tov)) < 0) break; if (n > 0) { if ((n = recv(sock, tmp, sizeof(tmp), 0)) < 0) break; } if (n == 0) { buf[cnt] = 0; response.parse(buf); break; } if (cnt + n >= len) { len += 1024; char *p = (char *)realloc(buf, len); if (!p) break; buf = p; } memcpy(buf + cnt, tmp, n); cnt += n; tov.tv_sec = 0; tov.tv_usec = 20000; // 20ms } free(buf); } } } closesocket(sock); } return response.getHttpStatus(); } static bool startup(void) { #ifdef __WINSOCK__ WSADATA wsaData; return WSAStartup(MAKEWORD(2, 2), &wsaData) == 0; #else return true; #endif } static void cleanup(void) { #ifdef __WINSOCK__ WSACleanup(); #endif } }; #endif |
【参照ライブラリ】
libb64
JSONライブラリ – nlohmann/json
ARMmbed/mbedtls
【参考情報】
mbedtls – Knowledge Base / Compiling and Building
【関連投稿】
TP-LINK WiFiスマートプラグをESP32(Arduino)から制御する
TP-LINK WiFiスマートプラグをLinux/Windowsから直接制御する
TP-LINK TAPO P100/P105をESP32から直接制御する
TP-LINK TAPO P100/P105/P110をLinux/Windowsから直接制御する