|
|
@@ -2,6 +2,7 @@
|
|
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
|
|
+use App\Service\Device\DeviceCommonService;
|
|
|
use Illuminate\Console\Command;
|
|
|
use PhpMqtt\Client\MqttClient;
|
|
|
use PhpMqtt\Client\ConnectionSettings;
|
|
|
@@ -36,44 +37,36 @@ class MqttSubscriber extends Command
|
|
|
*
|
|
|
* @return mixed
|
|
|
*/
|
|
|
+ // App/Console/Commands/MqttSubscriber.php
|
|
|
public function handle()
|
|
|
{
|
|
|
- $server = '47.111.77.194';
|
|
|
- $port = 1883;
|
|
|
- $clientId = 'laravel_backend_worker';
|
|
|
+ $mqtt = new MqttClient('47.111.77.194', 1883, 'PHP_SUB_WORKER');
|
|
|
+ $mqtt->connect((new ConnectionSettings)->setUsername('yonglidev1')->setPassword('tZjUw0kQ'), true);
|
|
|
|
|
|
- $mqtt = new MqttClient($server, $port, $clientId);
|
|
|
+ $this->info("接收进程已启动,监听中...");
|
|
|
+ $service = new DeviceCommonService();
|
|
|
+ $time = time();
|
|
|
+ // 使用通配符监听所有 Read 主题
|
|
|
+ $mqtt->subscribe('/HC/+/ReadRealtimeData/+', function ($topic, $message) use ($service,$time) {
|
|
|
+ if(time()- $time > 2){
|
|
|
+ $message = bin2hex($message);
|
|
|
+ $this->info("【收到】 " . date('H:i:s') . " | Topic: {$topic} | 内容: " .$message);
|
|
|
+ // 1. 将字符串拆分为数组
|
|
|
+ $parts = explode('/', $topic);
|
|
|
|
|
|
- $settings = (new ConnectionSettings)
|
|
|
- ->setUsername('php_server_user')
|
|
|
- ->setPassword('sEcrEt_pAss_123');
|
|
|
-
|
|
|
- $this->info("正在连接到 MQTT Broker...");
|
|
|
-
|
|
|
- $mqtt->connect($settings, true);
|
|
|
-
|
|
|
- // 订阅主题
|
|
|
- $mqtt->subscribe('/wy/119/RealtimeData/DT5/yonglidev1', function ($topic, $message) {
|
|
|
- $this->info("收到消息: $message");
|
|
|
-
|
|
|
- $data = json_decode($message, true);
|
|
|
-
|
|
|
- if (isset($data['total_work'])) {
|
|
|
- // 利用 Laravel 的模型直接入库
|
|
|
- $hours = round($data['total_work'] / 60, 2);
|
|
|
-
|
|
|
-// WorkLog::create([
|
|
|
-// 'device_id' => $data['device_id'] ?? 'unknown',
|
|
|
-// 'minutes' => $data['total_work'],
|
|
|
-// 'hours' => $hours,
|
|
|
-// 'raw_data' => $message,
|
|
|
-// ]);
|
|
|
-
|
|
|
- $this->info("数据已入库: {$hours} 小时");
|
|
|
+ // 2. 获取第 4 位内容(注意数组下标从 0 开始)
|
|
|
+ // 路径:/ (0) HC (1) + (2) ReadRealtimeData (3) + (4)
|
|
|
+ $type = $parts[4] ?? '';
|
|
|
+ $service->dealDevice($type,$message, function($msg) {
|
|
|
+ $this->info($msg); // 这里的 $this 指向 Command
|
|
|
+ });
|
|
|
}
|
|
|
+
|
|
|
+ // 异步交给 Service 处理入库逻辑
|
|
|
+ // app(PlcDataService::class)->handle($topic, $message);
|
|
|
}, 0);
|
|
|
|
|
|
- // 开始死循环监听
|
|
|
+ // 接收进程只需要死循环 loop 即可
|
|
|
$mqtt->loop(true);
|
|
|
}
|
|
|
}
|