Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Portflow Laravel Package

hamzi/portflow

PortFlow connects serial hardware (thermal printers, barcode/RFID scanners, scales, IoT boards) to Laravel via a driver-based architecture. Parse raw bytes into typed events, queue routes, and printing workflows, with Web Serial API support for browser integration.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require hamzi/portflow:^0.7.0
   php artisan vendor:publish --provider="Hamzi\PortFlow\PortFlowServiceProvider" --tag="portflow-config"
  • Publishes updated config (config/portflow.php) with new webhook driver and CLI tool settings.
  1. First Use Case:

    • Webhook Driver Example (new in v0.7.0):
      use Hamzi\PortFlow\Facades\PortFlow;
      
      // Configure webhook endpoint
      $webhook = PortFlow::connect('webhook', [
          'url' => 'https://your-app.com/api/device-webhook',
          'secret' => 'your_shared_secret',
      ]);
      
      // Simulate receiving data (e.g., from a hardware device)
      $webhook->receive([
          'device_id' => 'USB001',
          'data' => 'BARCODE_123',
          'timestamp' => now(),
      ]);
      
    • Diagnostic CLI Tool (new in v0.7.0):
      php artisan portflow:diagnose
      
      Lists connected devices, driver statuses, and buffer stats.
  2. Where to Look First:

    • Config: config/portflow.php (new webhook driver and cli tool settings).
    • Drivers: app/Drivers/ (custom drivers now support shouldPersistBuffer() for buffer optimizations).
    • CLI Tool: vendor/bin/portflow (interactive diagnostic commands).
    • Webhook Docs: Updated Webhook Driver Guide in the changelog.

Implementation Patterns

Core Workflows

  1. Webhook Integration (New in v0.7.0):

    • Server-Side: Validate incoming webhook payloads:
      PortFlow::on('webhook.received', function ($payload) {
          if (!hash_equals(config('portflow.webhook.secret'), $payload['signature'])) {
              abort(403);
          }
          // Process payload (e.g., store in DB or trigger actions)
      });
      
    • Client-Side: Send data to your Laravel app from external devices (e.g., IoT sensors):
      curl -X POST https://your-app.com/api/device-webhook \
           -H "Content-Type: application/json" \
           -d '{"device_id":"SENSOR_001","data":"temperature=25","signature":"..."}'
      
    • Use Case: Replace polling with event-driven updates (e.g., real-time inventory tracking).
  2. Diagnostic CLI Tool (New in v0.7.0):

    • Monitor Connections:
      php artisan portflow:diagnose --list-devices
      
    • Check Buffer Status:
      php artisan portflow:diagnose --buffer-stats
      
    • Interactive Mode:
      php artisan portflow:diagnose --interactive
      
      (Useful for debugging live systems without restarting.)
  3. Buffer Persistence Optimizations:

    • Enable for Critical Drivers: Configure in config/portflow.php:
      'buffer' => [
          'enabled' => true,
          'persist_drivers' => ['escpos', 'barcode'], // Only persist for these drivers
          'max_size' => 1024, // KB
      ],
      
    • Custom Drivers: Implement shouldPersistBuffer() in your driver:
      class CustomDriver extends AbstractDriver {
          public function shouldPersistBuffer(): bool {
              return $this->config['persist_buffer'] ?? false;
          }
      }
      
  4. Cleaner Architecture:

    • Service Provider: The PortFlowServiceProvider now registers the webhook driver and CLI tool by default. Override in AppServiceProvider if needed:
      public function boot() {
          $this->app->make('Hamzi\PortFlow\PortFlowServiceProvider')->registerWebhookDriver();
      }
      
    • Event System: New events for webhook interactions:
      PortFlow::on('webhook.validated', fn($payload) => Log::info('Valid payload received'));
      PortFlow::on('webhook.invalid', fn($payload) => Log::warning('Invalid payload rejected'));
      
  5. Frontend-Backend Sync (Updated):

    • Webhook + Web Serial: Use webhooks to sync device state changes (e.g., printer offline) to all connected clients:
      // Frontend: Listen for webhook-triggered events via Laravel Echo
      Echo.channel('device-updates')
          .listen('DeviceStatusUpdated', (e) => {
              console.log('Printer status:', e.status);
          });
      

Integration Tips

  • Laravel Horizon: Process webhook payloads asynchronously:
    PortFlow::on('webhook.received', function ($payload) {
        dispatch(new ProcessWebhookJob($payload));
    });
    
  • Laravel Telescope: Monitor webhook activity in the webhook tab (if using the telescope logging driver).
  • Testing Webhooks: Use the PortFlow::mockDriver('webhook') to simulate incoming payloads:
    PortFlow::mockDriver('webhook', [
        'receive' => fn($payload) => $payload['data'] === 'TEST_123',
    ]);
    
  • Security: Rotate webhook.secret in config/portflow.php periodically and use Laravel's signed helper for additional protection:
    $signedPayload = request()->input('payload');
    $decoded = base64_decode($signedPayload);
    

Gotchas and Tips

Common Pitfalls

  1. Webhook Driver Quirks:

    • Signature Mismatches: Ensure the secret in config/portflow.php matches the client's signature. Use hash_equals() to avoid timing attacks.
    • Rate Limiting: Webhook endpoints may be hit rapidly. Use Laravel middleware to throttle requests:
      Route::middleware(['throttle:10,1'])->post('/api/device-webhook', ...);
      
    • Payload Size: Large payloads may exceed PHP's post_max_size. Stream data or chunk it:
      $webhook->receiveChunked($data, 1024); // New in v0.7.0
      
  2. Buffer Persistence:

    • Disk I/O Overhead: Persisting buffers to disk adds latency. Monitor with the CLI tool:
      php artisan portflow:diagnose --buffer-stats
      
      Disable for high-frequency, low-latency drivers (e.g., real-time sensors).
    • Corruption Risk: Ensure your storage/app/portflow_buffers directory is writable and backed up.
  3. CLI Tool Limitations:

    • Permissions: The CLI tool requires access to system devices. Run with sudo if needed (not recommended for production):
      sudo php artisan portflow:diagnose
      
    • Cross-Platform: Device paths (e.g., /dev/ttyUSB0 vs. COM3) may differ. Use the --normalize-paths flag:
      php artisan portflow:diagnose --normalize-paths
      
  4. Breaking Changes in v0.7.0:

    • Driver Registration: Custom drivers must now implement shouldPersistBuffer() if they support buffer persistence. Old drivers will default to false.
    • Webhook Events: The data.received event is now split into webhook.received (raw) and webhook.validated (processed). Update your listeners.
    • Deprecated: The PortFlow::rawWrite() method is deprecated. Use $driver->write() directly.
  5. Diagnostic Tool False Positives:

    • The CLI tool may report "disconnected" devices if the underlying system API (e.g., Web Serial) is unavailable. Test in a controlled environment first.

Debugging Tips

  1. Webhook Debugging:

    • Enable verbose logging for webhook events:
      PortFlow::setLogLevel(Log::DEBUG);
      
    • Check storage/logs/portflow.log for raw payloads and validation errors.
    • Use Postman to test webhook endpoints with sample payloads:
      {
          "device_id": "TEST_DEVICE",
          "data": "sample_data",
          "signature": "sha256:your_shared_secret"
      }
      
  2. Buffer Issues:

    • Disk Full: Monitor buffer disk usage with:
      php artisan portflow:diagnose --buffer-usage
      
    • **Corrupted
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php
trappistes/laravel-custom-fields
splash/sonata-admin
splash/metadata