Exemple #1
0
 def to_binary(self):
     req = pack('!L', self.num)
     for i in xrange(self.num):
         req += add_str_to_binary(self.field[i])
         req += pack('!B', self.flag[i])
         req += add_str_to_binary(self.value[i])
     return req
Exemple #2
0
 def to_binary(self):
     req = pack('!L', self.num)
     for i in xrange(self.num):
         req += add_str_to_binary(self.field[i])
         req += pack('!B', self.flag[i])
         req += add_str_to_binary(self.value[i])
     return req
Exemple #3
0
def add_str_to_binary(s):
    if s:
        es = s.encode("GBK")
        return pack('!L',
                    len(es) + 1) + pack(str(len(es)) + 's',
                                        es) + '\x00'  #for c string
    else:
        return pack('!L', 0)
 def __shake_hands(self, read_code, write_code):
     shake_hands = TDHS_HEAD
     wbuf = shake_hands
     wbuf += pack('!L', TDHS_VERSION_BINARY)
     wbuf += pack('!L', self.time_out)
     wbuf += add_str_to_binary(read_code)
     wbuf += add_str_to_binary(write_code)
     self.send(pack(FMT, MAGIC_CODE, REQUEST_TYPE_SHAKE_HANDS, self.getid(), 0, len(wbuf)) + wbuf)
Exemple #5
0
 def to_binary(self):
     if not self.is_vaild():
         raise request_exception("insert is not valid!")
     req = self.table_info.to_binary()
     req += pack('!L', self.num)
     for i in xrange(self.num):
         req += pack('!B', self.flag[i])
         req += add_str_to_binary(self.value[i])
     return req
Exemple #6
0
 def to_binary(self):
     if not self.is_vaild():
         raise request_exception("insert is not valid!")
     req = self.table_info.to_binary()
     req += pack('!L', self.num)
     for i in xrange(self.num):
         req += pack('!B', self.flag[i])
         req += add_str_to_binary(self.value[i])
     return req
Exemple #7
0
 def to_binary(self):
     if not self.is_vaild():
         raise request_exception("get is not valid!")
     req = self.table_info.to_binary()
     req += add_array_to_binary(self.key)
     req += pack('!B', self.find_flag)
     req += pack('!L', self.start)
     req += pack('!L', self.limit)
     req += self.filter.to_binary()
     return req
Exemple #8
0
 def to_binary(self):
     if not self.is_vaild():
         raise request_exception("get is not valid!")
     req = self.table_info.to_binary()
     req += add_array_to_binary(self.key)
     req += pack('!B', self.find_flag)
     req += pack('!L', self.start)
     req += pack('!L', self.limit)
     req += self.filter.to_binary()
     return req
Exemple #9
0
 def __shake_hands(self, read_code, write_code):
     shake_hands = TDHS_HEAD
     wbuf = shake_hands
     wbuf += pack('!L', TDHS_VERSION_BINARY)
     wbuf += pack('!L', self.time_out)
     wbuf += add_str_to_binary(read_code)
     wbuf += add_str_to_binary(write_code)
     self.send(
         pack(FMT, MAGIC_CODE, REQUEST_TYPE_SHAKE_HANDS, self.getid(), 0,
              len(wbuf)) + wbuf)
Exemple #10
0
    def encode(self, mode, msg):

        if mode == 0:
            #return stc.pack("HHHH", mode, int(msg[0]), int(msg[1]), int(msg[2]))
            #return stc.pack("<fff", mode, msg[0], msg[1], msg[2])

            self.ser.write(stc.pack("H", mode))
            self.ser.write((str(msg[0]) + " ").encode("utf-8"))
            self.ser.write((str(msg[1]) + " ").encode("utf-8"))
            self.ser.write(str(msg[2]).encode("utf-8"))

        elif mode == 1:
            return stc.pack("H", mode)
Exemple #11
0
def add_array_to_binary(array):
    v = pack('!L', len(array))
    for a in array:
        if isinstance(a, list) or isinstance(a, tuple):
            v += add_array_to_binary(a)
        else:
            v += add_str_to_binary(a)
    return v
Exemple #12
0
def add_array_to_binary(array):
    v = pack('!L', len(array))
    for a in array:
        if isinstance(a, list) or isinstance(a, tuple):
            v += add_array_to_binary(a)
        else:
            v += add_str_to_binary(a)
    return v
Exemple #13
0
 def main(n):
     import _struct as struct
     import array
     a = array.array('B', struct.pack('i', 42))
     i = 0
     while i < n:
         i += 1
         struct.unpack('i', a)  # ID: unpack
     return i
