123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123 |
- <?php
- namespace app\common\workman;
- class Tlv
- {
-
- private $buffer;
- private $t_len = 4;
- private $l_len = 4;
- private $buf_len = 0;
- private $buf_array = array();
-
- function __construct()
- {
- }
-
- 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) {
-
- $t = $this->getLength($i, $this->t_len);
- if ($this->toHex($t) == "0xffffffff") break;
- $i += $this->t_len;
-
- $l = $this->getLength($i, $this->l_len);
- $i += $this->l_len;
-
- $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)
- {
- $ret = unpack($format, $data);
- 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;
- }
- }
|