MqttPusher.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Service\Device\DeviceCommonService;
  4. use Illuminate\Console\Command;
  5. use PhpMqtt\Client\MqttClient;
  6. use PhpMqtt\Client\ConnectionSettings;
  7. class MqttPusher extends Command
  8. {
  9. /**
  10. * The name and signature of the console command.
  11. *
  12. * @var string
  13. */
  14. protected $signature = 'mqtt:pusher';
  15. /**
  16. * The console command description.
  17. *
  18. * @var string
  19. */
  20. protected $description = 'Command pusher';
  21. /**
  22. * Create a new command instance.
  23. *
  24. * @return void
  25. */
  26. public function __construct()
  27. {
  28. parent::__construct();
  29. }
  30. /**
  31. * Execute the console command.
  32. *
  33. * @return mixed
  34. */
  35. // App/Console/Commands/MqttSubscriber.php
  36. // App/Console/Commands/MqttPublisher.php
  37. public function handle()
  38. {
  39. $service = new DeviceCommonService();
  40. $deviceConfigs = $service->deviceList;
  41. $this->info("发送进程启动(短连接模式)...");
  42. $m = 3;
  43. while (true) {
  44. foreach ($deviceConfigs as $dev) {
  45. try {
  46. // 1. 每次发送前创建新实例
  47. $mqtt = new MqttClient('47.111.77.194', 1883, 'PHP_PUB');
  48. $settings = (new ConnectionSettings)
  49. ->setUsername('HCWDL2')
  50. ->setPassword('HCWDL2')
  51. ->setConnectTimeout(5);
  52. // 2. 连接 -> 发送 -> 断开
  53. $mqtt->connect($settings, true);
  54. $pubTopic = "/HC/{$dev['type']}/WriteRealtimeData/{$dev['id']}";
  55. $hex = str_replace(' ', '', $dev['cmd']);
  56. $mqtt->publish($pubTopic, hex2bin($hex), 0);
  57. $this->info("【发送成功】 " . date('H:i:s') . " -> {$pubTopic}|{$hex}");
  58. $mqtt->disconnect(); // 主动断开,不占用服务端资源
  59. } catch (\Exception $e) {
  60. $this->error("【发送异常】 " . date('H:i:s') . " | " . $e->getMessage());
  61. }
  62. // 3. 严格等待 30 秒
  63. $this->info("等待 {$m} 秒中...");
  64. sleep($m);
  65. }
  66. // 防止数组为空导致死循环空转
  67. if (empty($deviceConfigs)) {
  68. sleep(10);
  69. }
  70. }
  71. }
  72. }