nana_sen 2 роки тому
батько
коміт
b005c7301f

+ 64 - 23
catch/api/controller/Api.php

@@ -173,10 +173,10 @@ class Api extends CatchController
         $dispose = new dispose($ues_redis);
         while(1){
             $jsonData= $ues_redis->rpop("mqtt_data_parea4rssi");
-            debug_log("InAndOUT",'数据redis'.$jsonData);
+            debug_log("pare_InAndOUT",'数据redis'.$jsonData);
             
             if(empty($jsonData)){
-                debug_log("InAndOUT",'没有数据');
+                debug_log("pare_InAndOUT",'没有数据');
                 sleep(1);
                 continue;
                 
@@ -217,7 +217,7 @@ class Api extends CatchController
             //         //推送离开
             //     }
             // }
-            sleep(2);
+            // sleep(2);
 
         }
 
@@ -229,6 +229,8 @@ class Api extends CatchController
 
     //消息处理
     public function handleMessage($text, $mac, $time, $ues_redis){
+        $EXP_TIME = 10;
+        $EFF_SIG_NUM = 6;
         while(strlen($text)>=24){
     
             $da=substr($text,0,24);
@@ -258,15 +260,15 @@ class Api extends CatchController
                 
                 $field = $mac."_".$rfid;
                 $info = $ues_redis->hget("parea_rfidinfos",$field);
-                debug_log("InAndOUT","数据:".json_encode($DA,true));
+                debug_log("pare_InAndOUT","数据:".json_encode($DA,true));
 
                 if(!$info){
                     $info = [
                         "mac" => $mac,
                         "id" => $rfid,
                         "firs_time" => $time,
-                        "last_time" => $time,
-                        "status" => 1,//1出状态,2进状态
+                        "time" => $time,
+                        "status" => 2,//2出状态,1进状态
                         "rssi" => [
                             [
                                 "front" => $rssi1,
@@ -278,10 +280,11 @@ class Api extends CatchController
                         ]
                     ];
                     $ues_redis->hset("parea_rfidinfos",$field, json_encode($info,true));
+                    debug_log("parea_rfidinfos_redis_set_record","redis更新记录".$url_res);
                 }else{
                     $info = json_decode($info,true);
 
-                    $info["last_time"] = $time;
+                    $info["time"] = $time;
                     $newRssi = [
                         "front" => $rssi1,
                         "behind" => $rssi2,
@@ -327,10 +330,11 @@ class Api extends CatchController
 
                     if ($cacCount == $EFF_SIG_NUM) {
                         # code...
-                        $this->compAndPush($info["avg"], $mac, $rfid, $ues_redis);
+                       $info = $this->compAndPush($info ,$ues_redis);
                     }
 
                     $ues_redis->hset("parea_rfidinfos",$field, json_encode($info,true));
+                    debug_log("parea_rfidinfos_redis_set_record","redis更新记录".$url_res);
                 }
                 $text=substr($text,24);
             }else{
@@ -340,40 +344,77 @@ class Api extends CatchController
         return $text ?$text : "";
     }
     //判断进出和推送
-    public function compAndPush($data, $mac, $rfid, $ues_redis){
+    public function compAndPush($info, $ues_redis){
         //标签多,数据多时候,判断完成后放入redis,异步推送,当前暂时直接推
-        if (empty($data)) {
+        if (empty($info)) {
             # code...
             return false;
         }
-        $config  = $ues_redis->hget("anbang_four_wire", $mac);
-
+        $config  = $ues_redis->hget("anbang_four_wire", $info["mac"]);
+        
         //{"front_in":44,"front_out":44,"behind_in":50,"behind_out":50,"left_in":55,"left_out":55,"right_out":44,"right_out":44}
         if (!$config) {
             # code...
             $config = [
-                "front_in" => 70,
-                "behind_in" => 70,
-                "left_in" => 70,
-                "right_in" => 70,
-                "front_out" => 80,
-                "behind_out" => 80,
-                "left_out" => 80,
-                "right_out" => 80,
+                "front_in" => 65,
+                "behind_in" => 65,
+                "left_in" => 65,
+                "right_in" => 65,
+                "front_out" => 78,
+                "behind_out" => 78,
+                "left_out" => 78,
+                "right_out" => 78,
             ];     
         }
 
+        $avg = $info['avg'];
+        $status = $info['status'];
+
         $flagIn = $data["front"] < $config["front_in"] || $data["behind"] < $config["behind_in"] || $data["left"] < $config["left_in"] || $data["right"] < $config["right_in"];
         $flagOut = $data["front"] > $config["front_out"] && $data["behind"] < $config["behind_out"] && $data["left"] < $config["left_out"] && $data["right"] < $config["right_out"];
 
-        if($flagIn){
+        $url="http://47.114.185.186:8115/api/areaReport";
+        if($flagIn && $status == 2){
             //推送进
-        }else{
+            $info['status'] = 1;
+            $url_data = [
+                "mac" => $info["mac"],
+                "data" => [
+                    [
+                        "label" => $info["id"],
+                        "time" => $info["time"],
+                        "dirt" => 1
+                    ]
+                ]
+            ];
+            debug_log("pushPareaRes","推送内容:".json_encode($url_data));
+            $url_res= curl_http_post(json_encode($url_data),$url,false);
+            debug_log("pushPareaRes","远程返回结果".$url_res);
+        }
+        if($flagOut && $status == 1){
             //推送出
+            $info['status'] = 2;
+            $url_data = [
+                "mac" => $info["mac"],
+                "data" => [
+                    [
+                        "label" => $info["id"],
+                        "time" => $info["time"],
+                        "dirt" => 2
+                    ]
+                ]
+            ];
+            debug_log("pushPareaRes","推送内容:".json_encode($url_data));
+            $url_res= curl_http_post(json_encode($url_data),$url,false);
+            debug_log("pushPareaRes","远程返回结果".$url_res);
         }
-        return true;
+        return $info;
     }
 
+    // $url="http://47.114.185.186:8115/api/accessReport";
+    // $url_res= curl_http_post(json_encode($url_data),$url,false);
+    // debug_log("InAndOUT","远程返回结果".$url_res);
+
    
     public function test(){
         

+ 253 - 0
task_script/PAREA_STATUS_UPDATE.php

@@ -0,0 +1,253 @@
+<?php
+require('../vendor/autoload.php');
+use \PhpMqtt\Client\MqttClient;
+use \PhpMqtt\Client\ConnectionSettings;
+use think\facade\Cache;
+date_default_timezone_set("PRC");
+define('HOST', '127.0.0.1');
+define('PORT', '6379');
+define('PASSWORD', '123456');
+define('DATABASE', 3);
+define('OFFLINETIMEINT', 120);
+
+
+function app_redis()
+{
+    static $redis = null;
+    static $conn = false;
+    if (!$conn) {
+        connect: //定义标签
+        $redis = new Redis();
+        try {
+            //建立的Redis短连接,在请求结束后不会自动关闭,相当于持久连接.
+            $conn = $redis->connect(HOST, PORT);
+            $conn = $redis->auth(PASSWORD);
+            $conn = $redis->select(DATABASE);
+            // 连接成功,返回$redis对象,连接失败,返回false.
+            return ($conn === true) ? $redis : false;
+        } catch (Exception $e) {
+            return false;
+        }
+    } else {
+        // 这里假设PHP-FPM在处理一个请求的时间内,Redis连接都是可用的.
+        // 所以只在PHP-CLI下检查Redis连接的状态,进行断线重连.
+        if (php_sapi_name() === 'cli') {
+            try {
+                // ping用于检查当前连接的状态,成功时返回+PONG,失败时抛出一个RedisException对象.
+                // ping失败时警告:
+                // Warning: Redis::ping(): connect() failed: Connection refused
+                // var_dump('AAAAAAAAA', $redis);
+                echo 'Redis 连接状态' . $redis->ping() . PHP_EOL;
+                @$redis->ping();
+                if (!$redis->ping()) {
+                    goto connect; //跳转到标签出继续执行连接操作
+                }
+            } catch (Exception  $e) {
+                // 信息如 Connection lost 或 Redis server went away
+                echo $e->getMessage();
+                echo 'Redis 连接失败 重新连接:' . PHP_EOL;
+                // 断线重连
+                goto connect;
+            }
+        }
+        return $redis;
+    }
+}
+
+function rlog(...$args)
+{
+    if (empty($args[0])) {
+        return;
+    }
+    static $LOG_CONSOLE = false; //是否输出到控制台
+    static $LOG_NAME = "parea_status_update.log"; //值为空时 不写入文件
+    static $LOG_SIZE = 64 * 1024 * 1024; //文件最大尺寸
+
+    static $LOG_CACHE = false; //是否缓存日志内容 用于批量写入文件
+    static $CACHE_DURATION = 10; //缓存最大时间 秒
+    static $CACHE_SIZE = 1024; //缓存大小
+    static $cacheStartTime = 0;
+    static $cacheBuf = '';
+
+    static $LOG_TIMES = 10; //调用这个函数最大次数 超过次数后判断下文件大小
+    static $logCount = 0;
+
+
+    $buf = '';
+    if (count($args) == 1 && $args[0] == "\n") { //只有换行时 不写入时间戳了
+        $buf = "\n";
+    } else {
+        $pid = ''; //进程id
+        if (function_exists('posix_getpid')) {
+            $pid = ' ' . posix_getpid() . ' ';
+        }
+        $fileLine = ''; //文件名:行号
+        {
+            $debug = debug_backtrace();
+            $fileLine = ($pid == '' ? ' ' : '') . basename($debug[0]['file']) . ':' . $debug[0]['line'] . ' ';
+        }
+        $buf = date("y-m-d H:i:s") . "{$pid}{$fileLine}" . implode(' ', $args) . "\n";
+    }
+
+    $logCount++;
+    if (!empty($LOG_NAME)) {
+        if ($LOG_CACHE) {
+            $cacheBuf .= $buf;
+            //超过缓存尺寸 或者 超过缓存时长 写缓存到文件
+            if (strlen($cacheBuf) > $CACHE_SIZE || time() - $cacheStartTime > $CACHE_DURATION) {
+                $cacheStartTime = time();
+                goto write;
+            } else {
+                goto skipWrite;
+            }
+        } else {
+            $cacheBuf = $buf;
+        }
+        write: {
+            //超过尺寸后 删除旧文件 把新文件重命名为旧文件  多进程同时操作 不加锁问题不大
+            if ($logCount > $LOG_TIMES && filesize($LOG_NAME) > $LOG_SIZE) {
+                $oldLogName = $LOG_NAME . '.old';
+                if (file_exists($oldLogName)) {
+                    if (!unlink($oldLogName)) {
+                        echo "unlink err\n";
+                    }
+                }
+                if (!rename($LOG_NAME, $oldLogName)) {
+                    echo "rename err\n";
+                }
+                $logCount = 0;
+            }
+            if (!file_put_contents($LOG_NAME, $cacheBuf, FILE_APPEND)) {
+                echo "file_put_contents err\n";
+            }
+            $cacheBuf = '';
+        }
+        skipWrite: {
+        }
+    }
+    if ($LOG_CONSOLE) {
+        echo $buf;
+    }
+}
+
+function http($url, $params, $header = [], $method = 'GET', $timeout = 10)
+{
+    // POST $params 字符串形式query=abcd&abc=12345
+    //GET $params 数组['query' => 'abcd', 'abc' => 12345]
+    //  $header[] = "Content-Type: application/x-www-form-urlencoded";
+    //  $header[] = "Content-Type: application/soap+xml; charset=utf-8";
+    //  $header[] = "Content-Type: application/json; charset=utf-8";
+    //  $header[] = "Expect: ";
+    rlog("[HTTP] url:$url,method:$method" . ",header:" . json_encode($header));
+    if (strtoupper($method) == 'POST') {
+        rlog("[POST] send params " . (!is_array($params) ? $params : json_encode($params, JSON_UNESCAPED_UNICODE)));
+    } else {
+        rlog("[GET] send " . json_encode($params));
+    }
+    $header[] = "Expect: ";
+    $opts = array(
+        CURLOPT_TIMEOUT => $timeout,
+        CURLOPT_RETURNTRANSFER => 1,
+        CURLOPT_SSL_VERIFYPEER => false,
+        CURLOPT_SSL_VERIFYHOST => false,
+        CURLOPT_HTTPHEADER => $header
+    );
+
+    /* 根据请求类型设置特定参数 */
+    switch (strtoupper($method)) {
+        case 'GET':
+            $opts[CURLOPT_URL] = $url . (empty($params) ? '' : ('?' . http_build_query($params)));
+            break;
+        case 'POST':
+            //$params = http_build_query($params);
+            $opts[CURLOPT_URL] = $url;
+            $opts[CURLOPT_POST] = 1;
+            $opts[CURLOPT_POSTFIELDS] = json_encode($params);
+            break;
+        default:
+            rlog("[ERR] method " . $method);
+            return false;
+    }
+
+    global $ch; //curl长连接
+    if (empty($ch)) {
+        $ch = curl_init();
+    }
+    if (empty($ch)) {
+        rlog("[ERR] curl_init");
+        return false;
+    }
+
+    $csa = curl_setopt_array($ch, $opts);
+    if (empty($csa)) {
+        rlog("[ERR] curl_setopt_array");
+        return false;
+    }
+
+    $data = curl_exec($ch);
+    if ($data === false) {
+        rlog("[ERR] curl_exec errno:" . curl_errno($ch) . " " . curl_error($ch));
+        return false;
+    }
+    //unicode转中文
+    $data = decodeUnicode($data);
+    rlog("[HTTP] recv " . $data);
+    //curl_close($ch);
+    return $data;
+}
+function decodeUnicode($str)
+{
+    return preg_replace_callback('/\\\\u([0-9a-f]{4})/i', function ($matches) {
+        return iconv("UCS-2BE", "UTF-8", pack("H*", $matches[1]));
+    }, $str);
+}
+
+
+function mqttToRedis($text){
+    
+    try{
+        app_redis()->lpush("mqtt_data_parea4rssi",$text);
+    }catch(\Exception $e){
+        rlog("INFO", 'recv',"redis 异常".$e->getMessage());
+    }
+    
+} 
+
+
+
+while (true) {
+    try {
+        rlog('INFO', 'task start');
+
+        $infos = app_redis()->hgetall("parea_rfidinfos");
+
+        foreach ($infos as $k => $v) {
+            # code...
+            $data = json_decode($v, true);
+            if ( (time() - $data["time"] ) > OFFLINETIMEINT ) {
+                # code...
+                if ($data["status"] == 1) {
+                    # code...
+                    $url="http://47.114.185.186:8115/api/areaReport";
+                    $url_data = [
+                        "mac" => $data["mac"],
+                        "data" => [
+                            [
+                                "label" => $data["id"],
+                                "time" => $data["time"],
+                                "dirt" => 2
+                            ]
+                        ]
+                    ];
+                    http($url, $url_data, [], 'POST');
+                }
+                app_redis()->hdel('parea_rfidinfos',$k);;
+            }
+        }
+        
+    } catch (\Exception $ex) {
+        rlog("INFO", 'pushhttp',"推送 异常".$ex->getMessage());
+    }
+    sleep(60); //1分钟遍历一次
+}
+

+ 1 - 1
task_script/RL4RSSI_PAREA_MQTT.php

@@ -59,7 +59,7 @@ function rlog(...$args)
         return;
     }
     static $LOG_CONSOLE = false; //是否输出到控制台
-    static $LOG_NAME = "school_mqtt.log"; //值为空时 不写入文件
+    static $LOG_NAME = "rl4rssi_parea_mqtt.log"; //值为空时 不写入文件
     static $LOG_SIZE = 64 * 1024 * 1024; //文件最大尺寸
 
     static $LOG_CACHE = false; //是否缓存日志内容 用于批量写入文件