star-cloud/app/Console/Commands/MqttSyncAuth.php
sky121113 588f5659ca [FIX] 修復 MQTT Gateway 啟動崩潰與認證失敗問題
1. 在 mqtt-gateway/main.go 中加入連線重試邏輯 (Redis & MQTT),避免在服務初始化或認證暫時失敗時直接退出。
2. 更新 App/Console/Commands/MqttSyncAuth.php,加入同步 star-cloud-gateway 自身認證資料至 Redis 的邏輯。
3. 修改 compose.yaml,為 mqtt-gateway 加入 restart: always,並為 emqx 加入健康檢查以優化容器啟動流程。
2026-04-17 09:08:18 +08:00

54 lines
1.5 KiB
PHP

<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\Machine\Machine;
use App\Services\Machine\MachineService;
class MqttSyncAuth extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'mqtt:sync-auth';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Sync all machine API tokens to Redis for MQTT authentication';
/**
* Execute the console command.
*/
public function handle(MachineService $machineService)
{
// 1. 同步 Gateway 自身的認證資料 (與 mqtt-gateway/main.go 對應)
$this->info("Syncing star-cloud-gateway auth...");
$gatewayKey = "machine_auth:star-cloud-gateway";
$gatewayPass = hash('sha256', "StarCloudSecret999");
\Illuminate\Support\Facades\Redis::hSet($gatewayKey, 'password', $gatewayPass);
$this->info("Gateway auth synced.");
// 2. 同步所有機台的認證資料
$machines = Machine::withoutGlobalScopes()->get();
$this->info("Syncing " . $machines->count() . " machines to Redis...");
$bar = $this->output->createProgressBar($machines->count());
$bar->start();
foreach ($machines as $machine) {
$machineService->syncMqttAuth($machine);
$bar->advance();
}
$bar->finish();
$this->newLine();
$this->info("Sync completed.");
}
}