123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385 |
- <?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', 'R!478gH*%23nPn');
- define('DATABASE', 2);
- function app_redis()
- {
- static $redis = null;
- static $conn = false;
- if (!$conn) {
- connect:
- $redis = new Redis();
- try {
-
- $conn = $redis->connect(HOST, PORT);
- $conn = $redis->auth(PASSWORD);
- $conn = $redis->select(DATABASE);
-
- return ($conn === true) ? $redis : false;
- } catch (Exception $e) {
- return false;
- }
- } else {
-
-
- if (php_sapi_name() === 'cli') {
- try {
-
-
-
-
- echo 'Redis 连接状态' . $redis->ping() . PHP_EOL;
- @$redis->ping();
- if (!$redis->ping()) {
- goto connect;
- }
- } catch (Exception $e) {
-
- 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 = "rl4rssi_parea_mqtt.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 = '';
- 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)
- {
-
-
-
-
-
-
- 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':
-
- $opts[CURLOPT_URL] = $url;
- $opts[CURLOPT_POST] = 1;
- $opts[CURLOPT_POSTFIELDS] = json_encode($params);
- break;
- default:
- rlog("[ERR] method " . $method);
- return false;
- }
- global $ch;
- 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;
- }
-
- $data = decodeUnicode($data);
- rlog("[HTTP] recv " . $data);
-
- 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 devRegularInfo($topic, $msg)
- {
-
- $data = json_decode($msg, true);
- if (empty($data)) {
- rlog("ERR", "json_decode");
- return;
- }
- rlog("[I]", $msg);
- $url = 'http://47.114.185.186:8115/api/trackReport';
-
- http($url, $data, [], 'POST');
- $loc = explode(',', $data['GPS']);
- $column = [
- 'csq' => $data['CSQ'] ?: '',
- 'rep_int' => $data['REP_INT'] ?: '',
- 'latitude' => isset($loc[0]) ? $loc[0] : '',
- 'longitude' => isset($loc[1]) ? $loc[1] : '',
- 'imei' => $data['IMEI'] ?: '',
- 'imsi' => $data['IMSI'] ?: '',
- 'iccid' => $data['ICCID'] ?: '',
- 'version' => $data['SYS_VER'] ?: '',
- 'time' => $data['Time'] ?: '',
- 'status' => $data['Status'] ?: '',
- 'status_msg' => $data['StatusMsg'] ?: '',
- 'initiative' => $data['Initiative'] ?: ''
- ];
- $url = 'http://47.114.185.186:8115/rlapi/busHeartbeatData';
-
- http($url, $column, [], 'POST');
- }
- function getUpDevSysMsg($topic, $msg)
- {
-
-
-
-
-
-
-
-
-
-
- $arr = json_decode($msg, true);
- if (empty($arr)) {
- rlog("ERR", "json_decode");
- return;
- }
- $column = [
- 'imei' => $arr['IMEI'],
- 'mqtt_host' => $arr['Mqtt_Host'],
- 'mqtt_port' => $arr['Mqtt_Port'],
- 'mqtt_user' => $arr['Mqtt_User'],
- 'mqtt_password' => $arr['Mqtt_Password'],
- 'tts_text' => $arr['TTS_TEXT'],
- 'gps_en' => $arr['GPS_EN'],
- 'time' => $arr['Time']
- ];
- $url = 'http://47.114.185.186:8115/rlapi/busSysMsgData';
-
- http($url, $column, [], 'POST');
- }
- function rcInfoMsg($topic, $msg)
- {
-
-
-
-
-
-
-
-
-
-
-
- $arr = json_decode($msg, true);
- if (empty($arr)) {
- rlog("ERR", "json_decode");
- return;
- }
- $column = [
- 'imei' => $arr['IMEI'],
- 'rc_number' => $arr['RC_Number'],
- 'rc_type' => $arr['RC_Type'],
- 'rc_pres' => $arr['RC_Pres'],
- 'rc_total' => $arr['RC_Total'],
- 'gps_x' => $arr['GPS_X'],
- 'gps_y' => $arr['GPS_Y'],
- 'msgid' => $arr['Msgid'],
- 'time' => $arr['Time']
- ];
- $url = 'http://47.114.185.186:8115/rlapi/busRcInfoData';
-
- http($url, $column, [], 'POST');
- }
- function loop()
- {
-
-
-
-
-
- $server = '127.0.0.1';
- $port = 1883;
- $clientId = 'mqttx_testparea'.rand(1234, 99999);
- $username = 'rl0606';
- $password = "rlian2023";
- $clean_session = true;
- $connectionSettings = new ConnectionSettings();
- $connectionSettings = $connectionSettings
- ->setUsername($username)
- ->setPassword($password)
- ->setKeepAliveInterval(60)
-
-
-
-
- ;
-
-
- $mqtt = new MqttClient($server, $port, $clientId);
- $mqtt->connect($connectionSettings, $clean_session);
- rlog('INFO', "connect OK");
-
-
- $mqtt->subscribe('PArea4RSSI/devOntime', function ($topic, $message) {
- rlog("INFO", 'recv', $topic, $message);
- var_dump($message);
- }, 0);
-
-
-
-
-
- $mqtt->subscribe('PArea4RSSI/rfidinfos', function ($topic, $message) {
- rlog("INFO", 'recv', $topic, $message);
- if(!empty($message)){
- mqttToRedis($message);
- }
-
- }, 0);
- $mqtt->loop(true);
- }
- function mqttToRedis($text){
-
- try{
- app_redis()->lpush("mqtt_data_parea4rssi",$text);
- }catch(\Exception $e){
- rlog("INFO", 'recv',"redis 异常".$e->getMessage());
- }
-
- }
- while (1) {
- try {
- rlog('INFO', 'connect start');
- loop();
- } catch (\Exception $ex) {
- rlog("ERR", $ex->getTraceAsString());
- rlog("ERR", $ex->getMessage());
- }
- sleep(3);
- }
|