Of course I did not find all the below by myself but taking pieces from here and there. I just put it together. I will add shortly the links to the sources. Also, will try to find a way to show up the code a bit nicer.
How to get the authorization token
$url = 'https://eu-wap.tplinkcloud.com';
$curl = curl_init( $url );
$content = array (
'method' => 'login',
'params' => array (
'appType' => 'Kasa_Android',
'cloudUserName' => $username,
'cloudPassword' => $password,
'terminalUUID' => ''
)
);
curl_setopt( $curl, CURLOPT_POSTFIELDS, json_encode($content) );
curl_setopt( $curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json") );
...
$json_response = curl_exec($curl);
$response = json_decode($json_response, true);
$token = $response['result']['token'];
How to get the device list
$content = array ( $content = array ( 'method' => 'getDeviceList' );
.....
$response = json_decode($json_response, true);
$deviceList = $response['result']['deviceList'];
How to get the device status (on/off)
$content = array ( 'method' => 'passthrough',
"params" => array( "deviceId" => $deviceID,
"requestData" => json_encode(array("system" => array("get_sysinfo" => null,),))));
there are two issues here: firstly, the returned JSON is malformed so the php json_decode won’t work; secondly, the status for a plug comes in the “relay_state” field while the status for a light bulb comes in the “on_off” field. Regular expressions can do the job.
$found = preg_match( '/"relay_state":([0-9])/i', $response['result']['responseData'], $matches );
if( $found == 0 )
$found = preg_match( '/"on_off":([0-9])/i', $response['result']['responseData'], $matches );
$status = $matches[1];
How to set the status of a plug and a bulb
For plugs
$content = array ( 'method' => 'passthrough',
"params" => array( "deviceId" => $deviceID,
"requestData" => "{\"system\":{\"set_relay_state\":{\"state\": $newStatus }}}" ) );
for light bulbs
$content = array ( 'method' => 'passthrough', "params" => array( "deviceId" => $deviceID, "requestData" => "{\"smartlife.iot.smartbulb.lightingservice\":{ \"transition_light_state\" : {\"on_off\": $newStatus, \"transition_period\": 0} } }" ) );
References
http://itnerd.space/2017/01/22/how-to-control-your-tp-link-hs100-smartplug-from-internet/