ReadCommand.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Jobs\SendDataJob;
  4. use Illuminate\Console\Command;
  5. use Illuminate\Support\Facades\Cache;
  6. use Illuminate\Support\Facades\Redis;
  7. class ReadCommand extends Command
  8. {
  9. /**
  10. * The name and signature of the console command.
  11. *
  12. * @var string
  13. */
  14. protected $signature = 'command:readTXT';
  15. /**
  16. * The console command description.
  17. *
  18. * @var string
  19. */
  20. protected $description = '读取文件';
  21. /**
  22. * Create a new command instance.
  23. *
  24. * @return void
  25. */
  26. public function __construct()
  27. {
  28. parent::__construct();
  29. }
  30. /**
  31. * Execute the console command.
  32. *
  33. * @return mixed
  34. */
  35. public function handle()
  36. {
  37. $this->tcpServer();
  38. $this->info('Your command executed!');
  39. }
  40. //读取数据
  41. public function readTxtForData()
  42. {
  43. $directory = env('PROCESS_DIR',null);
  44. if(! $directory) {
  45. echo '未找到日志文件位置,请确认工具运行位置,再进行配置!';die;
  46. }
  47. $newLogFile = storage_path().'/app/public/record_device.txt';
  48. // $positionFile = storage_path().'/app/public/position_device.txt';
  49. date_default_timezone_set("PRC");
  50. $key = date("Y-m-d",time());
  51. $position = Cache::get($key);
  52. // 读取上次记录的位置
  53. $lastPosition = 0;
  54. if ($position) $lastPosition = $position;
  55. // if (file_exists($positionFile)) {
  56. // $lastPosition = intval(file_get_contents($positionFile));
  57. // }
  58. // 持续监视日志文件的变化
  59. while (true) {
  60. $key = date("Y-m-d",time());
  61. //日志源 文件位置
  62. $logFile = $directory . "/TesttoolLog" . $key . '.log';
  63. // 检查文件是否有更新
  64. clearstatcache(true, $logFile);
  65. $currentFileSize = filesize($logFile);
  66. echo "当前指针位置:$currentFileSize 上一次指针位置:$lastPosition \n";
  67. if ($currentFileSize > $lastPosition) {
  68. // 打开原始日志文件和新的日志文件
  69. $fileHandle = fopen($logFile, 'r');
  70. $newFileHandle = fopen($newLogFile, 'a'); // 使用追加模式打开新的日志文件
  71. // 移动文件指针到上次记录的位置
  72. fseek($fileHandle, $lastPosition);
  73. // 逐行读取并处理新增内容
  74. $read_data = [];
  75. while (($line = fgets($fileHandle)) !== false) {
  76. // 提取Tag数字
  77. $pattern = '/Tag:(\d+)/';
  78. preg_match($pattern, $line, $matches);
  79. if (isset($matches[1])) {
  80. $tagNumber = $matches[1];
  81. echo "接收到的数据:" . $tagNumber . "\n";
  82. $read_data[] = $tagNumber;
  83. // 将Tag数字写入新的日志文件
  84. fwrite($newFileHandle, $tagNumber . PHP_EOL);
  85. }
  86. }
  87. if(! empty($read_data)) {
  88. $this->sendData($read_data);
  89. echo '发送成功---!' . "\n";
  90. }
  91. // 获取新的位置并更新位置文件
  92. $lastPosition = ftell($fileHandle);
  93. Cache::put($key,$lastPosition,86400);
  94. // file_put_contents($positionFile, $lastPosition);
  95. // 关闭文件句柄
  96. fclose($fileHandle);
  97. fclose($newFileHandle);
  98. } else {
  99. echo '暂无新数据...' . "\n";
  100. // 在下一次检查之前休眠一段时间
  101. sleep(2);
  102. }
  103. }
  104. }
  105. public function sendData($data){
  106. $url = env('CLOUD_ADDRESS',null);
  107. if(empty($url)) return;
  108. $curl = curl_init();
  109. curl_setopt_array($curl, array(
  110. CURLOPT_URL => $url,
  111. CURLOPT_RETURNTRANSFER => true,
  112. CURLOPT_ENCODING => '',
  113. CURLOPT_MAXREDIRS => 10,
  114. CURLOPT_TIMEOUT => 0,
  115. CURLOPT_FOLLOWLOCATION => true,
  116. CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  117. CURLOPT_CUSTOMREQUEST => 'POST',
  118. CURLOPT_POSTFIELDS => $data,
  119. ));
  120. $response = curl_exec($curl);
  121. curl_close($curl);
  122. }
  123. public function tcpServer(){
  124. //本地ipv4地址
  125. $ipv4 = $this->getMyIpV4();
  126. $host = env('HOST_TCP',$ipv4); // 主机地址
  127. $port = env('HOST_PORT',9501); // 端口号
  128. // 创建一个TCP socket
  129. $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  130. // 绑定到指定的主机和端口
  131. socket_bind($socket, $host, $port);
  132. // 监听连接
  133. socket_listen($socket);
  134. // 初始内存使用量
  135. $initialMemoryUsage = memory_get_usage();
  136. echo date("Y-m-d H:i:s") . "服务器已启动\n";
  137. file_put_contents('C:\Users\Administrator\Desktop\record.txt',date("Y-m-d H:i:s") . "服务器已启动".PHP_EOL,8);
  138. while (true) {
  139. // 接受连接请求并创建新的套接字
  140. $clientSocket = socket_accept($socket);
  141. if ($clientSocket === false) {
  142. // 错误处理
  143. $error = socket_strerror(socket_last_error($socket));
  144. echo "接受连接请求失败:{$error}\n";
  145. continue; // 继续下一次循环
  146. }
  147. // 读取客户端发送的数据
  148. $data = socket_read($clientSocket, 1024);
  149. // file_put_contents('C:\Users\Administrator\Desktop\record2.txt',$data .PHP_EOL,8);
  150. $this->byteParsing3($data);
  151. // 发送响应给客户端
  152. // $response = "服务器已接收到您的消息:" . $data;
  153. // socket_write($clientSocket, $response, strlen($response));
  154. $currentMemoryUsage = memory_get_usage();
  155. $memoryDiff = $currentMemoryUsage - $initialMemoryUsage;
  156. echo "内存使用量变化:" . $memoryDiff . " 字节\n";
  157. $initialMemoryUsage = $currentMemoryUsage;
  158. // 关闭当前连接的套接字
  159. socket_close($clientSocket);
  160. gc_collect_cycles();
  161. sleep(5);
  162. }
  163. // 关闭服务器套接字
  164. socket_close($socket);
  165. }
  166. public function byteParsing2($data){
  167. $frame = $data;
  168. // 提取字段值
  169. $frameHeader = bin2hex(substr($frame, 0, 2));
  170. $frameLength = unpack('v', substr($frame, 2, 2))[1];
  171. $frameSequence = unpack('v', substr($frame, 4, 2))[1];
  172. $port = ord(substr($frame, 6, 1));
  173. $communicationType = unpack('v', substr($frame, 7, 2))[1];
  174. $payload = substr($frame, 9, $frameLength - 8);
  175. $checksum = ord(substr($frame, -3, 1));
  176. $frameTail = bin2hex(substr($frame, -2));
  177. $payloadBytes = substr($frame, 9, 4); // 假设帧载荷在通信帧中的偏移量为9,并且长度为4个字节
  178. // 将4个字节转换为无符号整数(根据您的数据编码方式确定是否需要使用符号整数)
  179. $payloadValue = unpack('N', $payloadBytes)[1];
  180. echo "zhen" . $payloadValue . "\n";
  181. $payloadHex = sprintf('%08X', $payloadValue);
  182. echo "帧载荷值: $payloadHex\n";
  183. // 打印字段值
  184. echo "帧头: $frameHeader\n";
  185. echo "帧长度: $frameLength\n";
  186. echo "帧序号: $frameSequence\n";
  187. echo "端口: $port\n";
  188. echo "通信类型: $communicationType\n";
  189. echo "帧载荷: $payload\n";
  190. echo "校验和: $checksum\n";
  191. echo "帧尾: $frameTail\n";
  192. }
  193. public function byteParsing($data){
  194. // 接收到的TCP数据(以字节形式表示)
  195. $tcpData = $data;
  196. // 解析源端口和目标端口
  197. $sourcePort = unpack('n', substr($tcpData, 0, 2))[1];
  198. $destinationPort = unpack('n', substr($tcpData, 2, 2))[1];
  199. // 解析其他TCP头部字段,解析序列号
  200. $sequenceNumber = unpack('N', substr($tcpData, 4, 4))[1];
  201. // 获取TCP头部长度(通过读取数据偏移计算得出)
  202. $dataOffset = ord(substr($tcpData, 12, 1)) >> 4;
  203. $headerLength = $dataOffset * 4;
  204. // 提取数据部分
  205. $data = substr($tcpData, $headerLength);
  206. // 处理数据部分中的控制字符
  207. $data = $this->removeControlCharacters($data);
  208. // 打印解析结果
  209. echo "源端口: $sourcePort\n";
  210. echo "目标端口: $destinationPort\n";
  211. echo "序列号: $sequenceNumber\n";
  212. if(! empty($data)){
  213. echo "数据: $data\n";
  214. }
  215. }
  216. // 去除控制字符的函数
  217. function removeControlCharacters($string) {
  218. $controlChars = array(
  219. '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', // 去除 ASCII 控制字符
  220. // '/\xEF\xBF\xBD/u' // 去除 UTF-8 中的替代字符
  221. );
  222. return preg_replace($controlChars, '', $string);
  223. }
  224. public function readTxt(){
  225. $directory = env('PROCESS_DIR',null);
  226. $directory = 'C:\Users\Administrator\Desktop\\'; // 替换为你的文件所在目录路径
  227. $currentDate = date('Y-m-d'); // 当前日期
  228. $file = $directory . "TesttoolLog" . $currentDate . '.log'; // 拼接文件路径和文件名
  229. $lastModified = filemtime($file); // 获取文件最后修改时间
  230. while (true) {
  231. clearstatcache(); // 清除文件状态缓存
  232. $currentDate = date('Y-m-d'); // 获取当前日期
  233. $currentFile = $directory . "TesttoolLog" . $currentDate . '.log'; // 当前日期对应的文件路径和文件名
  234. if ($file !== $currentFile) {
  235. // 文件已切换,更新文件路径和最后修改时间
  236. $file = $currentFile;
  237. $lastModified = filemtime($file);
  238. }
  239. $currentModified = filemtime($file); // 获取当前文件最后修改时间
  240. if ($currentModified > $lastModified) {
  241. // 文件已被修改,读取新增内容
  242. $handle = fopen($file, 'r');
  243. fseek($handle, -1, SEEK_END); // 定位到文件末尾前两个字节
  244. $data = fread($handle, 2); // 读取新增内容
  245. fclose($handle);
  246. // 处理新增内容
  247. // ...
  248. // 示例:打印新增内容
  249. echo $data;
  250. $lastModified = $currentModified; // 更新最后修改时间
  251. }
  252. sleep(1); // 睡眠一段时间后再次检查文件是否被修改
  253. }
  254. }
  255. public function byteParsing3($data){
  256. $hexData = bin2hex($data);
  257. $hexData = str_replace(' ', '', $hexData);
  258. $toReplace = array("a6a8001300000a00010101001708120012000103b5a5a7", "a6a8000c00000a0003120001037da5a7");
  259. $result = str_replace($toReplace, "", $hexData);
  260. // echo "原数据:" . $hexData . PHP_EOL;
  261. // $memoryUsage = memory_get_usage();
  262. // echo "当前脚本占用的内存量:".$memoryUsage." 字节" . "\n";
  263. //
  264. // $memoryUsage = memory_get_peak_usage();
  265. // echo "PHP程序总内存使用量:" . $memoryUsage . " 字节" . "\n";
  266. if($result){
  267. $last38Chars = substr($result, -38, 32);
  268. echo "替换后:" . $last38Chars . PHP_EOL;
  269. file_put_contents('C:\Users\Administrator\Desktop\record.txt',$last38Chars.PHP_EOL,8);
  270. if(! empty($last38Chars)) {
  271. $this->sendData([$last38Chars]);
  272. echo '发送成功---!' . "\n";
  273. }
  274. }
  275. }
  276. public function getMyIpV4(){
  277. $ip = exec("ipconfig | findstr /i \"IPv4\"");
  278. return $ip;
  279. }
  280. }