cqp 3 minggu lalu
induk
melakukan
691d6092e5

+ 9 - 5
app/Http/Controllers/Api/JobController.php

@@ -2,6 +2,8 @@
 
 namespace App\Http\Controllers\Api;
 
+use App\Jobs\ManDeviceJobHc;
+use App\Jobs\ManDeviceJobJLWM;
 use App\Jobs\ManDeviceJobLf;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Redis;
@@ -10,8 +12,6 @@ class JobController extends BaseController
 {
     //有人云(朗峰)
     public function processDataJobAddDeviceManLf(Request $request){
-        $param = $request->all();
-//        if (empty($param['data']) || empty($param['data']['dataPoints'])) return;
 
         dispatch(new ManDeviceJobLf($request->all()))->onQueue('man_device_lf');
 
@@ -19,10 +19,14 @@ class JobController extends BaseController
     }
 
     public function processDataJobAddDeviceManHc(Request $request){
-        $param = $request->all();
-//        if (empty($param['data']) || empty($param['data']['dataPoints'])) return;
 
-//        dispatch(new ManDeviceJobLf($request->all()))->onQueue('man_device_lf');
+        dispatch(new ManDeviceJobHc($request->all()))->onQueue('man_device_hc');
+
+        echo $request->get('verify');die;
+    }
+
+    public function processDataJobAddDeviceManJLWM(Request $request){
+        dispatch(new ManDeviceJobJLWM($request->all()))->onQueue('man_device_jlwm');
 
         echo $request->get('verify');die;
     }

+ 163 - 0
app/Jobs/ManDeviceJobHc.php

@@ -0,0 +1,163 @@
+<?php
+
+namespace App\Jobs;
+
+use App\Service\ClearDataService;
+use Illuminate\Bus\Queueable;
+use Illuminate\Contracts\Queue\ShouldQueue;
+use Illuminate\Foundation\Bus\Dispatchable;
+use Illuminate\Queue\InteractsWithQueue;
+use Illuminate\Queue\SerializesModels;
+use Illuminate\Support\Facades\Log;
+use Symfony\Component\Console\Output\OutputInterface;
+
+class ManDeviceJobHc implements ShouldQueue
+{
+    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
+
+    protected $data;
+    protected $url;
+
+    /**
+     * Create a new job instance.
+     *
+     * @return void
+     */
+    public function __construct($data)
+    {
+        $this->data = $data;
+        $this->url = config('ip.zslf');
+    }
+
+    /**
+     * Execute the job.
+     *
+     * @return void
+     */
+    public function handle()
+    {
+        try {
+            if (empty($this->data['data'])) return;
+
+            $deviceId = $this->data['data']['deviceId'];
+            $dataPoints = $this->data['data']['dataPoints'] ?? [];
+
+            if ($this->data['type'] == "dataPoint") {
+                $redisKey = 'buffer:hengchang_data';
+                $batchSize = 500;
+
+                // 1. 整理数据并推入 Redis 列表
+                $records = [];
+                foreach ($dataPoints as $value) {
+                    if (empty($value['value'])) continue;
+
+                    $records[] = json_encode([
+                        'machine_code' => $deviceId . $value['dataPointId'],
+                        'param_value'   => floatval($value['value']),
+                        'time'    => $this->getNowDay()
+                    ]);
+                }
+
+                if (!empty($records)) {
+                    // 批量推入 Redis
+                    \Illuminate\Support\Facades\Redis::rpush($redisKey, ...$records);
+                }
+
+                // 2. 检查 Redis 里的总条数
+                $currentCount = \Illuminate\Support\Facades\Redis::llen($redisKey);
+
+                // 3. 达到 500 条,执行批量发送
+
+                if ($currentCount >= $batchSize) {
+                    $this->processBatchSend($redisKey, $batchSize);
+                }
+            }
+        } catch (\Exception $exception) {
+            Log::channel('apiLog')->info('hc开始位置', ["param" => $exception->getMessage()]);
+            $this->delete();
+        }
+    }
+
+    /**
+     * 批量处理发送逻辑
+     */
+    protected function processBatchSend($redisKey, $batchSize)
+    {
+        // 原子化弹出 500 条数据
+        $rawRecords = \Illuminate\Support\Facades\Redis::pipeline(function ($pipe) use ($redisKey, $batchSize) {
+            for ($i = 0; $i < $batchSize; $i++) {
+                $pipe->lpop($redisKey);
+            }
+        });
+
+        $batchData = array_map(fn($item) => json_decode($item, true), array_filter($rawRecords));
+
+        if (empty($batchData)) return;
+
+        list($status,$msg) = $this->sendToDeviceBatch($batchData);
+        if(! $status) echo $msg;
+    }
+
+    public function sendToDeviceBatch($data){
+        list($status,$token) = ClearDataService::getTokenHc();
+        if(! $status) return [false, $token];
+
+        $url = $this->url . "api/module-data/hc_device_machine_record/hc_device_machine_record/diy/create_data";
+        $post = [
+            'data' => [
+                'device_machine_record' => $data
+            ]
+        ];
+        $header = ["Authorization: Bearer {$token}","Content-Type:application/json","Site:HCLT"];
+
+        $curl = curl_init();
+        curl_setopt_array($curl, array(
+            CURLOPT_URL => $url,
+            CURLOPT_RETURNTRANSFER => true,
+            CURLOPT_ENCODING => '',
+            CURLOPT_MAXREDIRS => 10,
+            CURLOPT_TIMEOUT => 0,
+            CURLOPT_FOLLOWLOCATION => true,
+            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
+            CURLOPT_CUSTOMREQUEST => 'POST',
+            CURLOPT_POSTFIELDS => json_encode($post),
+            CURLOPT_SSL_VERIFYPEER => false,
+            CURLOPT_HTTPHEADER => $header,
+        ));
+        $response = curl_exec($curl);
+        if ($response === false) {
+            // 获取错误号
+            $errorNumber = curl_errno($curl);
+            // 获取错误信息
+            $errorMessage = curl_error($curl);
+            $message = "cURL Error #{$errorNumber}: {$errorMessage}";
+            Log::channel('apiLog')->info('hc写入数据', ["param" => $message]);
+        }
+        curl_close($curl);
+
+        $res = json_decode($response,true);
+        if(! isset($res['status'])){//报错了
+            Log::channel('apiLog')->info('hc写入数据返回错误', ["param" => $response]);
+        }
+
+        return [true, ''];
+    }
+
+    protected function echoMessage(OutputInterface $output)
+    {
+        $output->writeln($this->data);
+    }
+
+    function getNowDay(){
+        // 获取当前时间
+        $currentDateTime = new \DateTime();
+
+        // 设置时区为 PRC
+        $currentDateTime->setTimezone(new \DateTimeZone('UTC'));
+
+        // 格式化时间为 "2023-09-21T16:00:00.000Z" 的格式
+        $formattedDateTime = $currentDateTime->format('Y-m-d\TH:i:s.000\Z');
+
+        return $formattedDateTime;
+    }
+}

+ 163 - 0
app/Jobs/ManDeviceJobJLWM.php

@@ -0,0 +1,163 @@
+<?php
+
+namespace App\Jobs;
+
+use App\Service\ClearDataService;
+use Illuminate\Bus\Queueable;
+use Illuminate\Contracts\Queue\ShouldQueue;
+use Illuminate\Foundation\Bus\Dispatchable;
+use Illuminate\Queue\InteractsWithQueue;
+use Illuminate\Queue\SerializesModels;
+use Illuminate\Support\Facades\Log;
+use Symfony\Component\Console\Output\OutputInterface;
+
+class ManDeviceJobJLWM implements ShouldQueue
+{
+    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
+
+    protected $data;
+    protected $url;
+
+    /**
+     * Create a new job instance.
+     *
+     * @return void
+     */
+    public function __construct($data)
+    {
+        $this->data = $data;
+        $this->url = config('ip.zslf');
+    }
+
+    /**
+     * Execute the job.
+     *
+     * @return void
+     */
+    public function handle()
+    {
+        try {
+            if (empty($this->data['data'])) return;
+
+            $deviceId = $this->data['data']['deviceId'];
+            $dataPoints = $this->data['data']['dataPoints'] ?? [];
+
+            if ($this->data['type'] == "dataPoint") {
+                $redisKey = 'buffer:jialiwumei_data';
+                $batchSize = 500;
+
+                // 1. 整理数据并推入 Redis 列表
+                $records = [];
+                foreach ($dataPoints as $value) {
+                    if (empty($value['value'])) continue;
+
+                    $records[] = json_encode([
+                        'machine_code' => $deviceId . $value['dataPointId'],
+                        'param_value'   => floatval($value['value']),
+                        'time'    => $this->getNowDay()
+                    ]);
+                }
+
+                if (!empty($records)) {
+                    // 批量推入 Redis
+                    \Illuminate\Support\Facades\Redis::rpush($redisKey, ...$records);
+                }
+
+                // 2. 检查 Redis 里的总条数
+                $currentCount = \Illuminate\Support\Facades\Redis::llen($redisKey);
+
+                // 3. 达到 500 条,执行批量发送
+
+                if ($currentCount >= $batchSize) {
+                    $this->processBatchSend($redisKey, $batchSize);
+                }
+            }
+        } catch (\Exception $exception) {
+            Log::channel('apiLog')->info('jlwm开始位置', ["param" => $exception->getMessage()]);
+            $this->delete();
+        }
+    }
+
+    /**
+     * 批量处理发送逻辑
+     */
+    protected function processBatchSend($redisKey, $batchSize)
+    {
+        // 原子化弹出 500 条数据
+        $rawRecords = \Illuminate\Support\Facades\Redis::pipeline(function ($pipe) use ($redisKey, $batchSize) {
+            for ($i = 0; $i < $batchSize; $i++) {
+                $pipe->lpop($redisKey);
+            }
+        });
+
+        $batchData = array_map(fn($item) => json_decode($item, true), array_filter($rawRecords));
+
+        if (empty($batchData)) return;
+
+        list($status,$msg) = $this->sendToDeviceBatch($batchData);
+        if(! $status) echo $msg;
+    }
+
+    public function sendToDeviceBatch($data){
+        list($status,$token) = ClearDataService::getTokenJLWM();
+        if(! $status) return [false, $token];
+
+        $url = $this->url . "api/module-data/hc_device_machine_record/hc_device_machine_record/diy/create_data";
+        $post = [
+            'data' => [
+                'device_machine_record' => $data
+            ]
+        ];
+        $header = ["Authorization: Bearer {$token}","Content-Type:application/json","Site:JLWM"];
+
+        $curl = curl_init();
+        curl_setopt_array($curl, array(
+            CURLOPT_URL => $url,
+            CURLOPT_RETURNTRANSFER => true,
+            CURLOPT_ENCODING => '',
+            CURLOPT_MAXREDIRS => 10,
+            CURLOPT_TIMEOUT => 0,
+            CURLOPT_FOLLOWLOCATION => true,
+            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
+            CURLOPT_CUSTOMREQUEST => 'POST',
+            CURLOPT_POSTFIELDS => json_encode($post),
+            CURLOPT_SSL_VERIFYPEER => false,
+            CURLOPT_HTTPHEADER => $header,
+        ));
+        $response = curl_exec($curl);
+        if ($response === false) {
+            // 获取错误号
+            $errorNumber = curl_errno($curl);
+            // 获取错误信息
+            $errorMessage = curl_error($curl);
+            $message = "cURL Error #{$errorNumber}: {$errorMessage}";
+            Log::channel('apiLog')->info('jlwm写入数据', ["param" => $message]);
+        }
+        curl_close($curl);
+
+        $res = json_decode($response,true);
+        if(! isset($res['status'])){//报错了
+            Log::channel('apiLog')->info('jlwm写入数据返回错误', ["param" => $response]);
+        }
+
+        return [true, ''];
+    }
+
+    protected function echoMessage(OutputInterface $output)
+    {
+        $output->writeln($this->data);
+    }
+
+    function getNowDay(){
+        // 获取当前时间
+        $currentDateTime = new \DateTime();
+
+        // 设置时区为 PRC
+        $currentDateTime->setTimezone(new \DateTimeZone('UTC'));
+
+        // 格式化时间为 "2023-09-21T16:00:00.000Z" 的格式
+        $formattedDateTime = $currentDateTime->format('Y-m-d\TH:i:s.000\Z');
+
+        return $formattedDateTime;
+    }
+}

+ 99 - 4
app/Service/ClearDataService.php

@@ -2,8 +2,7 @@
 
 namespace App\Service;
 
-
-use App\Model\DeviceData;
+use Illuminate\Support\Facades\Log;
 use Illuminate\Support\Facades\Redis;
 
 class ClearDataService extends Service
@@ -36,13 +35,13 @@ class ClearDataService extends Service
                 // 获取错误信息
                 $errorMessage = curl_error($curl);
                 $message = "cURL Error #{$errorNumber}: {$errorMessage}";
-                file_put_contents('lf_device_error.txt',date('Y-m-d H:i:s'). PHP_EOL . $message .PHP_EOL,8);
+                Log::channel('apiLog')->info('lf获取token curl', ["param" => $message]);
             }
 
             curl_close($curl);
             $result = json_decode($response,true);
             if(empty($result['token'])) {
-                file_put_contents('lf_device_error.txt',date('Y-m-d H:i:s'). PHP_EOL . $response .PHP_EOL,8);
+                Log::channel('apiLog')->info('lf获取token curl', ["param" => $response]);
                 return [false,''];
             }else{
                 $token = $result['token'];
@@ -55,4 +54,100 @@ class ClearDataService extends Service
 
         return [true,$token];
     }
