Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
5c22c57
Auto Discovery of TPLinkDevices on network
shanerutter Nov 29, 2017
43a40be
Stopped stream_socket_client from giving off warning messages
shanerutter Nov 29, 2017
c2ea0ee
Faster querying of network devices by allowing config to support a ti…
shanerutter Nov 30, 2017
dab8bcb
Expose devices config via getConfig
shanerutter Nov 30, 2017
9efbc7f
Checking auto discovery for empty responses and null json_decodes
shanerutter Nov 30, 2017
ac1c507
PSR-2 compliance changes
shanerutter Dec 1, 2017
7a897f8
Exclude .idea dev folder
shanerutter Dec 1, 2017
b7d3d57
Updated readme.md
shanerutter Dec 1, 2017
64b4fa2
Updated readme.md
shanerutter Dec 1, 2017
e3faa21
Merge branch 'feature/auto_discovery' of github.com:shanerutter/tplin…
shanerutter Dec 1, 2017
bfb0fe3
Laravel config updated with timeout setting
shanerutter Dec 1, 2017
a9c457c
Added missing bit from readme
shanerutter Dec 1, 2017
d7d3efe
Added missing bit from readme
shanerutter Dec 1, 2017
81f6bb4
Merge branch 'feature/auto_discovery' of github.com:shanerutter/tplin…
shanerutter Dec 1, 2017
6de9fb7
Merge branch 'feature/auto_discovery' of github.com:shanerutter/tplin…
shanerutter Dec 1, 2017
94200f4
Merge branch 'feature/auto_discovery' of github.com:shanerutter/tplin…
shanerutter Dec 1, 2017
f0ed9de
Read me edit for deviceList
shanerutter Dec 1, 2017
8b750c7
Added jonnywilliamson changes with some bug fixes
shanerutter Jun 19, 2019
4f73c27
Merge branch 'feature/power_control_methods' into feature/auto_discovery
shanerutter Jun 19, 2019
0030c64
Removed error supression
shanerutter Jun 20, 2019
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
composer.phar
composer.lock
vendor/
build/
build/
.idea/
41 changes: 39 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,14 @@ return [
'lamp' => [
'ip' => '192.168.1.100', //Or hostname eg: home.example.com
'port' => '9999',
'timeout' => 5 // Optional, timeout setting (how long we will try communicate with device before giving up)
],
];
```

You may add as many devices as you wish, as long as you specify the IP address (or host address if required) and port number to access each one. Giving each device a name makes it easy to identify them when coding later. _(Please note that the name you give here does NOT have to match the actual name you might have assigned the device using an official app like Kasa. They do NOT have to match)_
You may add as many devices as you wish, as long as you specify the IP address (or host address if required) and port number to access each one. Giving each device a name makes it easy to identify them when coding later. _(Please note that the name you give here does NOT have to match the actual name you might have assigned the device using an official app like Kasa. They do NOT have to match)

You can use the `autoDiscoverTPLinkDevices` method to automatically find networked devices.

## Usage
You can access your device either through the `TPLinkManager` class (especially useful if you have multiple devices), or directly using the `TPLinkDevice` class.
Expand Down Expand Up @@ -130,7 +133,40 @@ If a command requires a parameter, provide that as well:
$tpDevice->sendCommand(TPLinkCommand::setLED(false));
```

####Toggle Power
#### Auto Discovery
You can search your local network for devices using `TPLinkManager`, using the method `autoDiscoverTPLinkDevices`
all found devices will be added to the 'TPLinkManager' config automatically, exposed using `deviceList()`.

You must provide the IP range you wish to scan, use it as follows:
```php
//Non laravel
$tpLinkManager->autoDiscoverTPLinkDevices('192.168.0.*');

//Laravel
// with facade
TPLink::autoDiscoverTPLinkDevices('192.168.0.*');

// without facade
app('tplink')->autoDiscoverTPLinkDevices('192.168.0.*');
app(TPLinkManager::class)->autoDiscoverTPLinkDevices('192.168.0.*');
```

The auto discovery command will take a while to scan, once completed you can use `deviceList()` method to view the new configuration and any found devices.

```php
//Non laravel
$tpLinkManager->deviceList();

//Laravel
// with facade
$devices = TPLink::deviceList();

// without facade
$devices = app('tplink')->deviceList();
$devices = app(TPLinkManager::class)->deviceList();
```

#### Toggle Power
There is one command that is called directly on the `TPLinkDevice` and that is the `togglePower()` method.