Exemple #14
0
def test_struct_bool():
    import _struct
    for prefix in tuple("<>!=")+('',):
        format = str(prefix + '?')
        packed = _struct.pack(format, {})
        unpacked = _struct.unpack(format, packed)

        AreEqual(len(unpacked), 1)
        AssertFalse(unpacked[0])
Exemple #15
0
def test_struct_bool():
    import _struct
    for prefix in tuple("<>!=")+('',):
        format = str(prefix + '?')
        packed = _struct.pack(format, {})
        unpacked = _struct.unpack(format, packed)

        AreEqual(len(unpacked), 1)
        AssertFalse(unpacked[0])
Exemple #16
0
 def main(n):
     import _struct as struct
     import array
     a = array.array('c', struct.pack('i', 42))
     i = 0
     while i < n:
         i += 1
         struct.unpack('<i', a)  # ID: unpack
     return i
Exemple #17
0
 def to_binary(self):
     if not self.is_vaild():
         raise request_exception("table_info is not valid!")
     req = add_str_to_binary(self.db)
     req += add_str_to_binary(self.table)
     if self.index:
         req += add_str_to_binary(self.index)
     else:
         req += pack('!L', 0)
     req += add_array_to_binary(self.fields)
     return req
Exemple #18
0
 def to_binary(self):
     if not self.is_vaild():
         raise request_exception("table_info is not valid!")
     req = add_str_to_binary(self.db)
     req += add_str_to_binary(self.table)
     if self.index:
         req += add_str_to_binary(self.index)
     else:
         req += pack('!L', 0)
     req += add_array_to_binary(self.fields)
     return req
Exemple #19
0
 def save_traffic(self, traffic, path):
     self.file = open(path + '/simulation_traffic_data.bin', 'wb')
     for veh in traffic:
         self.file.write(
             struct.pack(
                 '6f', *[
                     traffic[veh][64], traffic[veh][66][0],
                     traffic[veh][66][1], traffic[veh][67],
                     traffic[veh][68], traffic[veh][77]
                 ]))
         # print(fmt),
         name_length = len(traffic[veh][79])
         fmt = 'i'
         self.file.write(struct.pack(fmt, *[name_length]))
         # print(fmt),
         fmt = str(name_length) + 's'
         self.file.write(struct.pack(fmt, *[traffic[veh][79].encode()]))
         # print(fmt),
         name_length = len(traffic[veh][87])
         fmt = 'i'
         self.file.write(struct.pack(fmt, *[name_length]))
         # print(name_length),
         for route in traffic[veh][87]:
             name_length = len(route)
             fmt = 'i'
             self.file.write(struct.pack(fmt, *[name_length]))
             # print(fmt),
             fmt = str(name_length) + 's'
             self.file.write(struct.pack(fmt, *[route.encode()]))
             # print(fmt),
     self.file.close()
Exemple #20
0
    def encode(self):
        assert self.position == 0, 'Do not call encode twice'
        repeats = self.find_repeats()
        total_size = len(self.file_bytes)
        self.encoded_bytes.extend(pack('>L', total_size))
        for repeat in repeats:
            repeat_start, repeat_len, fill_byte = repeat
            # check if copy is needed
            if repeat_start > self.position:
                self._copy(repeat_start)
            self._fill(repeat_len, fill_byte)

        if total_size > self.position:
            self._copy(total_size)
        assert self.position == total_size, 'file could not parsed completely'
Exemple #21
0
  def encode(self):
    assert self.position == 0, 'Do not call encode twice'
    repeats = self.find_repeats()
    total_size = len(self.file_bytes)
    self.encoded_bytes.extend(pack('>L', total_size))
    for repeat in repeats:
      repeat_start, repeat_len, fill_byte = repeat
      # check if copy is needed
      if repeat_start > self.position:
        self._copy(repeat_start)
      self._fill(repeat_len, fill_byte)

    if total_size > self.position:
      self._copy(total_size)
    assert self.position == total_size, 'file could not parsed completely'
Exemple #22
0
  def digest(self):
    """Terminate the message-digest computation and return digest.

    Return the digest of the strings passed to the update()
    method so far. This is a 16-byte string which may contain
    non-ASCII characters, including null bytes.
    """

    A = self.A
    B = self.B
    C = self.C
    D = self.D
    input = [] + self.input
    count = [] + self.count

    index = (self.count[0] >> 3) & 0x3f

    if index < 56:
      padLen = 56 - index
    else:
      padLen = 120 - index

    padding = [b'\200'] + [b'\000'] * 63
    self.update(padding[:padLen])

    # Append length (before padding).
    bits = _bytelist2long(self.input[:56]) + count

    self._transform(bits)

    # Store state in digest.
    digest = struct.pack("<IIII", self.A, self.B, self.C, self.D)

    self.A = A
    self.B = B
    self.C = C
    self.D = D
    self.input = input
    self.count = count

    return digest
