# MQTT Module Changes - Socket-Based Implementation

## Summary
Replaced REST API-based MQTT implementation with proper MQTT protocol using native PHP sockets (no vendor dependencies).

## Problem
- Original implementation attempted HTTP REST calls to `/api/publish` endpoint
- MQTT broker (btim.brellahost.com.au) only supports standard MQTT protocol on ports 1883/8883
- No REST API exists on the broker, causing "Empty reply from server" errors

## Solution
Updated all three module files to use proper MQTT protocol implementation:

### 1. MqttModule.php
**Changes:**
- Updated default port from 9001 (WebSocket) to 8883 (TLS MQTT)
- Added `$timeout` property (default: 10 seconds)
- Updated comments to reflect standard MQTT protocol support
- Added timeout parameter to `getClient()` method

**Configuration Support:**
- Standard MQTT: ports 1883 (non-TLS), 8883 (TLS)
- WebSocket: port 9001 (if needed in future)
- Configurable timeout, TLS, authentication

### 2. MqttClient.php
**Replaced entire file with proper MQTT implementation:**

**Old Implementation (REST API):**
- Used cURL to make HTTP POST requests
- Attempted to call `/api/publish` and `/api/topic` endpoints
- Would fail with "Empty reply from server"

**New Implementation (Native PHP Sockets):**
- Uses native PHP `stream_socket_client()` - no vendor dependencies
- Raw MQTT 3.1.1 protocol implementation
- Implements standard MQTT methods:
  - `connect()` - establishes MQTT connection with CONNECT/CONNACK handshake
  - `disconnect()` - cleanly closes connection with DISCONNECT packet
  - `publish()` - publishes messages using MQTT PUBLISH packets
  - `createTopic()` - kept for backward compatibility (MQTT creates topics implicitly)
- Automatic connection management (connects on first publish)
- Proper error handling with exceptions
- Connection state tracking
- TLS configuration with self-signed certificate support via stream context

**Features:**
- JSON encoding for array/object messages
- QoS levels 0, 1, 2 support
- Message retention support
- Configurable timeouts
- Debug logging

### 3. MqttControllerTrait.php
**Changes:**
- Removed commented-out alternative implementation
- Added try-catch error handling to `publishMqtt()` method
- Added new method `getMqttConnectionInfo()` to get connection details
- Updated documentation
- Improved error logging

## Usage

### Module Configuration (config/main.php)
```php
'mqtt' => array(
    'class' => 'application.modules.mqtt.MqttModule',
    'host' => 'btim.brellahost.com.au',
    'port' => 8883,           // 1883 for non-TLS, 8883 for TLS
    'secure' => true,         // Enable TLS
    'clientIdPrefix' => 'pstat.dev_',
    'username' => '',         // Optional
    'password' => '',         // Optional
    'timeout' => 10,          // Connection timeout in seconds
    'debug' => YII_DEBUG,     // Enable debug logging
),
```

### Controller Usage
```php
class MyController extends Controller
{
    use MqttControllerTrait;
    
    public function actionTest()
    {
        // Publish a message
        $result = $this->publishMqtt('test/topic', 'test message');
        
        // Publish JSON data
        $data = ['key' => 'value', 'timestamp' => time()];
        $result = $this->publishMqtt('test/topic', $data, ['qos' => 1, 'retain' => false]);
        
        // Get connection info
        $connInfo = $this->getMqttConnectionInfo();
    }
}
```

### Direct Client Usage
```php
$client = Yii::app()->getModule('mqtt')->getClient();
$client->publish('topic/name', 'message', ['qos' => 1, 'retain' => false]);
```

## Technical Details

### Dependencies
- **No external vendor dependencies required**
- PHP 7.4+
- OpenSSL extension for TLS support
- Native PHP sockets support (stream_socket_client)

### MQTT Protocol
- Uses standard MQTT 3.1.1 protocol
- Direct TCP socket connection to broker
- Supports TLS/SSL encryption
- Proper CONNECT/PUBLISH/DISCONNECT packet handling

### Backward Compatibility
- All existing controller methods work unchanged
- Same method signatures maintained
- Enhanced error handling prevents silent failures

## Testing

### Test Script
A test script `test_mqtt.php` has been created in the project root to verify:
1. Module configuration
2. Client creation
3. Connection info retrieval
4. Message publishing (JSON and string)

Run with: `php test_mqtt.php`

### Verification
Check MQTT broker logs or use MQTT subscriber to verify messages are received:
```bash
# Using mosquitto_sub to test
mosquitto_sub -h btim.brellahost.com.au -p 8883 -t "poolstat/#" --capath /etc/ssl/certs
```

## Benefits
1. **Works with broker** - Uses actual MQTT protocol instead of non-existent REST API
2. **Reliable** - Proper connection management and error handling
3. **Secure** - Full TLS support with configurable settings
4. **Compatible** - Maintains same API, no code changes needed in controllers
5. **Flexible** - Supports both TLS (8883) and non-TLS (1883) ports
6. **Debuggable** - Comprehensive logging when debug mode enabled

## Files Modified
- `protected/modules/mqtt/MqttModule.php`
- `protected/modules/mqtt/components/MqttClient.php`
- `protected/modules/mqtt/components/MqttControllerTrait.php`

## Files Created
- `test_mqtt.php` - Test script for verification
- `protected/modules/mqtt/CHANGES.md` - This documentation
