ResponseServer.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Mead
  5. * Date: 2019/9/4
  6. * Time: 11:58 AM
  7. */
  8. namespace App\Servers;
  9. use App\Handlers\Crc16Handler;
  10. class ResponseServer
  11. {
  12. private $start = 'AA AA';
  13. use Crc16Handler;
  14. public function send($data = [], $cmd = '81', $num_code = '01')
  15. {
  16. $num = 12;
  17. $num += count($data);
  18. $data_length = $this->byNumGetDataLength($num);
  19. $header = [
  20. $data_length,
  21. $this->getSoftwareVersion(),
  22. $cmd,
  23. $num_code,
  24. '00',
  25. '00',
  26. '00'
  27. ];
  28. $data = $this->arr2str($header, $data);
  29. $data .= self::crc16(explode(' ', $data));
  30. return $this->format($this->start . $data);
  31. }
  32. /**
  33. * 获取数据包的长度
  34. * @param $num
  35. * @return array
  36. * User: Mead
  37. */
  38. public function byNumGetDataLength($num)
  39. {
  40. $length = dechex($num);
  41. return str_pad($length, 4, '0', STR_PAD_LEFT);
  42. }
  43. /**
  44. * 软件版本号
  45. * @return string
  46. * User: Mead
  47. */
  48. public function getSoftwareVersion()
  49. {
  50. return '04';
  51. }
  52. /**
  53. * 获取流水号
  54. * @return int
  55. * User: Mead
  56. */
  57. public function getPipelineNumber()
  58. {
  59. return '00';
  60. }
  61. public function arr2str()
  62. {
  63. $args = func_get_args();
  64. $arr = '';
  65. foreach ($args as $arg) {
  66. if (is_array($arg)) {
  67. $arr .= implode('', $arg);
  68. } else {
  69. $arr .= str_replace(' ', '', $arg);
  70. }
  71. }
  72. return implode(' ', str_split($arr, 2));
  73. }
  74. public function format($str)
  75. {
  76. return strtoupper(implode(' ', str_split(str_replace(' ', '', $str), 2)));
  77. }
  78. }