Exemple #23
0
    def digest(self):
        """Terminate the message-digest computation and return digest.

    Return the digest of the strings passed to the update()
    method so far. This is a 16-byte string which may contain
    non-ASCII characters, including null bytes.
    """

        A = self.A
        B = self.B
        C = self.C
        D = self.D
        input = [] + self.input
        count = [] + self.count

        index = (self.count[0] >> 3) & 0x3f

        if index < 56:
            padLen = 56 - index
        else:
            padLen = 120 - index

        padding = [b'\200'] + [b'\000'] * 63
        self.update(padding[:padLen])

        # Append length (before padding).
        bits = _bytelist2long(self.input[:56]) + count

        self._transform(bits)

        # Store state in digest.
        digest = struct.pack("<IIII", self.A, self.B, self.C, self.D)

        self.A = A
        self.B = B
        self.C = C
        self.D = D
        self.input = input
        self.count = count

        return digest
    def _test_float_point_number(self, type, byteorder):
        float_value = uniform(-3.1415926535, 3.1415926535)

        can_data = [0, 0]
        configs = [{
            "key": type + "Var",
            "is_ts": True,
            "type": type,
            "start": len(can_data),
            "length": 4 if type[0] == "f" else 8,
            "byteorder": byteorder
        }]

        can_data.extend(
            _struct.pack((">" if byteorder[0] == "b" else "<") + type[0],
                         float_value))
        tb_data = self.converter.convert(configs, can_data)
        self.assertTrue(
            isclose(tb_data["telemetry"][type + "Var"],
                    float_value,
                    rel_tol=1e-05))
Exemple #25
0
 def packInt32(self, val):
     return _struct.pack('<I', val)
Exemple #26
0
 def pack(self, data):
     size = len(data)
     data = struct.pack('!I%ss' % size, size, data)
     return data
Exemple #27
0
from _socket import *

if len(sys.argv) != 2:
    print('-' * 30)
    print("tips:")
    print("python xxx.py 192.168.1.1")
    print('-' * 30)
    exit()
else:
    ip = sys.argv[1]

# 创建udp套接字
udpSocket = socket(AF_INET, SOCK_DGRAM)

# 构造下载请求数据
sendData = _struct.pack("!H8sb5sb", 1, "test.jpg", 0, "octet", 0)

# 发送下载文件请求数据到指定服务器
sendAddr = (ip, 69)
udpSocket.sendto(sendData, sendAddr)

p_num = 0

recvFile = ''

while True:
    recvData, recvAddr = udpSocket.recvfrom(1024)

    recvDataLen = len(recvData)

    cmdTuple = _struct.unpack("!HH", recvData[:4])
Exemple #28
0
def length_to_bits(size):
    count = how_many_bytes(size)
    bin_size = pack('>L', size)[-count:]
    assert len(bin_size) == count
    return (count, bin_size)
 def packInt32(self, val):
     return _struct.pack('<I', val)
def add_str_to_binary(s):
    if s:
        es = s.encode("GBK")
        return pack('!L', len(es) + 1) + pack(str(len(es)) + 's', es) + '\x00' #for c string
    else:
        return pack('!L', 0)
 def packInt16(self, val):
     if val < 0:
         val = 0x10000 + val
     return _struct.pack('<H', val)
Exemple #32
0
def length_to_bits(size):
  count = how_many_bytes(size)
  bin_size = pack('>L', size)[-count:]
  assert len(bin_size) == count
  return (count, bin_size)
Exemple #33
0
 def packInt16(self, val):
     if val < 0:
         val = 0x10000 + val
     return _struct.pack('<H', val)
    #msg2 = stc.pack("HHHH", mode, angle1, angle2, angle3)

    print(msg1)

    ser.write(encoding_tests)


if __name__ == "__main__":

    mode = 0
    angle1 = 45
    angle2 = 50
    angle3 = 55

    msg2 = stc.pack("HHHH", mode, angle1, angle2, angle3)

    ser = serial.Serial('COM3', 115200, timeout=1)
    ser.flush()
    print("connected")

    print(stc.unpack("HHHH", msg2))

    ser.write(msg2)

    print("sent")

    while True:
        if ser.in_waiting > 0:
            line = ser.readline()
            line = line.decode("utf-8").rstrip()
Exemple #35
0
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import _struct as struct

# struct test
A = 0x67452301
B = 0xefcdab89
C = 0x98badcfe
D = 0x10325476

expected = '\x01#Eg\x89\xab\xcd\xef\xfe\xdc\xba\x98vT2\x10'

assert struct.pack("<IIII", A, B, C, D) == expected