| 26 | } |
| 27 | |
| 28 | bool KasaSmartController::Initialize() |
| 29 | { |
| 30 | is_initialized = false; |
| 31 | retry_count = 0; |
| 32 | |
| 33 | /*--------------*\ |
| 34 | | Try to connect | |
| 35 | \*--------------*/ |
| 36 | while(!port.connected && !port.tcp_client_connect() && retry_count < KASA_SMART_MAX_CONNECTION_ATTEMPTS) |
| 37 | { |
| 38 | ++retry_count; |
| 39 | } |
| 40 | if(!port.connected) |
| 41 | { |
| 42 | /*----------------*\ |
| 43 | | Couldn't connect | |
| 44 | \*----------------*/ |
| 45 | return is_initialized; |
| 46 | } |
| 47 | |
| 48 | const std::string system_info_query(KASA_SMART_SYSTEM_INFO_QUERY); |
| 49 | std::string system_info_json; |
| 50 | bool command_sent = KasaSmartController::SendCommand(system_info_query, system_info_json); |
| 51 | port.tcp_close(); |
| 52 | if(!command_sent || system_info_json.empty()) |
| 53 | { |
| 54 | /*---------------------------------------*\ |
| 55 | | Send command failed or no data returned | |
| 56 | \*---------------------------------------*/ |
| 57 | return is_initialized; |
| 58 | } |
| 59 | |
| 60 | json system_information; |
| 61 | try |
| 62 | { |
| 63 | system_information = json::parse(system_info_json); |
| 64 | } |
| 65 | catch (json::parse_error&) |
| 66 | { |
| 67 | /*-----------------------*\ |
| 68 | | Can't parse system info | |
| 69 | \*-----------------------*/ |
| 70 | return is_initialized; |
| 71 | } |
| 72 | |
| 73 | std::string device_type; |
| 74 | if(system_information["system"]["get_sysinfo"].contains("type")) |
| 75 | { |
| 76 | device_type = system_information["system"]["get_sysinfo"]["type"]; |
| 77 | } |
| 78 | else if(system_information["system"]["get_sysinfo"].contains("mic_type")) |
| 79 | { |
| 80 | device_type = system_information["system"]["get_sysinfo"]["mic_type"]; |
| 81 | } |
| 82 | else |
| 83 | { |
| 84 | /*----------------------*\ |
| 85 | | Can't find device type | |
no test coverage detected