star-cloud/app/Services/Machine/MqttService.php
sky121113 1d5aff2f2e [REFACTOR] 遷移遠端管理指令至 MQTT 非同步架構與邏輯優化
1. 實作 MqttService 統一管理 MQTT 指令發送。
2. 遷移「遠端庫存與效期中心」至 MQTT 流程,並加入 batch_no (批號) 支援。
3. 修改 RemoteController 指令中心所有指令同步改由 MQTT 推送。
4. 修正 Go Gateway redis_consumer.go 確保 JSON 格式符合最新規格(移除寫死的 target/message_id)。
5. 實作 ProcessCommandAck 自動更新指令結果、異常回滾 (Rollback) 與機台自動亮燈 (Online)。
6. 完善 mqtt-communication-specs 規格文件,補齊所有指令定義與 ACK 範例。
7. 強化指令狀態保護,確保只有 pending 狀態的指令能被更新結果,防止重複處理。
2026-04-22 11:30:39 +08:00

55 lines
1.8 KiB
PHP

<?php
namespace App\Services\Machine;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Log;
class MqttService
{
/**
* 推播雲端指令 (Downstream Command) 給機台
* 遵循 framework.md 中的 Redis 橋接機制,推入 mqtt_outgoing_commands 佇列,由 Go Gateway 接手發佈。
*
* @param string $serialNo 機台序號
* @param string $command 指令名稱 (例如: update_inventory, dispense)
* @param array $payload 指令的內容資料
* @param string $commandId 唯一指令識別碼 (通常對應 RemoteCommand 的 ID)
* @return bool
*/
public function pushCommand(string $serialNo, string $command, array $payload, string $commandId): bool
{
try {
$message = [
'serial_no' => $serialNo,
'command' => $command,
'payload' => $payload,
'command_id' => (string) $commandId,
'timestamp' => now()->toIso8601String(),
];
// 系統預設 outgoing queue 名稱 (Go Gateway 預設讀取此佇列)
$queueKey = config('app.mqtt_outgoing_queue', 'mqtt_outgoing_commands');
// Laravel 的 Redis Facade 會自動加上 database prefix
Redis::rpush($queueKey, json_encode($message));
Log::info("MQTT Command Pushed to Queue", [
'queue' => $queueKey,
'serial_no' => $serialNo,
'command' => $command,
'command_id' => $commandId
]);
return true;
} catch (\Exception $e) {
Log::error("Failed to push MQTT command", [
'serial_no' => $serialNo,
'command' => $command,
'error' => $e->getMessage()
]);
return false;
}
}
}