Tlv.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. <?php
  2. namespace app\common\workman;
  3. class Tlv
  4. {
  5. /**
  6. *
  7. * TLV包解析类
  8. *
  9. */
  10. private $buffer;
  11. private $t_len = 4; //T长度
  12. private $l_len = 4; //L长度
  13. private $buf_len = 0; //字节流长度
  14. private $buf_array = array();
  15. /**
  16. * 构造函数
  17. */
  18. function __construct()
  19. {
  20. }
  21. /**
  22. * 解析数据
  23. *
  24. * @param byte $buffer 二进制流数据
  25. * @param $IsArray
  26. * @return array
  27. */
  28. public function Read($buffer, $IsArray = false)
  29. {
  30. $this->buffer = $buffer;
  31. $this->buf_len = strlen($this->buffer);
  32. //清空数组
  33. if (isset($this->buf_array)) {
  34. unset($this->buf_array);
  35. $this->buf_array = array();
  36. }
  37. $i = 0;
  38. while ($i < $this->buf_len) {
  39. //获取TGA
  40. $t = $this->getLength($i, $this->t_len);
  41. if ($this->toHex($t) == "0xffffffff") break;
  42. $i += $this->t_len;
  43. //获取Length
  44. $l = $this->getLength($i, $this->l_len);
  45. $i += $this->l_len;
  46. //获取Value
  47. $v = substr($this->buffer, $i, $l);
  48. $i += $l;
  49. if ($IsArray) {
  50. $this->buf_array[$this->toHex($t)] = array($this->toHex($t), $l, $v);
  51. } else {
  52. array_push($this->buf_array, array($this->toHex($t), $l, $v));
  53. }
  54. }
  55. return $this->buf_array;
  56. }
  57. //将数组转换二进制数据
  58. public function Write($arrdata)
  59. {
  60. $msg = '';
  61. for ($i = 0; $i < count($arrdata); $i++) {
  62. $msg .= $this->Pack("N*", $arrdata[$i][0]);
  63. $msg .= $this->Pack("N*", $arrdata[$i][1]);
  64. $msg .= $arrdata[$i][2];
  65. }
  66. return $msg;
  67. }
  68. //获取值
  69. protected function getValue($key)
  70. {
  71. return $this->buf_array[$key][2];
  72. }
  73. //转换成十六进制
  74. protected function toHex($value)
  75. {
  76. return "0x" . dechex($value);
  77. }
  78. //压包
  79. protected function Pack($format, $data)
  80. {
  81. return pack($format, $data);
  82. }
  83. //解包
  84. protected function Unpack($format, $data)
  85. {
  86. // var_dump($format);
  87. // var_dump($data);
  88. $ret = unpack($format, $data);
  89. // var_dump($ret);
  90. return $ret[1];
  91. }
  92. protected function getLength($start, $len)
  93. {
  94. return $this->Unpack('N*', substr($this->buffer, $start, $len));
  95. }
  96. //清楚所有数据
  97. protected function Clear()
  98. {
  99. if (isset($this->buffer)) {
  100. unset($this->buffer);
  101. }
  102. $this->buf_len = 0;
  103. }
  104. }