deviceList; $this->info("发送进程启动(短连接模式)..."); $m = 10; while (true) { foreach ($deviceConfigs as $dev) { try { // 1. 每次发送前创建新实例 $mqtt = new MqttClient('47.111.77.194', 1883, 'PHP_PUB'); $settings = (new ConnectionSettings) ->setUsername('HCWDL2') ->setPassword('HCWDL2') ->setConnectTimeout(5); // 2. 连接 -> 发送 -> 断开 $mqtt->connect($settings, true); $pubTopic = "/HC/{$dev['type']}/WriteRealtimeData/{$dev['id']}"; $hex = str_replace(' ', '', $dev['cmd']); $mqtt->publish($pubTopic, hex2bin($hex), 0); $this->info("【发送成功】 " . date('H:i:s') . " -> {$pubTopic}|{$hex}"); $mqtt->disconnect(); // 主动断开,不占用服务端资源 } catch (\Exception $e) { $this->error("【发送异常】 " . date('H:i:s') . " | " . $e->getMessage()); } // 3. 严格等待 30 秒 $this->info("等待 {$m} 秒中..."); sleep($m); } // 防止数组为空导致死循环空转 if (empty($deviceConfigs)) { sleep(10); } } } }