| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- <?php
- namespace App\Console\Commands;
- use App\Service\Device\DeviceCommonService;
- use Illuminate\Console\Command;
- use PhpMqtt\Client\MqttClient;
- use PhpMqtt\Client\ConnectionSettings;
- class MqttPusher extends Command
- {
- /**
- * The name and signature of the console command.
- *
- * @var string
- */
- protected $signature = 'mqtt:pusher';
- /**
- * The console command description.
- *
- * @var string
- */
- protected $description = 'Command pusher';
- /**
- * Create a new command instance.
- *
- * @return void
- */
- public function __construct()
- {
- parent::__construct();
- }
- /**
- * Execute the console command.
- *
- * @return mixed
- */
- // App/Console/Commands/MqttSubscriber.php
- // App/Console/Commands/MqttPublisher.php
- public function handle()
- {
- $service = new DeviceCommonService();
- $deviceConfigs = $service->deviceList;
- $this->info("发送进程启动(短连接模式)...");
- $m = 3;
- 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);
- }
- }
- }
- }
|