If you only wish to toggle the current power state of the plug, use it as follows:
Expand Down Expand Up @@ -216,6 +252,7 @@ Any issues, feedback, suggestions or questions please use issue tracker [here][l
- [softScheck](https://github.com/softScheck/tplink-smartplug) (Who did the reverse engineering and provided the secrets on how to talk to the Smartplug.)
- [Jonathan Williamson][link-author]
- [Syed Irfaq R.](https://github.com/irazasyed) For the idea behind how to manage multiple devices.
- [Shane Rutter](https://shanerutter.co.uk) Auto-Discovery feature

## Disclaimer

Expand Down
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
}
],
"require": {
"tightenco/collect": "^5.3"
"tightenco/collect": "^5.3",
"s1lentium/iptools": "^1.1"
},
"require-dev": {
"phpunit/phpunit": "^5.7"
Expand Down
11 changes: 4 additions & 7 deletions src/Laravel/TPLinkServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,20 +27,17 @@ public function boot()
*/
public function register()
{
$this->app->singleton(TPLinkManager::class,
function ($app) {
$config = (array)$app['config']['TPLink'];
$this->app->singleton(TPLinkManager::class, function ($app) {
$config = (array)$app['config']['TPLink'];

return new TPLinkManager($config);
});
return new TPLinkManager($config);
});

$this->app->alias(TPLinkManager::class, 'tplink');


//Auto-register the TPLink facade if the user hasn't already
//assigned it to another class.
if (class_exists(AliasLoader::class)) {

$loader = AliasLoader::getInstance();

if (!array_key_exists('TPLink', $loader->getAliases())) {
Expand Down
4 changes: 3 additions & 1 deletion src/Laravel/config/TPLink.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@
// 'bedroom' => [
// 'ip' => '192.168.1.100', //Or hostname
// 'port' => '9999',
// 'timeout' => 5
// ],

// 'livingroom' => [
// 'ip' => '192.168.1.101', //Or hostname
// 'port' => '9999',
// 'timeout' => 10
// ],

];
];
21 changes: 10 additions & 11 deletions src/TPLinkCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
use InvalidArgumentException;
use Illuminate\Support\Collection;


/**
* Class TPLinkCommands
*
Expand Down Expand Up @@ -114,7 +113,7 @@ public static function setDeviceAlias($name)
public static function setMacAddress($macAddress)
{
if (filter_var($macAddress, FILTER_VALIDATE_MAC) === false) {
throw new InvalidArgumentException('The supplied MAC address is not valid. Try again using hyphens between each group of characters.');
throw new InvalidArgumentException('MAC address invalid. Try hyphens between each group of characters.');
}

return [
Expand Down Expand Up @@ -241,7 +240,7 @@ public static function flashFirmware($confirm = false)
];
}

throw new InvalidArgumentException('You must set the confirm flag to true before flashing firmware is allowed.');
throw new InvalidArgumentException('Confirm flag to true before flashing firmware is allowed.');
}

/**
Expand Down Expand Up @@ -402,7 +401,7 @@ public static function cloudUnregisterDevice($confirm = false)
];
}

throw new InvalidArgumentException('You must set the confirm flag to true before un-registering the device is allowed.');
throw new InvalidArgumentException('Confirm flag to true before un-registering the device is allowed.');
}

/**
Expand Down Expand Up @@ -662,7 +661,7 @@ public static function scheduleRuleList()
* @param DateTime $dateAndTime The actual Date and Time for this event.
* @param bool $turnOn Should the event turn on or off the timer.
* @param string $name An event name. On some clients this isn't even seen.
* @param array $daysOfWeekToRepeat (Optional). An array of days of the week this event should repeat. Use normal english like Tues, Saturday etc.
* @param array $daysOfWeekToRepeat (Optional). Days of week event should repeat. Use EN like Tues, Saturday etc.
*
* @return array
*/
Expand Down Expand Up @@ -690,7 +689,7 @@ public static function scheduleRuleCreate(DateTime $dateAndTime, $turnOn, $name,
* @param DateTime $dateAndTime The actual Date and Time for this event.
* @param bool $turnOn Should the event turn on or off the timer.
* @param string $name An event name. On some clients this isn't even seen.
* @param array $daysOfWeekToRepeat (Optional). An array of days of the week this event should repeat. Use normal english like Tues, Saturday etc.
* @param array $daysOfWeekToRepeat (Optional). Days of week event should repeat. Use EN like Tues, Saturday etc.
*
* @return array
*/
Expand Down Expand Up @@ -856,7 +855,7 @@ public static function antitheftRuleList()
* @param DateTime $startTime The start date/time for the event to begin
* @param DateTime $endTime The end date/time for the event to finish.
* @param string $name An event name. On some clients this isn't even seen.
* @param array $daysOfWeekToRepeat (Optional). An array of days of the week this event should repeat. Use normal english like Tues, Saturday etc.
* @param array $daysOfWeekToRepeat (Optional). Days of week event should repeat. Use EN like Tues, Saturday etc.
*
* @return array
*/
Expand Down Expand Up @@ -884,7 +883,7 @@ public static function antitheftRuleCreate(DateTime $startTime, DateTime $endTim
* @param DateTime $startTime The start date/time for the event to begin
* @param DateTime $endTime The end date/time for the event to finish.
* @param string $name An event name. On some clients this isn't even seen.
* @param array $daysOfWeekToRepeat (Optional). An array of days of the week this event should repeat. Use normal english like Tues, Saturday etc.
* @param array $daysOfWeekToRepeat (Optional). Days of week event should repeat. Use EN like Tues, Saturday etc.
*
* @return array
*/
Expand Down Expand Up @@ -1035,7 +1034,7 @@ protected static function calculateMinutes(DateTime $dateAndTime)
* @param DateTime $dateAndTime The actual Date and Time for this event.
* @param bool $turnOn Should the event turn on or off the timer.
* @param string $name An event name. On some clients this isn't even seen.
* @param array $daysOfWeekToRepeat (Optional). An array of days of the week this event should repeat. Use normal english like Tues, Saturday etc.
* @param array $daysOfWeekToRepeat (Optional) Day of week event should repeat. Use EN like Tues, Saturday etc.
* @param Collection $data specific information depending on if the event is repeating or not.
* @param string $ruleId The ID of the rule to be edited.
*
Expand Down Expand Up @@ -1103,7 +1102,7 @@ protected static function countdownCommonData($type, $delay, $turnOn, $name, $ru
* @param DateTime $startTime The start date/time for the event to begin
* @param DateTime $endTime The end date/time for the event to finish.
* @param string $name An event name. On some clients this isn't even seen.
* @param array $daysOfWeekToRepeat (Optional). An array of days of the week this event should repeat. Use normal english like Tues, Saturday etc.
* @param array $daysOfWeekToRepeat (Optional) Day of week event should repeat. Use EN like Tues, Saturday etc.
* @param Collection $data specific information depending on if the event is repeating or not.
* @param string $ruleId The ID of the rule to be edited.
*
Expand Down Expand Up @@ -1144,4 +1143,4 @@ protected static function antitheftCommonData(
],
];
}
}
}
54 changes: 42 additions & 12 deletions src/TPLinkDevice.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,44 @@ public function __construct(array $config, $deviceName)
$this->deviceName = $deviceName;
}

/**
* Return current power status
*
* @return boolean
*/
public function powerStatus()
{
return (bool)json_decode($this->sendCommand(TPLinkCommand::systemInfo()))->system->get_sysinfo->relay_state;
}

/**
* Toggle the current status of the switch on/off
*
* @return string
*/
public function togglePower()
{
$status = (bool)json_decode($this->sendCommand(TPLinkCommand::systemInfo()))->system->get_sysinfo->relay_state;
return $this->powerStatus() ? $this->sendCommand(TPLinkCommand::powerOff()) : $this->sendCommand(TPLinkCommand::powerOn());
}

return $status ? $this->sendCommand(TPLinkCommand::powerOff()) : $this->sendCommand(TPLinkCommand::powerOn());
/**
* Change the current status of the switch to on
*
* @return string
*/
public function powerOn()
{
return $this->sendCommand(TPLinkCommand::powerOn());
}

/**
* Change the current status of the switch off
*
* @return string
*/
public function powerOff()
{
return $this->sendCommand(TPLinkCommand::powerOff());
}

/**
Expand Down Expand Up @@ -66,11 +94,11 @@ protected function connectToDevice()
"tcp://" . $this->getConfig("ip") . ":" . $this->getConfig("port"),
$errorNumber,
$errorMessage,
5
$this->getConfig('timeout', 5)
);

if ($this->client === false) {
throw new UnexpectedValueException("Failed to connect to {$this->deviceName}: $errorMessage ($errorNumber)");
throw new UnexpectedValueException("Failed connect to {$this->deviceName}: $errorMessage ($errorNumber)");
}
}

Expand All @@ -80,7 +108,7 @@ protected function connectToDevice()
*
* @return mixed
*/
protected function getConfig($key, $default = null)
public function getConfig($key, $default = null)
{
if (is_array($this->config) && isset($this->config[$key])) {
return $this->config[$key];
Expand All @@ -101,12 +129,14 @@ protected function encrypt($string)
$key = 171;

return collect(str_split($string))
->reduce(function ($result, $character) use (&$key) {
$key = $key ^ ord($character);

return $result .= chr($key);
},
"\0\0\0\0");
->reduce(
function ($result, $character) use (&$key) {
$key = $key ^ ord($character);

return $result .= chr($key);
},
"\0\0\0\0"
);
}

/**
Expand All @@ -117,7 +147,7 @@ protected function connectionError()
{
return json_encode([
'success' => false,
'message' => "When sending the command to the smartplug {$this->deviceName}, the connection terminated before the command was sent.",
'message' => "{$this->deviceName} : connection terminated before the command was sent.",
]);
}

Expand Down
Loading