|
@@ -0,0 +1,123 @@
|
|
|
+<?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;
|
|
|
+ }
|
|
|
+
|
|
|
+}
|