66 lines
1.6 KiB
PHP
66 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace NoccyLabs\UPnP\SSDP;
|
|
|
|
use IteratorAggregate;
|
|
use ArrayIterator;
|
|
use NoccyLabs\UPnP\HTTPU\Endpoint;
|
|
use NoccyLabs\UPnP\HTTPU\EndpointException;
|
|
use NoccyLabs\UPnP\HTTPU\MSearchRequest;
|
|
use NoccyLabs\UPnP\HTTPU\MSearchResponse;
|
|
|
|
/**
|
|
* Basic implementation of the SSDP protocol.
|
|
*
|
|
*
|
|
*/
|
|
class Discovery implements IteratorAggregate
|
|
{
|
|
|
|
protected $devices = [];
|
|
|
|
/**
|
|
*
|
|
*
|
|
* @param string $search_type The device type or schema to search for
|
|
* @return int The number of devices found
|
|
*/
|
|
public function discover($search_type, $timeout=1)
|
|
{
|
|
// Set up the endpoint
|
|
try {
|
|
$endpoint = new Endpoint();
|
|
} catch (EndpointException $e) {
|
|
throw new DiscoveryException("Discovery failed", 0, $e);
|
|
}
|
|
|
|
// Clean up previous state
|
|
$this->devices = [];
|
|
|
|
// Create the request
|
|
$request = new MSearchRequest();
|
|
$request->setSearchType($search_type);
|
|
$request->setMaxWait($timeout-1);
|
|
|
|
// Send the request and wait for responses
|
|
$responses = $endpoint->send($request, $timeout);
|
|
foreach ($responses as $response) {
|
|
// Add the relevant responses to the list
|
|
if ($response instanceof MSearchResponse) {
|
|
$device = Device::createFromSchema($response->getLocation(), $response->getIp());
|
|
$this->devices[] = $device;
|
|
}
|
|
}
|
|
|
|
return count($this->devices);
|
|
|
|
}
|
|
|
|
public function getIterator()
|
|
{
|
|
return new ArrayIterator($this->devices);
|
|
}
|
|
|
|
}
|
|
|