PHP code example of oguzhantogay / philips-hue-client

1. Go to this page and download the library: Download oguzhantogay/philips-hue-client library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

oguzhantogay / philips-hue-client example snippets


use OguzhanTogay\HueClient\HueClient;
use OguzhanTogay\HueClient\Discovery\BridgeDiscovery;

// Auto-discover bridges on your network
$discovery = new BridgeDiscovery();
$bridges = $discovery->discover();

if (empty($bridges)) {
    die("No Hue bridges found on network");
}

$bridge = $bridges[0]; // Use first bridge
echo "Found bridge: {$bridge->getId()} at {$bridge->getIp()}\n";

// Create client and authenticate
$client = new HueClient($bridge->getIp());

// First time setup - press bridge button then run:
$username = $client->register('my-app-name', 'my-device-name');
echo "Save this username: {$username}\n";

// For subsequent connections:
$client = new HueClient($bridgeIp, $username);

// Get all lights
$lights = $client->lights()->getAll();

foreach ($lights as $light) {
    echo "{$light->getName()}: {$light->getState()->getStatus()}\n";
}

// Control specific light
$light = $client->lights()->get(1);

// Simple commands
$light->on();
$light->off();
$light->toggle();

// Set properties
$light->setBrightness(75);  // 0-100%
$light->setColor('#FF5733'); // Hex color
$light->setColorTemperature(2700); // Kelvin (2000-6500)

// Chain commands
$light->on()
     ->setBrightness(100)
     ->setColor('#00FF00')
     ->transition(1000); // 1 second transition

// Get all rooms
$rooms = $client->groups()->getRooms();

// Control entire room
$livingRoom = $client->groups()->getByName('Living Room');
$livingRoom->on();
$livingRoom->setBrightness(60);
$livingRoom->setScene('Relax');

// Create custom group
$group = $client->groups()->create('Movie Lights', [1, 3, 5]);
$group->setColor('#0000FF')->dim(20);

// Control all lights
$client->groups()->all()->off();

// List available scenes
$scenes = $client->scenes()->getAll();

foreach ($scenes as $scene) {
    echo "{$scene->getName()} - Room: {$scene->getGroup()}\n";
}

// Activate scene
$client->scenes()->activate('Sunset');

// Create custom scene
$scene = $client->scenes()->create(
    name: 'Movie Time',
    lights: [
        1 => ['on' => true, 'brightness' => 30, 'color' => '#0000FF'],
        2 => ['on' => false],
        3 => ['on' => true, 'brightness' => 20, 'color' => '#FF0000']
    ]
);

use OguzhanTogay\HueClient\Effects\ColorLoop;
use OguzhanTogay\HueClient\Effects\Breathing;
use OguzhanTogay\HueClient\Effects\Alert;

// Color loop effect
$effect = new ColorLoop($client);
$effect->start($light, duration: 30); // 30 seconds

// Breathing effect
$breathing = new Breathing($client);
$breathing->start($light, '#FF0000', speed: 'slow');

// Alert flash
$alert = new Alert($client);
$alert->flash($light, times: 3);

// Custom animation
$light->animate([
    ['color' => '#FF0000', 'duration' => 1000],
    ['color' => '#00FF00', 'duration' => 1000],
    ['color' => '#0000FF', 'duration' => 1000],
], repeat: 5);

// Create schedule
$schedule = $client->schedules()->create(
    name: 'Morning Wake Up',
    command: $client->groups()->getByName('Bedroom')->sunrise(duration: 900),
    time: '07:00:00',
    repeat: ['monday', 'tuesday', 'wednesday', 'thursday', 'friday']
);

// One-time schedule
$client->schedules()->once(
    name: 'Party Lights',
    command: $client->groups()->all()->party(),
    dateTime: '2024-12-31 23:00:00'
);

// Sunset/sunrise schedules
$client->schedules()->atSunset(
    command: $client->groups()->getByName('Garden')->on()
);

// Listen for light state changes
$client->events()->listen(function($event) {
    if ($event->getType() === 'light.state_changed') {
        echo "Light {$event->getLightId()} changed\n";
        echo "New state: " . json_encode($event->getData()) . "\n";
    }
});

// Subscribe to specific events
$client->events()->subscribe('motion.detected', function($event) {
    $client->groups()->getByName('Hallway')->on();
});

// config/hue.php (auto-published)
return [
    'default' => 'main',
    'bridges' => [
        'main' => [
            'ip' => env('HUE_BRIDGE_IP'),
            'username' => env('HUE_USERNAME'),
            'options' => [
                'timeout' => env('HUE_TIMEOUT', 5),
                'cache_enabled' => env('HUE_CACHE_ENABLED', true),
                'retry_attempts' => env('HUE_RETRY_ATTEMPTS', 3),
            ]
        ],
        // Multiple bridges supported
        'office' => [
            'ip' => env('HUE_BRIDGE_IP_2'),
            'username' => env('HUE_USERNAME_2'),
        ]
    ],
    'auto_discovery' => env('HUE_AUTO_DISCOVERY', true),
];

