123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123 |
- <?php
- namespace app\common\workman;
- class Tlv
- {
- /**
- *
- * TLV包解析类
- *
- */
- private $buffer;
- private $t_len = 4; //T长度
- private $l_len = 4; //L长度
- private $buf_len = 0; //字节流长度
- private $buf_array = array();
- /**
- * 构造函数
- */
- function __construct()
- {
- }
- /**
- * 解析数据
- *
- * @param byte $buffer 二进制流数据
- * @param $IsArray
- * @return array
- */
- public function Read($buffer, $IsArray = false)
- {
- $this->buffer = $buffer;
- $this->buf_len = strlen($this->buffer);
- //清空数组
- if (isset($this->buf_array)) {
- unset($this->buf_array);
- $this->buf_array = array();
- }
- $i = 0;
- while ($i < $this->buf_len) {
- //获取TGA
- $t = $this->getLength($i, $this->t_len);
- if ($this->toHex($t) == "0xffffffff") break;
- $i += $this->t_len;
- //获取Length
- $l = $this->getLength($i, $this->l_len);
- $i += $this->l_len;
- //获取Value
- $v = substr($this->buffer, $i, $l);
- $i += $l;
- if ($IsArray) {
- $this->buf_array[$this->toHex($t)] = array($this->toHex($t), $l, $v);
- } else {
- array_push($this->buf_array, array($this->toHex($t), $l, $v));
- }
- }
- return $this->buf_array;
- }
- //将数组转换二进制数据
- public function Write($arrdata)
- {
- $msg = '';
- for ($i = 0; $i < count($arrdata); $i++) {
- $msg .= $this->Pack("N*", $arrdata[$i][0]);
- $msg .= $this->Pack("N*", $arrdata[$i][1]);
- $msg .= $arrdata[$i][2];
- }
- return $msg;
- }
- //获取值
- protected function getValue($key)
- {
- return $this->buf_array[$key][2];
- }
- //转换成十六进制
- protected function toHex($value)
- {
- return "0x" . dechex($value);
- }
- //压包
- protected function Pack($format, $data)
- {
- return pack($format, $data);
- }
- //解包
- protected function Unpack($format, $data)
- {
- // var_dump($format);
- // var_dump($data);
- $ret = unpack($format, $data);
- // var_dump($ret);
- return $ret[1];
- }
- protected function getLength($start, $len)
- {
- return $this->Unpack('N*', substr($this->buffer, $start, $len));
- }
- //清楚所有数据
- protected function Clear()
- {
- if (isset($this->buffer)) {
- unset($this->buffer);
- }
- $this->buf_len = 0;
- }
- }
|