+
+    public static function getTokenHc(){
+        $token_key = 'hc_device_token';
+        $token = Redis::get($token_key);
+        if(! $token){
+            $url = config('ip.zslf');
+            $post = array("name" => "hcltdemo","password"=>"12345678","rememberMe"=>true);
+            $header = ['Content-Type:application/json'];
+            $curl = curl_init();
+            curl_setopt_array($curl, array(
+                CURLOPT_URL => $url . 'jbl/api/mes/login',
+                CURLOPT_RETURNTRANSFER => true,
+                CURLOPT_ENCODING => '',
+                CURLOPT_MAXREDIRS => 10,
+                CURLOPT_TIMEOUT => 0,
+                CURLOPT_FOLLOWLOCATION => true,
+                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
+                CURLOPT_CUSTOMREQUEST => 'POST',
+                CURLOPT_SSL_VERIFYPEER => false,
+                CURLOPT_POSTFIELDS => json_encode($post),
+                CURLOPT_HTTPHEADER =>  $header,
+            ));
+            $response = curl_exec($curl);
+            if ($response === false) {
+                // 获取错误号
+                $errorNumber = curl_errno($curl);
+                // 获取错误信息
+                $errorMessage = curl_error($curl);
+                $message = "cURL Error #{$errorNumber}: {$errorMessage}";
+                Log::channel('apiLog')->info('hc获取token curl', ["param" => $message]);
+            }
+
+            curl_close($curl);
+            $result = json_decode($response,true);
+            if(empty($result['token'])) {
+                Log::channel('apiLog')->info('hc获取token', ["param" => $response]);
+                return [false, ''];
+            }else{
+                $token = $result['token'];
+                $expire_time = 1728000; //20天
+                Redis::set($token_key,$token);
+                Redis::expire($token_key, $expire_time);
+                return [true,$token];
+            }
+        }
+
+        return [true,$token];
+    }
+
+    public static function getTokenJLWM(){
+        $token_key = 'jlwm_device_token';
+        $token = Redis::get($token_key);
+        if(! $token){
+            $url = config('ip.zslf');
+            $post = array("name" => "jlwmdemo","password"=>"12345678","rememberMe"=>true);
+            $header = ['Content-Type:application/json'];
+            $curl = curl_init();
+            curl_setopt_array($curl, array(
+                CURLOPT_URL => $url . 'jbl/api/mes/login',
+                CURLOPT_RETURNTRANSFER => true,
+                CURLOPT_ENCODING => '',
+                CURLOPT_MAXREDIRS => 10,
+                CURLOPT_TIMEOUT => 0,
+                CURLOPT_FOLLOWLOCATION => true,
+                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
+                CURLOPT_CUSTOMREQUEST => 'POST',
+                CURLOPT_SSL_VERIFYPEER => false,
+                CURLOPT_POSTFIELDS => json_encode($post),
+                CURLOPT_HTTPHEADER =>  $header,
+            ));
+            $response = curl_exec($curl);
+            if ($response === false) {
+                // 获取错误号
+                $errorNumber = curl_errno($curl);
+                // 获取错误信息
+                $errorMessage = curl_error($curl);
+                $message = "cURL Error #{$errorNumber}: {$errorMessage}";
+                Log::channel('apiLog')->info('jlwm获取token curl', ["param" => $message]);
+            }
+
+            curl_close($curl);
+            $result = json_decode($response,true);
+            if(empty($result['token'])) {
+                Log::channel('apiLog')->info('jlwm获取token', ["param" => $response]);
+                return [false, ''];
+            }else{
+                $token = $result['token'];
+                $expire_time = 1728000; //20天
+                Redis::set($token_key,$token);
+                Redis::expire($token_key, $expire_time);
+                return [true,$token];
+            }
+        }
+
+        return [true,$token];
+    }
 }

+ 4 - 2
routes/api.php

@@ -35,8 +35,10 @@ Route::any('getFileData','Api\ImportController@getFileData');
 
 //朗峰
 Route::any('man_device_lf', 'Api\JobController@processDataJobAddDeviceManLf');
-
-Route::any('hc_device_lf', 'Api\JobController@processDataJobAddDeviceManHc');
+//恒昌
+Route::any('man_device_hc', 'Api\JobController@processDataJobAddDeviceManHc');
+//家丽物美
+Route::any('man_device_jlwm', 'Api\JobController@processDataJobAddDeviceManJLWM');
 
 //设备大屏 设备报表
 Route::any('deviceStatisticsReportChart', 'Api\ReportFormsController@deviceStatisticsReportChart');