// config/app.php
'providers' => [
    // ...
    OguzhanTogay\HueClient\Laravel\HueServiceProvider::class,
],

'aliases' => [
    // ...
    'Hue' => OguzhanTogay\HueClient\Laravel\Facades\Hue::class,
],

use OguzhanTogay\HueClient\Laravel\Facades\Hue;
use OguzhanTogay\HueClient\HueClient;
use OguzhanTogay\HueClient\ConnectionPool;

// Using Facade
Hue::lights()->getAll();
Hue::groups()->getByName('Living Room')->on();
Hue::scenes()->activate('Movie Time');

// Using Service Container
$hue = app(HueClient::class);
$hue->lights()->get(1)->setColor('#FF5733');

// Multiple Bridges
$pool = app(ConnectionPool::class);
$results = $pool->broadcastToAll(function($client) {
    return $client->groups()->all()->off();
});

// In Controllers
class LightController extends Controller
{
    public function __construct(private HueClient $hue) {}

    public function toggleLight(int $lightId)
    {
        $light = $this->hue->lights()->get($lightId);
        $light->toggle();
        
        return response()->json([
            'success' => true,
            'light' => $light->getName(),
            'status' => $light->getState()->isOn() ? 'on' : 'off'
        ]);
    }
}

// Background Jobs
class MorningRoutineJob implements ShouldQueue
{
    public function handle(HueClient $hue): void
    {
        $bedroom = $hue->groups()->getByName('Bedroom');
        $bedroom->sunrise(600); // 10 minute sunrise
    }
}

// Event Listeners
class MotionDetectedListener
{
    public function handle(MotionDetected $event, HueClient $hue): void
    {
        $hue->groups()->getByName($event->room)->on();
    }
}

// config/bundles.php
return [
    // ...
    OguzhanTogay\HueClient\Symfony\HueBundle::class => ['all' => true],
];

// In Controllers
use OguzhanTogay\HueClient\HueClient;
use OguzhanTogay\HueClient\ConnectionPool;

class LightController extends AbstractController
{
    public function __construct(
        private HueClient $hueClient,
        private ConnectionPool $connectionPool
    ) {}

    #[Route('/lights', methods: ['GET'])]
    public function lights(): JsonResponse
    {
        $lights = $this->hueClient->lights()->getAll();
        
        return $this->json(array_map(function($light) {
            return [
                'id' => $light->getId(),
                'name' => $light->getName(),
                'state' => $light->getState()->toArray()
            ];
        }, $lights));
    }

    #[Route('/lights/{id}/toggle', methods: ['POST'])]
    public function toggleLight(int $id): JsonResponse
    {
        $light = $this->hueClient->lights()->get($id);
        $light->toggle();
        
        return $this->json([
            'success' => true,
            'status' => $light->getState()->isOn() ? 'on' : 'off'
        ]);
    }
}

// In Services
#[AsAlias('app.hue_service')]
class HueService
{
    public function __construct(private HueClient $hueClient) {}

    public function createMoodLighting(string $room, string $mood): void
    {
        $group = $this->hueClient->groups()->getByName($room);
        
        match($mood) {
            'relax' => $group->setColor('#FF8C00')->setBrightness(30),
            'focus' => $group->setColor('#FFFFFF')->setBrightness(90),
            'party' => $group->setColor('#FF00FF')->setBrightness(100),
            default => $group->on()
        };
    }
}

// Event Subscribers
class HueEventSubscriber implements EventSubscriberInterface
{
    public function __construct(private HueClient $hueClient) {}

    public static function getSubscribedEvents(): array
    {
        return [
            'app.user_arrived_home' => 'onUserArrivedHome',
            'app.bedtime' => 'onBedtime',
        ];
    }

    public function onUserArrivedHome(): void
    {
        $this->hueClient->scenes()->activate('Welcome Home');
    }

    public function onBedtime(): void
    {
        $this->hueClient->groups()->all()->sunset(300);
    }
}



$config = [
    'bridge_ip' => '192.168.1.100',
    'username' => 'your-username'
];

$hue = new \OguzhanTogay\HueClient\HueClient(
    $config['bridge_ip'], 
    $config['username']
);

use OguzhanTogay\HueClient\ConnectionPool;

$pool = new ConnectionPool();
$pool->addBridge('192.168.1.100', 'username1');
$pool->addBridge('192.168.1.101', 'username2');

// Health check all bridges
$health = $pool->healthCheck();

// Broadcast action to all bridges
$results = $pool->broadcastToAll(function($client) {
    return $client->groups()->all()->on();
});

$client = new HueClient($bridgeIp, $username, [
    'cache_enabled' => true,
    'cache_type' => 'redis', // or 'filesystem'
    'retry_attempts' => 5,
    'timeout' => 10
]);

// Automatic caching and retry on failures
$lights = $client->lights()->getAll(); // Cached for 10 seconds
bash
# Discover bridges
php artisan hue:discover

# Setup bridge authentication  
php artisan hue:setup --discover

# Start REST API server
php artisan hue:serve --port=8080

# Clear Hue cache
php artisan cache:clear --tags=hue