php-mqtt Laravel Client

repository·master·Indexed 42 days ago

https://github.com/php-mqtt/laravel-client

A Laravel wrapper for the php-mqtt/client package that provides a seamless way to connect to MQTT brokers, publish messages, and subscribe to topics using Laravel's Facades and configuration patterns. It includes a ConnectionManager for managing multiple connections and an MQTT facade for simplified interaction with MQTT services.

Tokens
3K
Snippets
14
Records
16
Agent score
53%

What's inside php-mqtt-laravel-client

  1. Access the underlying MqttClient for advanced features

    master

    The Laravel client is a wrapper around php-mqtt/client. You can access the full power of the underlying library by retrieving the MqttClient contract via the MQTT facade.

    use PhpMqtt\Client\Facades\MQTT;
    
    /** @var \PhpMqtt\Client\Contracts\MqttClient $mqtt */
    $mqtt = MQTT::connection('connection_name');
    // Now you have access to all methods defined in \PhpMqtt\Client\Contracts\MqttClient
  2. Install php-mqtt/laravel-client

    master

    Install the package via Composer. The package uses Laravel auto-discovery to register the MqttClientServiceProvider and the MQTT facade.

    composer require php-mqtt/laravel-client
  3. Publish the MQTT configuration file

    master

    After installation, publish the configuration file to config/mqtt-client.php to customize your connection settings.

    php artisan vendor:publish --provider="PhpMqtt\Client\MqttClientServiceProvider" --tag="config"
  4. Configure multiple MQTT connections

    master

    You can define multiple named connections in config/mqtt-client.php. Use the default_connection key to specify which connection to use when no name is provided. It is recommended to use environment variables for sensitive settings.

    'default_connection' => 'private',
    
    'connections' => [
        'private' => [
            'host' => 'mqtt.example.com',
            'port' => 1883,
        ],
        'public' => [
            'host' => 'test.mosquitto.org',
            'port' => 1883,
        ],
    ],
  5. Configure the MQTT client

    master

    The package uses a configuration file named mqtt-client.php. To customize the MQTT settings, you should publish the configuration file to your application's config directory using the following Artisan command:

    php artisan vendor:publish --tag=config

    Once published, you can modify the settings in config/mqtt-client.php. The package accesses these settings using the mqtt-client configuration key.

  6. Subscribe to topics

    master

    Subscribing requires an event loop to process incoming messages. Register the subscription first, then start the loop.

    use PhpMqtt\Client\Facades\MQTT;
    
    /** @var \PhpMqtt\Client\Contracts\MqttClient $mqtt */
    $mqtt = MQTT::connection();
    
    $mqtt->subscribe('some/topic', function (string $topic, string $message) {
        echo sprintf('Received QoS level 1 message on topic [%s]: %s', $topic, $message);
    }, 1);
    
    $mqtt->loop(true);
  7. Publish a message with QoS level 0

    master

    For simple, one-off publishing where QoS 0 is sufficient, use the MQTT facade directly. This method implicitly calls MQTT::connection() but does not close the connection automatically. Note that MQTT::publish($topic, $message) always uses QoS level 0.

    use PhpMqtt\Client\Facades\MQTT;
    
    // Basic publish
    MQTT::publish('some/topic', 'Hello World!');
    
    // Publish with retain flag and specific connection name
    // MQTT::publish($topic, $message, $retain, $connectionName)
    MQTT::publish('some/topic', 'Hello World!', true, 'public');
    
    // Manually disconnect if needed
    MQTT::disconnect();
  8. Publish messages with QoS level 1 or 2

    master

    To use QoS 1 or 2, you must interact with the MqttClient instance directly and run an event loop. The loop ensures that acknowledgements are received from the broker.

    To exit the loop once all resend queues are cleared, call $mqtt->loop(true, true). Alternatively, you can call $mqtt->interrupt() to exit during the next iteration.

    use PhpMqtt\Client\Facades\MQTT;
    
    /** @var \PhpMqtt\Client\Contracts\MqttClient $mqtt */
    $mqtt = MQTT::connection();
    
    // QoS 1
    $mqtt->publish('some/topic', 'foo', 1);
    
    // QoS 2 with retain flag
    $mqtt->publish('some/other/topic', 'bar', 2, true);
    
    // Start loop and exit once all resend queues are cleared
    $mqtt->loop(true, true);
  9. Configure MQTT connections in Laravel

    master

    Connections are managed via a configuration array. Each connection is identified by a key under connections. The manager uses a default_connection key (defaulting to 'default') to determine which connection to use when a name is not explicitly provided.

    Connection Configuration Keys

    When defining a connection in your config, you can use the following keys:

    • host: The broker hostname.
    • port: The broker port (defaults to 1883).
    • client_id: The unique MQTT client identifier.
    • protocol: The MQTT protocol version (defaults to MqttClient::MQTT_3_1).
    • use_clean_session: Boolean indicating if a clean session should be used (defaults to true).
    • repository: The class name of the repository to use (defaults to Repository::class).
    • enable_logging: Boolean to enable logging (defaults to true).
    • log_channel: The Laravel log channel to use if logging is enabled.
    • connection_settings: An array of advanced settings (see ConnectionSettings).
    • auth.username: Username for authentication.
    • auth.password: Password for authentication.
    • tls.enabled: Boolean to enable TLS.
    • tls.allow_self_signed_certificate: Boolean for TLS self-signed certs.
    • tls.verify_peer: Boolean to verify TLS peer.
    • tls.verify_peer_name: Boolean to verify TLS peer name.
    • tls.ca_file: Path to the CA file.
    • tls.ca_path: Path to the CA path.
    • tls.client_certificate_file: Path to the client certificate.
    • tls.client_certificate_key_file: Path to the client certificate key.
    • tls.client_certificate_key_passphrase: Passphrase for the client certificate key.
    • tls.alpn: ALPN protocols.
    • last_will.topic: Topic for the Last Will and Testament.
    • last_will.message: Message for the Last Will and Testament.
    • last_will.quality_of_service: QoS for the Last Will.
    • last_will.retain: Whether the Last Will is retained.
    • auto_reconnect.enabled: Enable automatic reconnection.
    • auto_reconnect.max_reconnect_attempts: Maximum number of reconnection attempts.
    • auto_reconnect.delay_between_reconnect_attempts: Delay between attempts.
  10. Publish a message with QoS 0 using ConnectionManager

    master

    The publish() method provides a shortcut to send a message with a Quality of Service (QoS) level of QOS_AT_MOST_ONCE (0). You can specify the topic, the message, and whether the message should be retained. You can also specify which connection to use by passing its name.

    // Publish to the default connection
    $connectionManager->publish('my/topic', 'hello world');
    
    // Publish with retention to a specific connection
    $connectionManager->publish('my/topic', 'hello world', true, 'specific_connection');
  11. Disconnect an MQTT connection

    master

    Use the disconnect() method to close an active connection. If no connection name is provided, it will disconnect the default_connection. This method also removes the connection from the manager's internal cache.

    // Disconnect the default connection
    $connectionManager->disconnect();
    
    // Disconnect a specific connection
    $connectionManager->disconnect('broker_name');