LIVESTOCK_MQTT_FMZL.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. <?php
  2. require('../vendor/autoload.php');
  3. use \PhpMqtt\Client\MqttClient;
  4. use \PhpMqtt\Client\ConnectionSettings;
  5. use think\facade\Cache;
  6. // date_default_timezone_set("America/Bahia");
  7. define('HOST', '127.0.0.1');
  8. define('PORT', '6379');
  9. define('PASSWORD', '123456');
  10. define('DATABASE', 2);
  11. // define('HOST', 'r-bp1eebab79320044pd.redis.rds.aliyuncs.com');
  12. // define('PORT', '6379');
  13. // define('PASSWORD', '7e2b5c91e438be3c!');
  14. // define('DATABASE', 4);
  15. use \think\facade\Db;
  16. function app_redis()
  17. {
  18. static $redis = null;
  19. static $conn = false;
  20. if (!$conn) {
  21. connect: //定义标签
  22. $redis = new Redis();
  23. try {
  24. //建立的Redis短连接,在请求结束后不会自动关闭,相当于持久连接.
  25. $conn = $redis->connect(HOST, PORT);
  26. $conn = $redis->auth(PASSWORD);
  27. $conn = $redis->select(DATABASE);
  28. // 连接成功,返回$redis对象,连接失败,返回false.
  29. return ($conn === true) ? $redis : false;
  30. } catch (Exception $e) {
  31. return false;
  32. }
  33. } else {
  34. // 这里假设PHP-FPM在处理一个请求的时间内,Redis连接都是可用的.
  35. // 所以只在PHP-CLI下检查Redis连接的状态,进行断线重连.
  36. if (php_sapi_name() === 'cli') {
  37. try {
  38. // ping用于检查当前连接的状态,成功时返回+PONG,失败时抛出一个RedisException对象.
  39. // ping失败时警告:
  40. // Warning: Redis::ping(): connect() failed: Connection refused
  41. // var_dump('AAAAAAAAA', $redis);
  42. // echo 'Redis 连接状态' . $redis->ping() . PHP_EOL;
  43. @$redis->ping();
  44. if (!$redis->ping()) {
  45. goto connect; //跳转到标签出继续执行连接操作
  46. }
  47. } catch (Exception $e) {
  48. // 信息如 Connection lost 或 Redis server went away
  49. echo $e->getMessage();
  50. echo 'Redis 连接失败 重新连接:' . PHP_EOL;
  51. // 断线重连
  52. goto connect;
  53. }
  54. }
  55. return $redis;
  56. }
  57. }
  58. function rlog(...$args)
  59. {
  60. if (empty($args[0])) {
  61. return;
  62. }
  63. static $LOG_CONSOLE = false; //是否输出到控制台
  64. static $LOG_NAME = "livestock_fmzl_mqtt.log"; //值为空时 不写入文件
  65. static $LOG_SIZE = 64 * 1024 * 1024; //文件最大尺寸
  66. static $LOG_CACHE = false; //是否缓存日志内容 用于批量写入文件
  67. static $CACHE_DURATION = 10; //缓存最大时间 秒
  68. static $CACHE_SIZE = 1024; //缓存大小
  69. static $cacheStartTime = 0;
  70. static $cacheBuf = '';
  71. static $LOG_TIMES = 10; //调用这个函数最大次数 超过次数后判断下文件大小
  72. static $logCount = 0;
  73. $buf = '';
  74. if (count($args) == 1 && $args[0] == "\n") { //只有换行时 不写入时间戳了
  75. $buf = "\n";
  76. } else {
  77. $pid = ''; //进程id
  78. if (function_exists('posix_getpid')) {
  79. $pid = ' ' . posix_getpid() . ' ';
  80. }
  81. $fileLine = ''; //文件名:行号
  82. {
  83. $debug = debug_backtrace();
  84. $fileLine = ($pid == '' ? ' ' : '') . basename($debug[0]['file']) . ':' . $debug[0]['line'] . ' ';
  85. }
  86. $buf = date("y-m-d H:i:s") . "{$pid}{$fileLine}" . implode(' ', $args) . "\n";
  87. }
  88. $logCount++;
  89. if (!empty($LOG_NAME)) {
  90. if ($LOG_CACHE) {
  91. $cacheBuf .= $buf;
  92. //超过缓存尺寸 或者 超过缓存时长 写缓存到文件
  93. if (strlen($cacheBuf) > $CACHE_SIZE || time() - $cacheStartTime > $CACHE_DURATION) {
  94. $cacheStartTime = time();
  95. goto write;
  96. } else {
  97. goto skipWrite;
  98. }
  99. } else {
  100. $cacheBuf = $buf;
  101. }
  102. write: {
  103. //超过尺寸后 删除旧文件 把新文件重命名为旧文件 多进程同时操作 不加锁问题不大
  104. if ($logCount > $LOG_TIMES && filesize($LOG_NAME) > $LOG_SIZE) {
  105. $oldLogName = $LOG_NAME . '.old';
  106. if (file_exists($oldLogName)) {
  107. if (!unlink($oldLogName)) {
  108. echo "unlink err\n";
  109. }
  110. }
  111. if (!rename($LOG_NAME, $oldLogName)) {
  112. echo "rename err\n";
  113. }
  114. $logCount = 0;
  115. }
  116. if (!file_put_contents($LOG_NAME, $cacheBuf, FILE_APPEND)) {
  117. echo "file_put_contents err\n";
  118. }
  119. $cacheBuf = '';
  120. }
  121. skipWrite: {
  122. }
  123. }
  124. if ($LOG_CONSOLE) {
  125. echo $buf;
  126. }
  127. }
  128. function sendData($topic,$data)
  129. {
  130. $server = 'stage-agro-mqtt.cacfintech.com';
  131. $port = 1883;
  132. $clientId = 'local_mqtt_livestock_data_cli_123321';
  133. $username = '';
  134. $password = "";
  135. $clean_session = false;
  136. $connectionSettings = new ConnectionSettings();
  137. $connectionSettings = $connectionSettings
  138. ->setUsername($username)
  139. ->setPassword($password)
  140. ->setKeepAliveInterval(60)
  141. // Last Will 设置
  142. // ->setLastWillTopic('emqx/test/last-will')
  143. // ->setLastWillMessage('client disconnect')
  144. // ->setLastWillQualityOfService(1)
  145. ;
  146. $mqtt = new MqttClient($server, $port, $clientId);
  147. $mqtt->connect($connectionSettings, $clean_session);
  148. rlog('['.date('Y-m-d H:i:s').']connect OK');
  149. rlog('['.date('Y-m-d H:i:s').']topic:'.$topic);
  150. $res=$mqtt->publish(
  151. $topic,
  152. $data,
  153. 1
  154. );
  155. rlog('['.date('Y-m-d H:i:s').']publish end');
  156. $mqtt->loop(true,true);
  157. $mqtt->disconnect();
  158. return $res;
  159. }
  160. $device_arr=[
  161. '866216067708342-999202300000000','869761079694821-999202300000000','869761079697154-999202300000000','869761079697790-999202300000000','869761079698186-999202300000000','869761079698913-999202300000000','869761079699325-999202300000000','869761079700354-999202300000000','869761079700396-999202300000000','869761079700438-999202300000000','869761079700453-999202300000000','869761079700511-999202300000000','869761079700537-999202300000000','869761079700545-999202300000000','869761079700552-999202300000000','869761079700594-999202300000000','869761079700628-999202300000000','869761079700669-999202300000000','869761079700701-999202300000000','869761079700727-999202300000000','869761079700776-999202300000000','869761079700792-999202300000000','869761079700859-999202300000000','869761079700875-999202300000000','869761079700891-999202300000000','869761079700958-999202300000000','869761079700966-999202300000000','869761079700982-999202300000000','869761079700990-999202300000000','869761079701055-999202300000000','869761079701113-999202300000000','869761079701139-999202300000000','869761079701147-999202300000000','869761079701162-999202300000000','869761079701188-999202300000000','869761079701220-999202300000000','869761079701238-999202300000000','869761079701253-999202300000000','869761079701261-999202300000000','869761079701303-999202300000000','869761079701329-999202300000000','869761079701352-999202300000000','869761079701394-999202300000000','869761079701451-999202300000000','869761079701477-999202300000000','869761079701485-999202300000000','869761079701519-999202300000000','869761079701535-999202300000000','869761079701584-999202300000000','869761079701592-999202300000000','869761079701626-999202300000000','869761079701675-999202300000000','869761079701683-999202300000000','869761079701725-999202300000000','869761079701741-999202300000000','869761079701758-999202300000000','869761079701774-999202300000000','869761079701873-999202300000000','869761079701907-999202300000000','869761079701931-999202300000000','869761079701949-999202300000000','869761079701964-999202300000000','869761079702053-999202300000000','869761079702095-999202300000000','869761079702129-999202300000000','869761079702152-999202300000000','869761079702194-999202300000000','869761079702202-999202300000000','869761079702269-999202300000000','869761079702277-999202300000000','869761079702285-999202300000000','869761079702293-999202300000000','869761079702343-999202300000000','869761079702376-999202300000000','869761079702418-999202300000000','869761079702434-999202300000000','869761079702467-999202300000000','869761079702491-999202300000000','869761079702590-999202300000000','869761079702624-999202300000000','869761079702640-999202300000000','869761079702657-999202300000000','869761079702715-999202300000000','869761079702764-999202300000000','869761079702871-999202300000000','869761079702954-999202300000000','869761079708803-999202300000000','869761079708894-999202300000000','869761079708944-999202300000000','869761079709199-999202300000000','869761079711823-999202300000000'
  162. ];
  163. while (1) {
  164. $jsonData= app_redis()->rpop("livestock_data_after_handle");
  165. if(!$jsonData){
  166. sleep(3);
  167. continue;
  168. }
  169. $data=json_decode($jsonData,true);
  170. if(!in_array($data['deviceId'],$device_arr)){
  171. continue;
  172. }
  173. // var_dump($data);
  174. rlog("redis data: " . json_encode($data));
  175. $topic="earings/".$data['deviceId']."/reportData";
  176. $res=sendData($topic,json_encode($data));
  177. }