Python struct.unpack_from() Examples

The following are code examples for showing how to use struct.unpack_from(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: phrydy   Author: Josef-Friedrich   File: mediafile.py    MIT License 6 votes vote down vote up
def _unpack_asf_image(data):
    """Unpack image data from a WM/Picture tag. Return a tuple
    containing the MIME type, the raw image data, a type indicator, and
    the image's description.

    This function is treated as "untrusted" and could throw all manner
    of exceptions (out-of-bounds, etc.). We should clean this up
    sometime so that the failure modes are well-defined.
    """
    type, size = struct.unpack_from('<bi', data)
    pos = 5
    mime = b''
    while data[pos:pos + 2] != b'\x00\x00':
        mime += data[pos:pos + 2]
        pos += 2
    pos += 2
    description = b''
    while data[pos:pos + 2] != b'\x00\x00':
        description += data[pos:pos + 2]
        pos += 2
    pos += 2
    image_data = data[pos:pos + size]
    return (mime.decode("utf-16-le"), image_data, type,
            description.decode("utf-16-le")) 
Example 2
Project: LayoutExporterU   Author: aboood40091   File: bflan.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, file, pos):
                        initPos = pos
                        _curveTypes = ["Constant", "Step", "Hermite"]

                        (self.id,
                         self.target,
                         self.curveType,
                         self.keyNum,
                         self.keysOffset) = struct.unpack_from('>3BxH2xI', file, pos); pos += 12

                        assert self.keysOffset == 12

                        self.keys = []
                        if self.curveType:
                            size = 8 if self.curveType == 1 else 12
                            key = self.StepKey if self.curveType == 1 else self.HermiteKey
                            pos = initPos + self.keysOffset

                            for _ in range(self.keyNum):
                                self.keys.append(key(file, pos)); pos += size 
Example 3
Project: LayoutExporterU   Author: aboood40091   File: bflan.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, file, pos):
                initPos = pos

                _types = ["Pane", "Material"]

                (nameBytes,
                 self.num,
                 self.type) = struct.unpack_from('>28s2B', file, pos); pos += 32

                self.name = readString(nameBytes)
                #print(self.name)

                animInfoOffsets = struct.unpack_from('>%dI' % self.num, file, pos)
                self.animInfos = []

                for pAnimInfo in animInfoOffsets:
                    self.animInfos.append(self.AnimationInfo(file, initPos + pAnimInfo)) 
Example 4
Project: LayoutExporterU   Author: aboood40091   File: bflyt.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, file, pos):
            super().__init__(file, pos)

            self.fontNum = struct.unpack_from('>H', self.data)[0]
            self.fonts = []

            if self.fontNum:
                _printFnt("Fonts:")

            for i in range(self.fontNum):
                pFont = struct.unpack_from('>I', self.data, 4 * (i+1))[0] + 4
                font = readString(self.data, pFont)

                assert font[-6:] == ".bffnt"
                font = font[:-6]

                _printFnt(font)
                self.fonts.append(font)

            if self.fontNum:
                _printFnt() 
Example 5
Project: LayoutExporterU   Author: aboood40091   File: bflyt.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, file, pos):
                    (self.texIdx,
                     self.wrapSflt,
                     self.wrapTflt) = struct.unpack_from('>H2B', file, pos)

                    _texWrap = ["Clamp", "Repeat", "Mirror"]
                    _texFilter = ["Near", "Linear"]

                    # wrapSflt -> 0000FFWW
                    self.wrapS = self.wrapSflt & 3
                    self.minFilter = (self.wrapSflt >> 2) & 3

                    # wrapTflt -> 0000FFWW
                    self.wrapT = self.wrapTflt & 3
                    self.magFilter = (self.wrapTflt >> 2) & 3

                    _printMat("Texture Index: %d" % self.texIdx)
                    _printMat("Wrap S: %s" % _texWrap[self.wrapS])
                    _printMat("Wrap T: %s" % _texWrap[self.wrapT])
                    _printMat("Min Filter: %s" % _texFilter[self.minFilter])
                    _printMat("Mag Filter: %s" % _texFilter[self.magFilter]) 
Example 6
Project: LayoutExporterU   Author: aboood40091   File: bflyt.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, file, pos):
            initPos = pos
            super().__init__(file, pos); pos += 84

            self.inflation = struct.unpack_from('>4h', file, pos); pos += 8
            self.frameSize = struct.unpack_from('>4H', file, pos); pos += 8

            (self.frameNum,
             self.windowFlags,
             self.contentOffset,
             self.frameOffsetTableOffset) = struct.unpack_from('>2B2x2I', file, pos); pos += 12

            self.readWindowFlags()

            pos = initPos + self.contentOffset
            self.content = self.WindowContent(file, pos)

            self.frames = []
            for i in range(self.frameNum):
                pos = initPos + self.frameOffsetTableOffset + 4*i
                pos = initPos + struct.unpack_from('>I', file, pos)[0]
                self.frames.append(self.WindowFrame(file, pos)) 
Example 7
Project: LayoutExporterU   Author: aboood40091   File: bflyt.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, file, initPos, pos):
                (nameBytes,
                 self.usageFlag,
                 self.basicUsageFlag,
                 self.propertyOffset,
                 self.extUserDataOffset,
                 self.paneBasicInfoOffset) = struct.unpack_from('>24s2B2x3I', file, pos)

                self.name = readString(nameBytes)

                self.property = None
                if self.propertyOffset:
                    self.property = readPane(file, initPos + self.propertyOffset)

                self.extUserData = None
                if self.extUserDataOffset:
                    self.extUserData = FLYT.ExtUserDataList.ExtUserData(file, initPos + self.extUserDataOffset)

                self.basicInfo = None
                if self.paneBasicInfoOffset:
                    self.basicInfo = self.PartsPaneBasicInfo(file, initPos + self.paneBasicInfoOffset) 
Example 8
Project: LayoutExporterU   Author: aboood40091   File: bflyt.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, file, pos):
                (self.nameStrOffset,
                 self.dataOffset,
                 self.num,
                 self.type) = struct.unpack_from('>2IHB', file, pos)

                self.name = readString(file, pos + self.nameStrOffset)
                self.data = []

                if self.dataOffset:
                    if self.type == 0:
                        tempPos = pos + self.dataOffset
                        for _ in range(self.num):
                            _string = readString(file, tempPos); tempPos += len(string) + 1
                            self.data.append(_string)

                    elif self.type == 1:
                        self.data = struct.unpack_from('>%di' % self.num, file, pos + self.dataOffset)

                    elif self.type == 2:
                        self.data = struct.unpack_from('>%df' % self.num, file, pos + self.dataOffset) 
Example 9
Project: LayoutExporterU   Author: aboood40091   File: bflyt.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, file, pos, major):
            super().__init__(file, pos); pos += 8

            if major < 5:
                fmt = '>24sH2x'
                size = 28

            else:
                fmt = '>33sxH'
                size = 36

            (nameBytes,
             self.paneNum) = struct.unpack_from(fmt, file, pos); pos += size

            self.name = readString(nameBytes)

            self.panes = []
            for i in range(self.paneNum):
                pane = readString(struct.unpack_from('>24s', file, pos + 24*i)[0])
                self.panes.append(pane) 
Example 10
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 6 votes vote down vote up
def decode_ID2(packet):			#NAVDATA_RAW_MEASURES_TAG
	dataset = struct.unpack_from("HHHHHhhhhhIHHHHHHHHHHHHhh", packet, 0)
	if dataset[1] != 52:		print "*** ERROR : navdata-raw_measures-Options-Package (ID=2) has the wrong size !!!"
	raw_measures = [[0,0,0],[0,0,0],[0,0],0,0,0,0,0,0,0,0,0,0,0,0,0]
	for i in range(0,3,1):	raw_measures[0][i] = dataset[2+i]	# raw_accs[xyz]			filtered accelerometer-datas [LSB]	(uint16)
	for i in range(0,3,1):	raw_measures[1][i] = dataset[5+i]	# raw_gyros[xyz]		filtered gyrometer-datas [LSB]		(int16)
	for i in range(0,2,1):	raw_measures[2][i] = dataset[8+i]	# raw_gyros_110[xy]		gyrometers  x/y 110 deg/s [LSB]		(int16)
	raw_measures[ 3] = dataset[10]		# vbat_raw				battery voltage raw (mV)			(uint)
	raw_measures[ 4] = dataset[11]		# us_debut_echo			[LSB]								(uint16)
	raw_measures[ 5] = dataset[12]		# us_fin_echo			[LSB]								(uint16)
	raw_measures[ 6] = dataset[13]		# us_association_echo	[LSB]								(uint16)
	raw_measures[ 7] = dataset[14]		# us_distance_echo		[LSB]								(uint16)
	raw_measures[ 8] = dataset[15]		# us_courbe_temps		[LSB]								(uint16)
	raw_measures[ 9] = dataset[16]		# us_courbe_valeur		[LSB]								(uint16)
	raw_measures[10] = dataset[17]		# us_courbe_ref			[LSB]								(uint16)
	raw_measures[11] = dataset[18]		# flag_echo_ini			[LSB]								(uint16)
	raw_measures[12] = dataset[19]		# nb_echo				[LSB]								(uint16)
	raw_measures[13] = dataset[21]		# sum_echo				juRef_st lower 16Bit, upper 16Bit=tags?	(uint32)
	raw_measures[14] = dataset[23]		# alt_temp_raw			in Milimeter	(just lower 16Bit)	(int32)
	raw_measures[15] = dataset[24]		# gradient				[LSB]								(int16)
	return(raw_measures)

##### ID = 3 ### "phys_measures" ############################################## 
Example 11
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 6 votes vote down vote up
def decode_ID10(packet):		#NAVDATA_ALTITUDE_TAG
	dataset = struct.unpack_from("HHifiiffiiiIffI", packet, 0)
	if dataset[1] != 56:		print "*** ERROR : navdata-navdata_altitude-Options-Package (ID=10) has the wrong size !!!"
	altitude = [0,0.0,0,0,0.0,0.0,[0,0,0],0,[0,0],0]
	altitude[0] = dataset[2]			# altitude_vision	[mm]					(int32)
	altitude[1] = dataset[3]			# altitude_vz		[mm/s]					(float)
	altitude[2] = dataset[4]			# altitude_ref		[mm]					(int32)
	altitude[3] = dataset[5]			# altitude_raw		[mm]					(int32)
	altitude[4] = dataset[6]			# obs_accZ			Observer AccZ [m/s2]	(float)
	altitude[5] = dataset[7]			# obs_alt			Observer altitude US [m](float)
	for i in range (0,3,1):
		altitude[6][i] = dataset[8+i]	# obs_x				3-Vector				(int32)
	altitude[7] = dataset[11]			# obs_state			Observer state [-]		(uint32)
	for i in range (0,2,1):
		altitude[8][i] = dataset[12+i]	# est_vb			2-Vector				(float)
	altitude[9] = dataset[14]			# est_state			Observer flight state 	(uint32)
	return(altitude)

##### ID = 11 ### "vision_raw" ################################################# 
Example 12
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 6 votes vote down vote up
def decode_ID16(packet):  		#NAVDATA_VISION_DETECT_TAG
	dataset = struct.unpack_from("HHIIIIIIIIIIIIIIIIIIIIIIIIIffffIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII", packet, offsetND)
	if dataset[1] != 328:	print "*** ERROR : navdata-vision_detect-Package (ID=16) has the wrong size !!!"
	vision_detect = [0,[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0.0,0.0,0.0,0.0],[[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0],[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0],[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0],[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0]],[[0.0,0.0,0.0],[0.0,0.0,0.0],[0.0,0.0,0.0],[0.0,0.0,0.0]],[0,0,0,0]]
	#Max marker detection in one picture: 4
	vision_detect[0] = dataset[2]									 		# nb_detected						(uint32)
	for i in range (0,4,1):		vision_detect[1][i] = dataset[3+i]			# type[4]							(uint32)
	for i in range (0,4,1):		vision_detect[2][i] = dataset[7+i]			# xc[4]								(uint32)
	for i in range (0,4,1):		vision_detect[3][i] = dataset[11+i]			# yc[4]								(uint32)
	for i in range (0,4,1):		vision_detect[4][i] = dataset[15+i]			# width[4]							(uint32)
	for i in range (0,4,1):		vision_detect[5][i] = dataset[19+i]			# height[4]							(uint32)
	for i in range (0,4,1):		vision_detect[6][i] = dataset[23+i]			# dist[4]							(uint32)
	for i in range (0,4,1):		vision_detect[7][i] = dataset[27+i]			# orientation_angle[4]				(float)
	for i in range (0,4,1):
		for j in range (0,9,1):	vision_detect[8][i][j] = dataset[31+i+j]	# rotation[4]						(float 3x3 matrix (11,12,13,21,...)
	for i in range (0,4,1):
		for j in range (0,3,1):	vision_detect[9][i][j] = dataset[67+i+j]	# rotation[4]						(float 3 vector)
	for i in range (0,4,1):		vision_detect[10][i] = dataset[79+i]		# camera_source[4]					(uint32)
	return(vision_detect)

##### ID = 17 ### "watchdog" ################################################### 
Example 13
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 6 votes vote down vote up
def decode_ID19(packet):		#NAVDATA_VIDEO_STREAM_TAG
	dataset = struct.unpack_from("HHBIIIIfIIIiiiiiII", packet, offsetND)
	if dataset[1] != 65:	print "*** ERROR : navdata-video_stream-Package (ID=19) has the wrong size !!!"
	video_stream = [0,0,0,0,0,0.0,0,0,0,[0,0,0,0,0],0,0]
	video_stream[0] = dataset[2]	# quant   		quantizer reference used to encode [1:31]   				(uint8)
	video_stream[1] = dataset[3]	# frame_size	frame size in bytes   										(uint32)
	video_stream[2] = dataset[4]	# frame_number	frame index   												(uint32)
	video_stream[3] = dataset[5]	# atcmd_ref_seq	atmcd ref sequence number   								(uint32)
	video_stream[4] = dataset[6]	# atcmd_mean_ref_gap	mean time between two consecutive atcmd_ref (ms)	(uint32)
	video_stream[5] = dataset[7]	# atcmd_var_ref_gap															(float)
	video_stream[6] = dataset[8]	# atcmd_ref_quality		estimator of atcmd link quality   					(uint32)
	#Drone 2.0:
	video_stream[7] = dataset[9]	# out_bitrate			measured out throughput from the video tcp socket	(uint32)
	video_stream[8] = dataset[10]	# desired_bitrate		last frame size generated by the video encoder		(uint32)
	for i in range (0,5,1):		video_stream[9][i] = dataset[11+i]	# data		misc temporary data				(int32)
	video_stream[10] = dataset[16]	# tcp_queue_level		queue usage											(uint32)
	video_stream[11] = dataset[17]	# fifo_queue_level		queue usage											(uint32)
	return(video_stream)

##### ID = 20 ### "games" ###################################################### 
Example 14
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 6 votes vote down vote up
def decode_ID22(packet):		#NAVDATA_MAGNETO_TAG
	dataset = struct.unpack_from("HHhhhffffffffffffBifff", packet, offsetND)
	if dataset[1] != 83:	print "*** ERROR : navdata-magneto-Package (ID=22) has the wrong size !!!"
	magneto = [[0,0,0],[0.0,0.0,0.0],[0.0,0.0,0.0],[0.0,0.0,0.0],0.0,0.0,0.0,0,0,0.0,0.0,0.0]
	for i in range (0,3,1):		magneto[0][i]=dataset[2+i]	# mx/my/mz											(int16)
	for i in range (0,3,1):		magneto[1][i]=dataset[5+i]	# magneto_raw		magneto in the body frame [mG]	(vector float)
	for i in range (0,3,1):		magneto[2][i]=dataset[8+i]	# magneto_rectified									(vector float)
	for i in range (0,3,1):		magneto[3][i]=dataset[11+i]	# magneto_offset									(vector float)
	magneto[ 4] = dataset[14]								# heading_unwrapped 								(float)
	magneto[ 5] = dataset[15]								# heading_gyro_unwrapped							(float)
	magneto[ 6] = dataset[16]								# heading_fusion_unwrapped 							(float)
	magneto[ 7] = dataset[17]								# magneto_calibration_ok							(char)
	magneto[ 8] = dataset[18]								# magneto_state 									(uint32)
	magneto[ 9] = dataset[19]								# magneto_radius									(float)
	magneto[10] = dataset[20]								# error_mean 										(float)
	magneto[11] = dataset[21]								# error_var											(float)
	return(magneto)

##### ID = 23 ### "wind_speed" ################################################ 
Example 15
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 6 votes vote down vote up
def decode_ID24(packet):  		#NAVDATA_KALMAN_PRESSURE_TAG
	dataset = struct.unpack_from("HHffffffffff?f?ff??", packet, offsetND)
	if dataset[1] != 72:	print "*** ERROR : navdata-wind_speed-Package (ID=24) has the wrong size !!!"
	kalman_pressure = [0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0,0.0,False,0.0,0.0,False,False]
	kalman_pressure[ 0] = dataset[2]	# offset_pressure 			   					(float)
	kalman_pressure[ 1] = dataset[3]	# est_z											(float)
	kalman_pressure[ 2] = dataset[4]	# est_zdot 										(float)
	kalman_pressure[ 3] = dataset[5]	# est_bias_PWM 									(float)
	kalman_pressure[ 4] = dataset[6]	# est_biais_pression							(float)
	kalman_pressure[ 5] = dataset[7]	# offset_US 			   						(float)
	kalman_pressure[ 6] = dataset[8]	# prediction_US									(float)
	kalman_pressure[ 7] = dataset[9]	# cov_alt 										(float)
	kalman_pressure[ 8] = dataset[10]	# cov_PWM										(float)
	kalman_pressure[ 9] = dataset[11]	# cov_vitesse									(float)
	kalman_pressure[10] = dataset[12]	# bool_effet_sol								(bool)
	kalman_pressure[11] = dataset[13]	# somme_inno									(float)
	kalman_pressure[12] = dataset[14]	# flag_rejet_US									(bool)
	kalman_pressure[13] = dataset[15]	# u_multisinus									(float)
	kalman_pressure[14] = dataset[16]	# gaz_altitude									(float)
	kalman_pressure[15] = dataset[17]	# Flag_multisinus								(bool)
	kalman_pressure[16] = dataset[18]	# Flag_multisinus_debut							(bool)
	return(kalman_pressure)

##### ID = 25 ### "hdvideo_stream" ############################################ 
Example 16
Project: cronosparser   Author: occrp   File: parser.py    MIT License 6 votes vote down vote up
def parse_columns(text, base, count):
    # Parse the columns from the table definition. Columns start with
    # a short record length indicator, followed by type and sequence
    # information (each a short), and the name (prefixed by the length).
    columns = []
    for i in range(count):
        if len(text[base:]) < 8:
            break
        col_len, = struct.unpack_from('H', text, base)
        base = base + 2
        if len(text[base:]) < col_len:
            break
        col_data = text[base - 1:base - 1 + col_len]
        type_, col_id = struct.unpack_from('>HH', col_data, 0)
        text_len, = struct.unpack_from('>I', col_data, 4)
        col_name = decode_text(col_data[8:8 + text_len])
        if col_name is None:
            continue
        columns.append({
            'id': col_id,
            'name': col_name,
            'type': type_
        })
        base = base + col_len
    return columns 
Example 17
Project: cronosparser   Author: occrp   File: parser.py    MIT License 6 votes vote down vote up
def parse_record(meta, dat_fh):
    # Each data record is stored as a linked list of data fragments. The
    # metadata record holds the first and second offset, while all further
    # chunks are prefixed with the next offset.
    offset, length, next_offset, next_length = struct.unpack('<IHIH', meta)
    dat_fh.seek(offset)
    if length == 0:
        if next_length == 0 or next_length == 0xffff:
            return
    data = dat_fh.read(length)
    while next_length != 0 and next_length != 0xffff:
        dat_fh.seek(next_offset)
        next_data = dat_fh.read(min(252, next_length))
        if len(next_data) < 4:
            break
        next_offset, = struct.unpack_from('<I', next_data)
        data += next_data[4:]
        if next_length > 252:
            next_length -= 252
        else:
            next_length = 0
    return data 
Example 18
Project: pyblish-win   Author: pyblish   File: test_struct.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_unpack_from(self, cls=str):
        data = cls('abcd01234')
        fmt = '4s'
        s = struct.Struct(fmt)

        self.assertEqual(s.unpack_from(data), ('abcd',))
        self.assertEqual(struct.unpack_from(fmt, data), ('abcd',))
        for i in xrange(6):
            self.assertEqual(s.unpack_from(data, i), (data[i:i+4],))
            self.assertEqual(struct.unpack_from(fmt, data, i), (data[i:i+4],))
        for i in xrange(6, len(data) + 1):
            self.assertRaises(struct.error, s.unpack_from, data, i)
            self.assertRaises(struct.error, struct.unpack_from, fmt, data, i) 
Example 19
Project: UR5_Controller   Author: tsinghua-rll   File: rtif.py    MIT License 5 votes vote down vote up
def __recv(self):
        self.__buf = ''

        while 1:
            self.__buf += self.__sock.recv(4096)
            # unpack_from requires a buffer of at least 3 bytes
            if len(self.__buf) >= 880:
                # Attempts to extract a packet
                data, _ = StateMessageReceiver.unpack(self.__buf)
                return data 
Example 20
Project: kvmd   Author: pikvm   File: inotify.py    GNU General Public License v3.0 5 votes vote down vote up
def _inotify_parsed_buffer(data: bytes) -> Generator[Tuple[int, int, int, bytes], None, None]:
    offset = 0
    while offset + _EVENT_HEAD_SIZE <= len(data):
        (wd, mask, cookie, length) = struct.unpack_from("iIII", data, offset)
        name = data[
            offset + _EVENT_HEAD_SIZE  # noqa: E203
            :
            offset + _EVENT_HEAD_SIZE + length
        ].rstrip(b"\0")
        offset += _EVENT_HEAD_SIZE + length
        if wd >= 0:
            yield (wd, mask, cookie, name) 
Example 21
Project: LayoutExporterU   Author: aboood40091   File: bflan.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file, pos, fmt):
                (nameBytes,
                 self.flag) = struct.unpack_from(fmt, file, pos)

                self.name = readString(nameBytes)
                self.fmt = fmt 
Example 22
Project: LayoutExporterU   Author: aboood40091   File: bflan.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file, pos, major):
            initPos = pos
            super().__init__(file, pos); pos += 8

            (self.tagOrder,
             self.groupNum,
             self.nameOffset,
             self.groupsOffset,
             self.startFrame,
             self.endFrame,
             self.flag) = struct.unpack_from('>2H2I2hB', file, pos)

            # flag & 1 -> ANIMTAGFLAG_DESCENDINGBIND

            pos = initPos + self.nameOffset
            self.name = readString(file, pos)

            pos = initPos + self.groupsOffset
            self.groups = []

            if major < 5:
                fmt = '>24sB3x'
                size = 28

            else:
                fmt = '>33sB2x'
                size = 36

            for _ in range(self.groupNum):
                self.groups.append(self.AnimationGroupRef(file, pos, fmt))
                pos += size 
Example 23
Project: LayoutExporterU   Author: aboood40091   File: bflan.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file, pos):
                (srcPaneNameBytes,
                 targetGroupNameBytes) = struct.unpack_from('>25s25s', file, pos)

                self.srcPaneName = readString(srcPaneNameBytes)
                self.targetGroupName = readString(targetGroupNameBytes)

                #print(self.srcPaneName) 
Example 24
Project: LayoutExporterU   Author: aboood40091   File: bflan.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file, pos):
            super().__init__(file, pos); pos += 8

            (self.animShareInfoOffset,
             self.shareNum) = struct.unpack_from('>IH', file, pos)

            pos += self.animShareInfoOffset - 8
            self.animShareInfos = []

            for _ in range(self.shareNum):
                self.animShareInfos.append(self.AnimationShareInfo(file, pos))
                pos += 52 
Example 25
Project: LayoutExporterU   Author: aboood40091   File: bflan.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file, pos):
                            (self.frame,
                             self.value,
                             self.slope) = struct.unpack_from('>3f', file, pos) 
Example 26
Project: LayoutExporterU   Author: aboood40091   File: bflan.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file, pos):
                    initPos = pos

                    (self.magic,
                     self.num) = struct.unpack_from('>4sB', file, pos); pos += 8

                    self.animTargets = []
                    animTargetOffsets = struct.unpack_from('>%dI' % self.num, file, pos)

                    for pAnimTarget in animTargetOffsets:
                        self.animTargets.append(self.AnimationTarget(file, initPos + pAnimTarget)) 
Example 27
Project: LayoutExporterU   Author: aboood40091   File: bflan.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file, pos):
            initPos = pos
            super().__init__(file, pos); pos += 8

            (self.frameSize,
             self.loop,
             self.fileNum,
             self.animContNum,
             animContOffsetsOffset) = struct.unpack_from('>HBx2HI', file, pos); pos += 12

            self.fileNames = []
            self.formats = []

            for i in range(self.fileNum):
                pFileName, = struct.unpack_from('>I', file, pos + 4*i)
                fileName = readString(file, pos + pFileName)
                format = ""

                assert fileName[-6:] == ".bflim"
                fileName = fileName[:-6]

                if len(fileName) > 2:
                    if fileName[-1] in 'abcdefghijklmnopqrstu' and fileName[-2] == "^":
                        format = fileName[-1:]
                        fileName = fileName[:-2]

                self.fileNames.append(fileName)
                self.formats.append(format)

            pos = initPos + animContOffsetsOffset
            animContOffsets = struct.unpack_from('>%dI' % self.animContNum, file, pos)
            self.animConts = []

            for pAnimCont in animContOffsets:
                self.animConts.append(self.AnimationContent(file, initPos + pAnimCont)) 
Example 28
Project: LayoutExporterU   Author: aboood40091   File: bflan.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file):
        if file[4:6] != b'\xFE\xFF':
            raise NotImplementedError("Only big endian layouts are supported")  # TODO little endian

        (self.magic,
         self.headSize,
         self.version,
         self.fileSize,
         self.numSections) = struct.unpack_from('>4s2xH2IH', file)

        assert self.magic == b'FLAN'
        major = self.version >> 24  # TODO little endian
        if major not in [2, 3, 5]:
            print("Untested BFLAN version: %s\n" % hex(self.version))

        self.tag = None
        self.share = None
        self.info = None

        pos = 20
        for _ in range(self.numSections):
            if file[pos:pos + 4] == b'pat1':
                self.tag = self.AnimationTagBlock(file, pos, major)
                pos += self.tag.blockHeader.size

            elif file[pos:pos + 4] == b'pah1':
                self.share = self.AnimationShareBlock(file, pos)
                pos += self.share.blockHeader.size

            elif file[pos:pos + 4] == b'pai1':
                self.info = self.AnimationBlock(file, pos)
                pos += self.info.blockHeader.size 
Example 29
Project: LayoutExporterU   Author: aboood40091   File: bflyt.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file, pos):
            super().__init__(file, pos)

            self.texNum = struct.unpack_from('>H', self.data)[0]
            self.textures = []
            self.formats = []

            if self.texNum:
                _printTex("Textures:")

            for i in range(self.texNum):
                pTexture = struct.unpack_from('>I', self.data, 4 * (i+1))[0] + 4
                texture = readString(self.data, pTexture)
                format = ""

                assert texture[-6:] == ".bflim"
                texture = texture[:-6]

                if len(texture) > 2:
                    if texture[-1] in 'abcdefghijklmnopqrstu' and texture[-2] == "^":
                        format = texture[-1:]
                        texture = texture[:-2]

                _printTex(texture)
                self.textures.append(texture)
                self.formats.append(format)

            if self.texNum:
                _printTex() 
Example 30
Project: LayoutExporterU   Author: aboood40091   File: bflyt.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file, pos):
                    self.translate = struct.unpack_from('>2f', file, pos); pos += 8
                    self.rotate = struct.unpack_from('>f', file, pos); pos += 4
                    self.scale = struct.unpack_from('>2f', file, pos); pos += 8

                    _printMat("Texture Translation:", self.translate)
                    _printMat("Texture Rotation:", self.rotate)
                    _printMat("Texture Scale:", self.scale) 
Example 31
Project: LayoutExporterU   Author: aboood40091   File: bflyt.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file, pos):
                    _texGenTypes = ["Matrix2x4"]
                    _texGenSrcs = [
                        "Tex0", "Tex1", "Tex2", "Orthogonal Projection",
                        "Pane-Based Projection", "Perspective Projection",
                    ]

                    (self.texGenType,
                     self.texGenSrc) = struct.unpack_from('>2B2x', file, pos); pos += 4

                    self.projectionTexGenParameter = None

                    _printMat("Texture Coordinate Generation Type: %s" % _texGenTypes[self.texGenType])
                    _printMat("Texture Coordinate Generation Source: %s" % _texGenSrcs[self.texGenSrc]) 
Example 32
Project: LayoutExporterU   Author: aboood40091   File: bflyt.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file, pos):
                    _funcs = [
                        "Never", "Less", "Less or Equal", "Equal",
                        "Not Equal", "Greater or Equal", "Greater", "Always",
                    ]

                    (self.func,
                     self.ref) = struct.unpack_from('>Bf', file, pos); pos += 5

                    _printMat("Alpha Compare function: %s" % _funcs[self.func])
                    _printMat("Alpha Compare: %f" % self.ref) 
Example 33
Project: LayoutExporterU   Author: aboood40091   File: bflyt.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file, pos, isAlpha=False):
                    _factors = [
                        "0", "1", "Destination Color", "Destination Inverse Color", "Source Alpha",
                        "Source Inverse Alpha", "Destination Alpha", "Destination Inverse Alpha",
                        "Source Color", "Source Inverse Color",
                    ]

                    _blendOp = [
                        "Disable", "Add", "Subtract", "Reverse Subtract",
                        "Select Min", "Select Max",
                    ]

                    _logicOp = [
                        "Disable", "No Op", "Clear", "Set", "Copy",
                        "InvCopy", "Inv", "And", "Nand", "Or",
                        "Nor", "Xor", "Equiv", "RevAnd",
                        "InvAnd", "RevOr", "InvOr",
                    ]

                    (self.blendOp,
                     self.srcFactor,
                     self.dstFactor,
                     self.logicOp) = struct.unpack_from('>4B', file, pos); pos += 4

                    if isAlpha:
                        _printMat("Alpha:")

                    _printMat("Blend Op: %s" % _blendOp[self.blendOp])
                    _printMat("Source factor: %s" % _factors[self.srcFactor])
                    _printMat("Destination factor: %s" % _factors[self.dstFactor])
                    _printMat("Logic Op: %s" % _logicOp[self.logicOp]) 
Example 34
Project: LayoutExporterU   Author: aboood40091   File: bflyt.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file, pos):
                    self.rotate = struct.unpack_from('>f', file, pos); pos += 4
                    self.scale = struct.unpack_from('>2f', file, pos); pos += 8

                    _printMat("Indirect Rotation:", self.rotate)
                    _printMat("Indirect Scale:", self.scale) 
Example 35
Project: LayoutExporterU   Author: aboood40091   File: bflyt.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file, pos):
                    self.translate = struct.unpack_from('>2f', file, pos); pos += 8
                    self.scale = struct.unpack_from('>2f', file, pos); pos += 8
                    flag = file[pos]; pos += 4

                    self.isFittingLayoutSize = bool(flag & 1)
                    self.isFittingPaneSizeEnabled = bool(flag & 2)
                    self.isAdjustProjectionSREnabled = bool(flag & 4)

                    _printMat("Projection Translation:", self.translate)
                    _printMat("Projection Scale:", self.scale)
                    _printMat("Projection isFittingLayoutSize:", self.isFittingLayoutSize)
                    _printMat("Projection isFittingPaneSizeEnabled:", self.isFittingPaneSizeEnabled)
                    _printMat("Projection isAdjustProjectionSREnabled:", self.isAdjustProjectionSREnabled) 
Example 36
Project: LayoutExporterU   Author: aboood40091   File: bflyt.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file, pos):
                    self.blackInterporateColor = struct.unpack_from('>3B', file, pos); pos += 3
                    self.whiteInterporateColor = struct.unpack_from('>4B', file, pos); pos += 5

                    _printMat("Font Shadow Black Interporate Color:", self.blackInterporateColor)
                    _printMat("Font Shadow White Interporate Color:", self.whiteInterporateColor) 
Example 37
Project: LayoutExporterU   Author: aboood40091   File: bflyt.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file, pos):
            super().__init__(file, pos); pos += 84
            self.vtxCols = [struct.unpack_from('>4B', file, pos + 4*i) for i in range(4)]; pos += 16

            (self.materialIdx,
             self.texCoordNum) = struct.unpack_from('>HB', file, pos); pos += 4

            self.texCoords = []
            for _ in range(self.texCoordNum):
                self.texCoords.append([struct.unpack_from('>2f', file, pos + 8*z) for z in range(4)]); pos += 32 
Example 38
Project: LayoutExporterU   Author: aboood40091   File: bflyt.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file, pos):
                (self.evalTimeOffset,
                 self.evalTimeWidth,
                 self.loopType,
                 self.originV,
                 self.hasAnimationInfo) = struct.unpack_from('>2f3Bx', file, pos) 
Example 39
Project: LayoutExporterU   Author: aboood40091   File: bflyt.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file, pos):
                self.vtxCols = [struct.unpack_from('>4B', file, pos + 4*i) for i in range(4)]; pos += 16

                (self.materialIdx,
                 self.texCoordNum) = struct.unpack_from('>HB', file, pos); pos += 4

                self.texCoords = []
                for _ in range(self.texCoordNum):
                    self.texCoords.append([struct.unpack_from('>2f', file, pos + 8*z) for z in range(4)]); pos += 32 
Example 40
Project: LayoutExporterU   Author: aboood40091   File: bflyt.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file, pos):
                    self.userData = readString(struct.unpack_from('>8s', file, pos)[0]); pos += 8
                    self.translate = struct.unpack_from('>3f', file, pos); pos += 12
                    self.rotate = struct.unpack_from('>3f', file, pos); pos += 12
                    self.scale = struct.unpack_from('>2f', file, pos); pos += 8
                    self.size = struct.unpack_from('>2f', file, pos); pos += 8
                    self.alpha = file[pos] 
Example 41
Project: LayoutExporterU   Author: aboood40091   File: bflyt.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file, pos):
            initPos = pos
            super().__init__(file, pos); pos += 84

            self.propertyNum, = struct.unpack_from('>I', file, pos); pos += 4
            self.magnify = struct.unpack_from('>2f', file, pos); pos += 8

            self.properties = [self.PartsProperty(file, initPos, pos + 40*i) for i in range(self.propertyNum)]
            pos += 40 * self.propertyNum

            self.filename = readString(file, pos)
            assert self.filename 
Example 42
Project: LayoutExporterU   Author: aboood40091   File: common.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file, pos):
        self.magic, self.size = struct.unpack_from('>4sI', file, pos) 
Example 43
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: compat.py    MIT License 5 votes vote down vote up
def get_terminal_size():
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        def ioctl_GWINSZ(fd):
            try:
                import fcntl
                import termios
                import struct
                cr = struct.unpack_from(
                    'hh',
                    fcntl.ioctl(fd, termios.TIOCGWINSZ, '12345678')
                )
            except:
                return None
            if cr == (0, 0):
                return None
            return cr
        cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
        if not cr:
            try:
                fd = os.open(os.ctermid(), os.O_RDONLY)
                cr = ioctl_GWINSZ(fd)
                os.close(fd)
            except:
                pass
        if not cr:
            cr = (os.environ.get('LINES', 25), os.environ.get('COLUMNS', 80))
        return int(cr[1]), int(cr[0]) 
Example 44
Project: sic   Author: Yanixos   File: tarfile.py    GNU General Public License v3.0 5 votes vote down vote up
def calc_chksums(buf):
    """Calculate the checksum for a member's header by summing up all
       characters except for the chksum field which is treated as if
       it was filled with spaces. According to the GNU tar sources,
       some tars (Sun and NeXT) calculate chksum with signed char,
       which will be different if there are chars in the buffer with
       the high bit set. So we calculate two checksums, unsigned and
       signed.
    """
    unsigned_chksum = 256 + sum(struct.unpack_from("148B8x356B", buf))
    signed_chksum = 256 + sum(struct.unpack_from("148b8x356b", buf))
    return unsigned_chksum, signed_chksum 
Example 45
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 5 votes vote down vote up
def decode_ID0(packet):		# NAVDATA_DEMO_TAG
	dataset = struct.unpack_from("HHIIfffifffIffffffffffffIIffffffffffff", packet, 0)
	if dataset[1] != 148:		print "*** ERROR : Navdata-Demo-Options-Package (ID=0) has the wrong size !!!"
	demo=[[0,0,0,0,0,0,0,0,0,0,0,0],0,[0,0,0],0,[0,0,0],0,[0,0,0,0,0,0,0,0,0],[0,0,0],0,0,[0,0,0,0,0,0,0,0,0],[0,0,0]]
	demo[0][ 0] = dataset[2]>>15&1	# DEFAULT			(bool)
	demo[0][ 1] = dataset[2]>>16&1	# INIT				(bool)
	demo[0][ 2] = dataset[2]>>17&1	# LANDED			(bool)
	demo[0][ 3] = dataset[2]>>18&1	# FLYING			(bool)
	demo[0][ 4] = dataset[2]>>19&1	# HOVERING			(bool)  (Seems like landing)
	demo[0][ 5] = dataset[2]>>20&1	# TEST				(bool)
	demo[0][ 6] = dataset[2]>>21&1	# TRANS_TAKEOFF		(bool)
	demo[0][ 7] = dataset[2]>>22&1	# TRANS_GOFIX		(bool)
	demo[0][ 8] = dataset[2]>>23&1	# TRANS_LANDING		(bool)
	demo[0][ 9] = dataset[2]>>24&1	# TRANS_LOOPING		(bool)
	demo[0][10] = dataset[2]>>25&1	# TRANS_NO_VISION	(bool)
	demo[0][11] = dataset[2]>>26&1	# NUM_STATE			(bool)
	demo[1]		=dataset[3]			# vbat_flying_percentage	battery voltage (filtered) in percent	(uint32)
	demo[2][0]	=dataset[4]/1000.0	# theta						pitch in degrees						(float)
	demo[2][1]	=dataset[5]/1000.0	# phi						roll  in degrees						(float)
	demo[2][2]	=dataset[6]/1000.0	# psi						yaw   in degrees						(float)
	demo[3]		=dataset[7]/10.0	# altitude					altitude in centimetres					(int32)
	demo[4][0]	=dataset[8]			# vx						estimated speed in X in mm/s			(float)	
	demo[4][1]	=dataset[9]			# vy						estimated speed in Y in mm/s			(float)
	demo[4][2]	=dataset[10]		# vz						estimated speed in Z in mm/s			(float)
	demo[5]		=dataset[11]		# num_frames				streamed frame index 					(uint32) (Not used to integrate in video stage)
	for i in range (0,9,1):	demo[6][i]	= dataset[12+i]	# detection_camera_rot		Camera parameters compute by detection	(float matrix33)
	for i in range (0,3,1):	demo[7][i]	= dataset[21+i]	# detection_camera_trans	Deprecated ! Don't use !				(float vector31)
	demo[8]								= dataset[24]	# detection_tag_index		Deprecated ! Don't use !				(uint32)
	demo[9]								= dataset[25]	# detection_camera_type   	Type of tag								(uint32)
	for i in range (0,9,1):	demo[10][i]	= dataset[26+i]	# drone_camera_rot			Camera parameters computed by drone		(float matrix33)
	for i in range (0,3,1):	demo[11][i]	= dataset[35+i]	# drone_camera_trans		Deprecated ! Don't use !				(float vector31)
	return(demo)
	
##### ID = 1 ### "time" ####################################################### 
Example 46
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 5 votes vote down vote up
def decode_ID1(packet):			#NAVDATA_TIME_TAG
	dataset = struct.unpack_from("HHI", packet, 0)
	if dataset[1] != 8:		print "*** ERROR : navdata-time-Options-Package (ID=1) has the wrong size !!!"
	time=[0.0]
	# Value: 11 most significant bits represent the seconds, and the 21 least significant bits represent the microseconds.
	for i in range(0,21,1):		time[0] += ((dataset[2]>>i&1)*(2**i))		# Calculating the millisecond-part
	time[0] /= 1000000
	for i in range(21,32,1):	time[0] += (dataset[2]>>i&1)*(2**(i-21))	# Calculating second-part
	return(time)
	
##### ID = 2 ### "raw_measures" ################################################ 
Example 47
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 5 votes vote down vote up
def decode_ID3(packet):  		#NAVDATA_PHYS_MEASURES_TAG
	dataset = struct.unpack_from("HHfHffffffIII", packet, 0)
	if dataset[1] != 46:		print "*** ERROR : navdata-phys_measures-Options-Package (ID=3) has the wrong size !!!"
	phys_measures = [0,0,[0,0,0],[0,0,0],0,0,0]
	phys_measures[0] = dataset[2]	#float32   accs_temp
	phys_measures[1] = dataset[3]	#uint16    gyro_temp
	phys_measures[4] = dataset[10]	#uint32    alim3V3              3.3volt alim [LSB]
	phys_measures[5] = dataset[11]	#uint32    vrefEpson            ref volt Epson gyro [LSB]
	phys_measures[6] = dataset[12]	#uint32    vrefIDG              ref volt IDG gyro [LSB]
	dataset = struct.unpack_from(">HHfHffffffIII", packet, 0) 	#switch from little to big-endian
	for i in range(0,3,1):	phys_measures[2][i] = dataset[4+i]	#float32   phys_accs[xyz] 
	for i in range(0,3,1):	phys_measures[3][i] = dataset[7+i]	#float32   phys_gyros[xyz]
	return(phys_measures)

##### ID = 4 ### "gyros_offsets" ############################################## 
Example 48
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 5 votes vote down vote up
def decode_ID4(packet):  		#NNAVDATA_GYROS_OFFSETS_TAG
	dataset = struct.unpack_from("HHfff", packet, 0)
	if dataset[1] != 16:		print "*** ERROR : navdata-gyros_offsets-Options-Package (ID=4) has the wrong size !!!"
	gyros_offsets = [0,0,0]
	for i in range (0,3,1):		gyros_offsets[i]=dataset[i+2]	# offset_g[xyz]				in deg/s					(float)
	return(gyros_offsets)

##### ID = 5 ### "euler_angles" ############################################### 
Example 49
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 5 votes vote down vote up
def decode_ID6(packet):			#NAVDATA_REFERENCES_TAG
	dataset = struct.unpack_from("HHiiiiiiiiffffffIfffffI", packet, 0)
	if dataset[1] != 88:		print "*** ERROR : navdata-references-Options-Package (ID=6) has the wrong size !!!"
	references = [[0,0,0],[0,0],[0,0,0],[0.0,0.0],[0.0,0.0],[0.0,0.0],0,[0.0,0.0,0.0,0.0,0.0,0]]
	references[0][0] = dataset[2]		#ref_theta  	Theta_ref_embedded [milli-deg]	(int32)
	references[0][1] = dataset[3]		#ref_phi		Phi_ref_embedded [milli-deg]	(int32)
	references[0][2] = dataset[9]		#ref_psi		Psi_ref_embedded [milli-deg]	(int32)
	references[1][0] = dataset[4]		#ref_theta_I	Theta_ref_int [milli-deg]		(int32)
	references[1][1] = dataset[5]		#ref_phi_I		Phi_ref_int [milli-deg]			(int32)
	references[2][0] = dataset[6]		#ref_pitch		Pitch_ref_embedded [milli-deg]	(int32)
	references[2][1] = dataset[7]		#ref_roll		Roll_ref_embedded [milli-deg]	(int32)
	references[2][2] = dataset[8]		#ref_yaw		Yaw_ref_embedded [milli-deg/s]	(int32)
	references[3][0] = dataset[10]		#vx_ref			Vx_Ref_[mm/s]					(float)
	references[3][1] = dataset[11]		#vy_ref			Vy_Ref_[mm/s]					(float)
	references[4][0] = dataset[12]		#theta_mod		Theta_modele [radian]			(float)
	references[4][1] = dataset[13]		#phi_mod		Phi_modele [radian]				(float)
	references[5][0] = dataset[14]		#k_v_x											(float)
	references[5][1] = dataset[15]		#k_v_y											(float)
	references[6]    = dataset[16]		#k_mode											(uint32)
	references[7][0] = dataset[17]		#ui_time										(float)
	references[7][1] = dataset[18]		#ui_theta										(float)
	references[7][2] = dataset[19]		#ui_phi											(float)
	references[7][3] = dataset[20]		#ui_psi											(float)
	references[7][4] = dataset[21]		#ui_psi_accuracy								(float)
	references[7][5] = dataset[22]		#ui_seq											(int32)
	return(references)

##### ID = 7 ### "trims" ###################################################### 
Example 50
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 5 votes vote down vote up
def decode_ID7(packet):			#NAVDATA_TRIMS_TAG
	dataset = struct.unpack_from("HHfff", packet, 0)
	if dataset[1] != 16:		print "*** ERROR : navdata-trims-Options-Package (ID=7) has the wrong size !!!"
	trims = [0,0,0]
	trims[0] = dataset[2]	#  angular_rates_trim									(float)
	trims[1] = dataset[3]	#  euler_angles_trim_theta	[milli-deg]					(float)
	trims[2] = dataset[4]	#  euler_angles_trim_phi	[milli-deg]					(float)
	return(trims)

##### ID = 8 ### "rc_references" ############################################## 
Example 51
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 5 votes vote down vote up
def decode_ID8(packet):			#NAVDATA_RC_REFERENCES_TAG
	dataset = struct.unpack_from("HHiiiii", packet, 0)
	if dataset[1] != 24:		print "*** ERROR : navdata-rc_references-Options-Package (ID=8) has the wrong size !!!"
	rc_references = [0,0,0,0,0]
	rc_references[0] = dataset[2]	#  rc_ref_pitch		Pitch_rc_embedded			(int32)
	rc_references[1] = dataset[3]	#  rc_ref_roll		Roll_rc_embedded			(int32)
	rc_references[2] = dataset[4]	#  rc_ref_yaw		Yaw_rc_embedded				(int32)
	rc_references[3] = dataset[5]	#  rc_ref_gaz		Gaz_rc_embedded				(int32)
	rc_references[4] = dataset[6]	#  rc_ref_ag		Ag_rc_embedded				(int32)
	return(rc_references)

##### ID = 9 ### "pwm" ######################################################## 
Example 52
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 5 votes vote down vote up
def decode_ID9(packet):			#NAVDATA_PWM_TAG
	dataset = struct.unpack_from("HHBBBBBBBBffffiiifiiifHHHHff", packet, 0)
	if dataset[1] != 76 and dataset[1] != 92:   #92 since firmware 2.4.8 ?
		print "*** ERROR : navdata-navdata_pwm-Options-Package (ID=9) has the wrong size !!!"
		#print "Soll: 76     Ist:",dataset[1]
	pwm = [[0,0,0,0],[0,0,0,0],0.0,0.0,0.0,0.0,[0,0,0],0.0,[0,0,0,0.0],[0,0,0,0],0.0,0.0]
	for i in range(0,4,1):	pwm[0][i] = dataset[2+i]	#  motor1/2/3/4		[Pulse-width mod]	(uint8)
	for i in range(0,4,1):	pwm[1][i] = dataset[6+i]	#  sat_motor1/2/3/4	[Pulse-width mod]	(uint8)
	pwm[2]    = dataset[10]			# gaz_feed_forward		[Pulse-width mod]	(float)
	pwm[3]    = dataset[11]			# gaz_altitud			[Pulse-width mod]	(float)
	pwm[4]    = dataset[12]			# altitude_integral		[mm/s]				(float)
	pwm[5]    = dataset[13]			# vz_ref				[mm/s]				(float)
	pwm[6][0] = dataset[14]			# u_pitch				[Pulse-width mod]	(int32)
	pwm[6][1] = dataset[15]			# u_roll				[Pulse-width mod]	(int32)
	pwm[6][2] = dataset[16]			# u_yaw					[Pulse-width mod]	(int32)
	pwm[7]    = dataset[17]			# yaw_u_I				[Pulse-width mod]	(float)
	pwm[8][0] = dataset[18]			# u_pitch_planif		[Pulse-width mod]	(int32)
	pwm[8][1] = dataset[19]			# u_roll_planif			[Pulse-width mod]	(int32)
	pwm[8][2] = dataset[20]			# u_yaw_planif			[Pulse-width mod]	(int32)
	pwm[8][3] = dataset[21]			# u_gaz_planif			[Pulse-width mod]	(float)
	for i in range(0,4,1):
		pwm[9][i] = dataset[22+i]	# current_motor1/2/3/4	[mA]				(uint16)
	pwm[10]   = dataset[26]			# altitude_prop			[Pulse-width mod]	(float)
	pwm[11]   = dataset[27]			# altitude_der			[Pulse-width mod]	(float)
	return(pwm)

##### ID = 10 ### "altitude" ################################################### 
Example 53
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 5 votes vote down vote up
def decode_ID12(packet):		#NAVDATA_VISION_OF_TAG
	dataset = struct.unpack_from("HHffffffffff", packet, 0)
	if dataset[1] != 44:	print "*** ERROR : navdata-vision_of-Options-Package (ID=12) has the wrong size !!!"
	vision_of = [[0.0,0.0,0.0,0.0,0.0],[0.0,0.0,0.0,0.0,0.0]]
	for i in range (0,5,1):		vision_of[0][i] = dataset[2+i]	#  of_dx[5]							(float)
	for i in range (0,5,1):		vision_of[1][i] = dataset[7+i]	#  of_dy[5]							(float)
	return(vision_of)

##### ID = 13 ### "vision" ##################################################### 
Example 54
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 5 votes vote down vote up
def decode_ID13(packet):		#NAVDATA_VISION_TAG
	dataset = struct.unpack_from("HHIiffffifffiIffffffIIff", packet, 0)
	if dataset[1] != 92:	print "*** ERROR : navdata-vision-Options-Package (ID=13) has the wrong size !!!"
	vision=[0,0,0.0,0.0,0.0,0.0,0,[0.0,0.0,0.0],0,0.0,[0.0,0.0,0.0],[0.0,0.0,0.0],0,0,[0.0,0.0]]
	vision[0] = dataset[2]				# vision_state FIXME: What are the meanings of the tags ?
	vision[1] = dataset[3]				# vision_misc							(int32)	
	vision[2] = dataset[4]				# vision_phi_trim						(float)
	vision[3] = dataset[5]				# vision_phi_ref_prop					(float)
	vision[4] = dataset[6]				# vision_theta_trim						(float)
	vision[5] = dataset[7]				# vision_theta_ref_prop					(float)
	vision[6] = dataset[8]				# new_raw_picture						(int32)
	for i in range (0,3,1):
		vision[7][i] = dataset[9+i]		# theta/phi/psi_capture					(float)
	vision[8] = dataset[12]				# altitude_capture						(int32)
	for i in range (0,21,1):						# Calculating milisecond-part
		vision[9] += ((dataset[13]>>i&1)*(2**i))
	vision[9] /= 1000000
	for i in range (21,32,1):						# Calculating second-part
		vision[9] += (dataset[13]>>i&1)*(2**(i-21))	# time_capture			(float)
	for i in range (0,3,1):
		vision[10][i] = dataset[14+i]	#  velocities[xyz]						(float)
	for i in range (0,3,1):
		vision[11][i] = dataset[17+i]	#  delta_phi/theta/psi					(float)
	vision[12] =    dataset[20]			# gold_defined							(uint32)
	vision[13] =    dataset[21]			# gold_reset							(uint32)	
	vision[14][0] = dataset[22]			# gold_x								(float)
	vision[14][1] = dataset[23]			# gold_y								(float)
	return(vision)

##### ID = 14 ### "vision_perf" ############################################### 
Example 55
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 5 votes vote down vote up
def decode_ID14(packet):		#NAVDATA_VISION_PERF_TAG
	dataset = struct.unpack_from("HHffffffffffffffffffffffffff", packet, 0)
	if dataset[1] != 108:		print "*** ERROR : navdata-vision_of-Options-Package (ID=14) has the wrong size !!!"
	vision_perf=[0.0,0.0,0.0,0.0,0.0,0.0,[0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0]]
	vision_perf[0] = dataset[2]				# time_szo								(float)
	vision_perf[1] = dataset[3]				# time_corners							(float)
	vision_perf[2] = dataset[4]				# time_compute							(float)
	vision_perf[3] = dataset[5]				# time_tracking							(float)
	vision_perf[4] = dataset[6]				# time_trans							(float)
	vision_perf[5] = dataset[7]				# time_update							(float)
	for i in range (0,20,1):
		vision_perf[6][i] = dataset[8+i]	# time_custom[20]						(float)
	return(vision_perf)

##### ID = 15 ### "trackers_send" ############################################# 
Example 56
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 5 votes vote down vote up
def decode_ID15(packet):  		#NAVDATA_TRACKERS_SEND_TAG
	dataset = struct.unpack_from("HHiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii", packet, 0)
	if dataset[1] != 364:		print "*** ERROR : navdata-trackers_send-Options-Package (ID=15) has the wrong size !!!"
	DEFAULT_NB_TRACKERS_WIDTH  = 6
	DEFAULT_NB_TRACKERS_HEIGHT = 5
	limit = DEFAULT_NB_TRACKERS_WIDTH*DEFAULT_NB_TRACKERS_HEIGHT
	trackers_send = [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]]]
	for i in range (0, limit, 1):
		trackers_send[0][i] = dataset[2+i]			#  locked[limit]				(int32)
	for i in range (0, limit, 1):
		trackers_send[1][i][0] = dataset[32+(i*2)]	#  point[x[limit],y[limit]]		(int32)
		trackers_send[1][i][1] = dataset[33+(i*2)]
	return(trackers_send)

##### ID = 16 ### "vision_detect" ############################################# 
Example 57
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 5 votes vote down vote up
def decode_ID18(packet):  		#NAVDATA_ADC_DATA_FRAME_TAG
	dataset = struct.unpack_from("HHIBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB", packet, offsetND)
	if dataset[1] != 40:	print "*** ERROR : navdata-adc_data_frame-Package (ID=18) has the wrong size !!!"
	adc_data_frame = [0,[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]
	adc_data_frame[0] = dataset[2]									# version								(uint32)
	for i in range (0,32,1):	adc_data_frame[1][i] = dataset[3+i]	# data_frame[32]						(uint8)
	return(adc_data_frame)

##### ID = 19 ### "video_stream" ############################################### 
Example 58
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 5 votes vote down vote up
def decode_ID20(packet):  		#NAVDATA_GAMES_TAG
	dataset = struct.unpack_from("HHII", packet, offsetND)
	if dataset[1] != 12:	print "*** ERROR : navdata-games-Package (ID=20) has the wrong size !!!"
	games = [0,0]
	games[0] = dataset[2]	# double_tap_counter 			   							(uint32)
	games[1] = dataset[3]	# finish_line_counter										(uint32)
	return(games)

##### ID = 21 ### "pressure_raw" ############################################### 
Example 59
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 5 votes vote down vote up
def decode_ID21(packet):  		#NAVDATA_PRESSURE_RAW_TAG
	dataset = struct.unpack_from("HHihii", packet, offsetND)
	if dataset[1] != 18:	print "*** ERROR : navdata-pressure_raw-Package (ID=21) has the wrong size !!!"
	pressure_raw = [0,0,0,0]
	pressure_raw[0] = dataset[2]	# up 			   									(int32)
	pressure_raw[1] = dataset[3]	# ut												(int16)
	pressure_raw[2] = dataset[4]	# Temperature_meas 									(int32)
	pressure_raw[3] = dataset[5]	# Pression_meas										(int32)
	return(pressure_raw)

##### ID = 22 ### "magneto" #################################################### 
Example 60
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 5 votes vote down vote up
def decode_ID25(packet):		#NAVDATA_HDVIDEO-TAG
	dataset = struct.unpack_from("HHfffffff", packet, offsetND)
	if dataset[1] != 32:	print "*** ERROR : navdata-hdvideo_stream-Package (ID=25) has the wrong size !!!"
	hdvideo_stream = [0.0,0.0,0.0,0.0,0.0,0.0,0.0]
	hdvideo_stream[0] = dataset[2]	# hdvideo_state 			   					(float)
	hdvideo_stream[1] = dataset[3]	# storage_fifo_nb_packets						(float)
	hdvideo_stream[2] = dataset[4]	# storage_fifo_size 							(float)
	hdvideo_stream[3] = dataset[5]	# usbkey_size 			USB key in kb (no key=0)(float)
	hdvideo_stream[4] = dataset[6]	# usbkey_freespace		USB key in kb (no key=0)(float)
	hdvideo_stream[5] = dataset[7]	# frame_number 			PaVE field of the frame starting to be encoded for the HD stream (float)
	hdvideo_stream[6] = dataset[8]	# usbkey_remaining_time	[sec]					(float)
	return(hdvideo_stream)

##### ID = 26 ### "wifi" ###################################################### 
Example 61
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 5 votes vote down vote up
def decode_ID26(packet):		#NAVDATA_WIFI_TAG
	dataset = struct.unpack_from("HHI", packet, offsetND)
	if dataset[1] != 8:	print "*** ERROR : navdata-wifi-Package (ID=26) has the wrong size !!!"
	wifi = dataset[2]	# link_quality 			   								(uint32)
	return(wifi)

##### ID = 27 ### "zimmu_3000" ################################################ 
Example 62
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 5 votes vote down vote up
def decode_ID27(packet):  #NAVDATA_ZIMU_3000_TAG
	dataset = struct.unpack_from("HHif", packet, offsetND)
	if dataset[1] != 12 and dataset[1] != 216:		# 216 since firmware 2.4.8 ?
		print "*** ERROR : navdata-zimmu_3000-Package (ID=27) has the wrong size !!!"
	zimmu_3000 = [0,0.0]
	zimmu_3000[0] = dataset[2]	# vzimmuLSB 			   							(int32)
	zimmu_3000[1] = dataset[3]	# vzfind 			   								(float)
	return(zimmu_3000)

##### Footer ### "chksum" ##################################################### 
Example 63
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 5 votes vote down vote up
def decode_Footer(packet,allpacket):   ### Decode Checksum options-package ID=65535
	dataset = struct.unpack_from("HHI", packet, offsetND)
	if dataset[1] != 8:	print "*** ERROR : Checksum-Options-Package (ID=65535) has the wrong size !!!"
	chksum = 	[0,False]
	chksum[0] = dataset[2]
	sum, plen =	0, len(allpacket)-8
	for i in range (0,plen,1):	sum += ord(allpacket[i])		# Slows down this Navdata-subprocess massivly
	if sum == chksum[0]:	chksum[1] = True
	return(chksum)


###############################################################################
### Navdata-Decoding
############################################################################### 
Example 64
Project: neos-classic-electrum-server   Author: neoscoin   File: deserialize.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _read_num(self, format):
        (i,) = struct.unpack_from(format, self.input, self.read_cursor)
        self.read_cursor += struct.calcsize(format)
        return i 
Example 65
Project: neos-classic-electrum-server   Author: neoscoin   File: deserialize.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def script_GetOp(bytes):
    i = 0
    while i < len(bytes):
        vch = None
        opcode = ord(bytes[i])
        i += 1

        if opcode <= opcodes.OP_PUSHDATA4:
            nSize = opcode
            if opcode == opcodes.OP_PUSHDATA1:
                nSize = ord(bytes[i])
                i += 1
            elif opcode == opcodes.OP_PUSHDATA2:
                (nSize,) = struct.unpack_from('<H', bytes, i)
                i += 2
            elif opcode == opcodes.OP_PUSHDATA4:
                (nSize,) = struct.unpack_from('<I', bytes, i)
                i += 4
            if i+nSize > len(bytes):
              vch = "_INVALID_"+bytes[i:]
              i = len(bytes)
            else:
             vch = bytes[i:i+nSize]
             i += nSize

        yield (opcode, vch, i) 
Example 66
Project: face_rekognition   Author: cnidus   File: MspImagePlugin.py    GNU General Public License v3.0 5 votes vote down vote up
def decode(self, buffer):
        
        img = io.BytesIO()
        blank_line = bytearray((0xff,)*((self.state.xsize+7)//8))
        try:
            self.fd.seek(32)
            rowmap = struct.unpack_from("<%dH" % (self.state.ysize),
                                        self.fd.read(self.state.ysize*2))
        except struct.error:
            raise IOError("Truncated MSP file in row map")

        for x, rowlen in enumerate(rowmap):
            try:
                if rowlen == 0:
                    img.write(blank_line)
                    continue
                row = self.fd.read(rowlen)
                if len(row) != rowlen:
                    raise IOError("Truncated MSP file, expected %d bytes on row %s",
                                  (rowlen, x))
                idx = 0
                while idx < rowlen:
                    runtype = i8(row[idx])
                    idx += 1
                    if runtype == 0:
                        (runcount, runval) = struct.unpack("Bc", row[idx:idx+2])
                        img.write(runval * runcount)
                        idx += 2
                    else:
                        runcount = runtype
                        img.write(row[idx:idx+runcount])
                        idx += runcount
                        
            except struct.error:
                raise IOError("Corrupted MSP file in row %d" %x)
            
        self.set_as_raw(img.getvalue(), ("1", 0, 1))
                
        return 0,0 
Example 67
Project: deb-python-cassandra-driver   Author: openstack   File: murmur3.py    Apache License 2.0 5 votes vote down vote up
def body_and_tail(data):
    l = len(data)
    nblocks = l // 16
    tail = l % 16
    if nblocks:
        # we use '<', specifying little-endian byte order for data bigger than
        # a byte so behavior is the same on little- and big-endian platforms
        return struct.unpack_from('<' + ('qq' * nblocks), data), struct.unpack_from('b' * tail, data, -tail), l
    else:
        return tuple(), struct.unpack_from('b' * tail, data, -tail), l 
Example 68
Project: bitpay-brick   Author: javgh   File: bt_record.py    MIT License 5 votes vote down vote up
def data(self, string):
        log.debug("parse '{0}' record".format(self.type))
        if len(string) > 0:
            f = io.BytesIO(string)
            oob_length = struct.unpack_from('<H', f.read(2))[0]
            log.debug("bluetooth oob length {0}".format(oob_length))
            if oob_length > len(string):
                log.warning("OOB data length exceeds payload length")
                oob_length = len(string)
            self._bdaddr = bytearray(reversed(f.read(6)))
            while f.tell() < oob_length:
                eir_length = ord(f.read(1))
                eir_type = ord(f.read(1))
                self.eir[eir_type] = f.read(eir_length-1) 
Example 69
Project: jawfish   Author: war-and-code   File: tarfile.py    MIT License 5 votes vote down vote up
def calc_chksums(buf):
    """Calculate the checksum for a member's header by summing up all
       characters except for the chksum field which is treated as if
       it was filled with spaces. According to the GNU tar sources,
       some tars (Sun and NeXT) calculate chksum with signed char,
       which will be different if there are chars in the buffer with
       the high bit set. So we calculate two checksums, unsigned and
       signed.
    """
    unsigned_chksum = 256 + sum(struct.unpack_from("148B8x356B", buf))
    signed_chksum = 256 + sum(struct.unpack_from("148b8x356b", buf))
    return unsigned_chksum, signed_chksum 
Example 70
Project: Sinopac-Order-API   Author: ypochien   File: pyT4.py    MIT License 5 votes vote down vote up
def convert_stock_bytes_to_dict(stock_order_res_bytes):
    """委託回報為bytes。所以先轉為有結構的NameTuple,但每個item得從bytes to utf8"""
    stock_record_field = 'trade_type,account,code_id,ord_price,ord_qty,ord_seq,ord_date,effective_date,' \
                         'ord_time,ord_no,ord_soruce,org_ord_seq,ord_bs,ord_type,market_id,price_type,ord_status,Msg'
    StockOrderRecord = namedtuple('StockOrderRecord', stock_record_field)
    stock_order_res_format = '2s15s6s6s3s6s8s8s6s5s3s6s1s2s1s1s2s60s'
    if len(stock_order_res_bytes) != struct.calcsize(stock_order_res_format):
        return stock_order_res_bytes
    stock_order_res = StockOrderRecord._make(struct.unpack_from(stock_order_res_format, stock_order_res_bytes))
    stock_order_res_lst = [str(item, 'cp950') for item in stock_order_res]
    return StockOrderRecord(*stock_order_res_lst)._asdict() 
Example 71
Project: Sinopac-Order-API   Author: ypochien   File: pyT4.py    MIT License 5 votes vote down vote up
def convert_future_bytes_to_dict(future_order_res_bytes):
    future_record_field = 'trade_type,account,market_id,code_id,f_callput,ord_bs,ord_price,price_type,ord_qty,' \
                          'ord_no,ord_seq,ord_type,oct_type,f_mttype,f_composit,c_futopt,c_code,c_callput,' \
                          'c_buysell,c_price,c_quantity,ord_date,preord_date,ord_time,type,err_code,msg'
    FutureOrderRecord = namedtuple('FutureOrderRecord', future_record_field)
    future_order_res_format = '2s15s1s10s1s1s12s3s4s6s6s3s1s1s2s1s10s1s1s12s4s8s8s6s1s4s60s'
    if len(future_order_res_bytes) != struct.calcsize(future_order_res_format):
        return future_order_res_bytes
    future_order_res = FutureOrderRecord._make(struct.unpack_from(future_order_res_format, future_order_res_bytes))
    future_order_res_lst = [str(item, 'cp950') for item in future_order_res]
    return FutureOrderRecord(*future_order_res_lst)._asdict() 
Example 72
Project: cronosparser   Author: occrp   File: parser.py    MIT License 5 votes vote down vote up
def vword(data):
    # A vodka word is a russian data unit, encompassing three bytes on good
    # days, with a flag in the fourth.
    word, = struct.unpack_from('<I', data)
    num = word & 0x00ffffff
    flags = (word & 0xff000000) >> 24
    return num, flags 
Example 73
Project: cronosparser   Author: occrp   File: parser.py    MIT License 5 votes vote down vote up
def parse_table(text, next_byte):
    # Once we've guessed a table definition location, we can start
    # parsing the name; followed by the two-letter table abbreviation
    # and the count of columns.
    next_len = ord(text[next_byte])
    next_byte = next_byte + 1
    if len(text) < next_byte + next_len + 10:
        return
    if ord(text[next_byte + next_len]) != 2:
        return
    # Get the table name.
    table_name = decode_text(text[next_byte:next_byte + next_len])
    if table_name is None:
        return
    next_byte = next_byte + next_len + 1
    # Get the table abbreviation.
    table_abbr = decode_text(text[next_byte:next_byte + 2])
    if table_abbr is None:
        return
    next_byte = next_byte + 2
    if ord(text[next_byte]) != 1:
        # raise CronosException('Table ID not ended by 0x01!')
        return
    next_byte = next_byte + 4
    # Get the number of columns for the table.
    col_count, = struct.unpack_from('I', text, next_byte)
    return {
        'name': table_name,
        'abbr': table_abbr,
        'columns': parse_columns(text, next_byte + 4, col_count),
        'column_count': col_count
    } 
Example 74
Project: JukeBox   Author: gauravsarkar97   File: compat.py    MIT License 5 votes vote down vote up
def get_terminal_size():
        """
        Returns a tuple (x, y) representing the width(x) and the height(y)
        in characters of the terminal window.
        """
        def ioctl_GWINSZ(fd):
            try:
                import fcntl
                import termios
                import struct
                cr = struct.unpack_from(
                    'hh',
                    fcntl.ioctl(fd, termios.TIOCGWINSZ, '12345678')
                )
            except:
                return None
            if cr == (0, 0):
                return None
            return cr
        cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
        if not cr:
            try:
                fd = os.open(os.ctermid(), os.O_RDONLY)
                cr = ioctl_GWINSZ(fd)
                os.close(fd)
            except:
                pass
        if not cr:
            cr = (os.environ.get('LINES', 25), os.environ.get('COLUMNS', 80))
        return int(cr[1]), int(cr[0]) 
Example 75
Project: PiRogue   Author: PiRanhaLysis   File: gls.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def toU32(bits):
    import struct
    return struct.unpack_from(">I", bits)[0] 
Example 76
Project: UR5_Controller   Author: tsinghua-rll   File: rtif.py    MIT License 4 votes vote down vote up
def unpack(byte_stream):
        joint_data = namedtuple("vector6d", ("p0", "p1", "p2", "p3", "p4", "p5"))
        coordinate_data = namedtuple("coordinate6d", ("x", "y", "z", "rx", "ry", "rz"))
        message = {"Time Step": 0.0,
                   "Target Joint Positions": joint_data(0., 0., 0., 0., 0., 0.),
                   "Target Joint Velocities": joint_data(0., 0., 0., 0., 0., 0.),
                   "Target Joint Accelerations": joint_data(0., 0., 0., 0., 0., 0.),
                   "Target Joint Currents": joint_data(0., 0., 0., 0., 0., 0.),
                   "Target Joint Torques": joint_data(0., 0., 0., 0., 0., 0.),
                   "Actual Joint Positions": joint_data(0., 0., 0., 0., 0., 0.),
                   "Actual Joint Velocities": joint_data(0., 0., 0., 0., 0., 0.),
                   "Actual Joint Currents": joint_data(0., 0., 0., 0., 0., 0.),
                   "Joint Control Currents": joint_data(0., 0., 0., 0., 0., 0.),
                   "Actual Tool Coordinates": coordinate_data(0., 0., 0., 0., 0., 0.),
                   "Actual Tool Speed": coordinate_data(0., 0., 0., 0., 0., 0.),
                   "Generalized Tool Force": coordinate_data(0., 0., 0., 0., 0., 0.),
                   "Target Tool Coordinates": coordinate_data(0., 0., 0., 0., 0., 0.),
                   "Target Tool Speed": coordinate_data(0., 0., 0., 0., 0., 0.),
                   "Digit Input": 0.0,
                   "Temperature": joint_data(0., 0., 0., 0., 0., 0.),
                   "Execute Time": 0.0,
                   "Robot Mode": 0.0,
                   "Joint Mode": joint_data(0., 0., 0., 0., 0., 0.),
                   "Safety Mode": 0.0,
                   }
        cnt, message["Time Step"] = struct.unpack_from('!Id', byte_stream)
        bias = 12                       # byte count + time step = 12 byte
        while 0 < bias < cnt:
            if bias == 12:
                message["Target Joint Positions"] = joint_data(*struct.unpack_from('!6d', byte_stream, bias + 0 * 48))
                message["Target Joint Velocities"] = joint_data(*struct.unpack_from('!6d', byte_stream, bias + 1 * 48))
                message["Target Joint Accelerations"] = joint_data(*struct.unpack_from('!6d', byte_stream, bias + 2 * 48))
                message["Target Joint Currents"] = joint_data(*struct.unpack_from('!6d', byte_stream, bias + 3 * 48))
                message["Target Joint Torques"] = joint_data(*struct.unpack_from('!6d', byte_stream, bias + 4 * 48))
                message["Actual Joint Positions"] = joint_data(*struct.unpack_from('!6d', byte_stream, bias + 5 * 48))
                message["Actual Joint Velocities"] = joint_data(*struct.unpack_from('!6d', byte_stream, bias + 6 * 48))
                message["Actual Joint Currents"] = joint_data(*struct.unpack_from('!6d', byte_stream, bias + 7 * 48))
                message["Joint Control Currents"] = joint_data(*struct.unpack_from('!6d', byte_stream, bias + 7 * 48))
                bias += 9 * 48
            elif bias == 444:
                message["Actual Tool Coordinates"] = coordinate_data(*struct.unpack_from('!6d', byte_stream, bias + 0 * 48))
                message["Actual Tool Speed"] = coordinate_data(*struct.unpack_from('!6d', byte_stream, bias + 1 * 48))
                message["Generalized Tool Force"] = coordinate_data(*struct.unpack_from('!6d', byte_stream, bias + 2 * 48))
                message["Target Tool Coordinates"] = coordinate_data(*struct.unpack_from('!6d', byte_stream, bias + 3 * 48))
                message["Target Tool Speed"] = coordinate_data(*struct.unpack_from('!6d', byte_stream, bias + 4 * 48))
                bias += 5 * 48
            elif bias == 684:
                message["Digit Input"] = struct.unpack_from('!d', byte_stream, bias + 0)
                message["Temperature"] = joint_data(*struct.unpack_from('!6d', byte_stream, bias + 8))
                message["Execute Time"] = struct.unpack_from('!d', byte_stream, bias + 56)
                message["Robot Mode"] = struct.unpack_from('!d', byte_stream, bias + 72)
                message["Joint Mode"] = joint_data(*struct.unpack_from('!6d', byte_stream, bias + 80))
                message["Safety Mode"] = struct.unpack_from('!d', byte_stream, bias + 128)
                bias = -1
        return message, (bias < 0) 
Example 77
Project: LayoutExporterU   Author: aboood40091   File: bflyt.py    GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, file, pos):
            super().__init__(file, pos); pos += 8

            _xModes = {
                0: "Center",
                1: "Left",
                2: "Right",
            }

            _yModes = {
                0: "Center",
                1: "Top",
                2: "Bottom",
            }

            (self.flag,
             self.basePosition,
             self.alpha,
             self.flagEx,
             nameBytes,
             userDataBytes) = struct.unpack_from('>4B24s8s', file, pos); pos += 36

            self.name = readString(nameBytes)
            self.userData = readString(userDataBytes)

            _printPan("\nPane name: %s" % self.name)
            _printPan("Pane visible:", bool(self.flag & 1))
            _printPan("Pane influenced alpha:", bool((self.flag >> 1) & 1))
            _printPan("Pane location adjust:", bool((self.flag >> 2) & 1))
            _printPan("Pane hidden (in editor?):", bool((self.flag >> 7) & 1))
            ignorePartsMagnify = bool(self.flagEx & 1)
            _printPan("Pane ignore parts magnify:", ignorePartsMagnify)
            if not ignorePartsMagnify:
                _printPan("Pane parts magnify influence:", bool((self.flagEx >> 1) & 1))

            parentRelativeY = (self.basePosition >> 6) & 3
            parentRelativeX = (self.basePosition >> 4) & 3
            baseY = (self.basePosition >> 2) & 3
            baseX = self.basePosition & 3

            _printPan("Pane base X position:", _xModes[baseX])
            _printPan("Pane base Y position:", _xModes[baseY])
            _printPan("Pane parent-relative X position:", _xModes[parentRelativeX])
            _printPan("Pane parent-relative Y position:", _xModes[parentRelativeY])

            self.translate = struct.unpack_from('>3f', file, pos); pos += 12
            self.rotate = struct.unpack_from('>3f', file, pos); pos += 12
            self.scale = struct.unpack_from('>2f', file, pos); pos += 8
            self.size = struct.unpack_from('>2f', file, pos); pos += 8

            _printPan("Pane translation:", self.translate)
            _printPan("Pane rotation:", self.rotate)
            _printPan("Pane scale:", self.scale)
            _printPan("Pane size:", self.size)

            self.parent = None
            self.childList = [] 
Example 78
Project: LayoutExporterU   Author: aboood40091   File: bflyt.py    GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, file, pos):
            initPos = pos
            super().__init__(file, pos); pos += 84

            (self.textBufBytes,
             self.textStrBytes,
             self.materialIdx,
             self.fontIdx,
             self.textPosition,
             self.textAlignment,
             self.textBoxFlag,
             self.italicRatio,
             self.textStrOffset) = struct.unpack_from('>4H3BxfI', file, pos); pos += 20

            self.readTextBoxFlag()

            self.textCols = [struct.unpack_from('>4B', file, pos + 4*i) for i in range(2)]; pos += 8
            self.fontSize = struct.unpack_from('>2f', file, pos); pos += 8

            (self.charSpace,
             self.lineSpace,
             self.textIDOffset) = struct.unpack_from('>2fI', file, pos); pos += 12

            self.shadowOffset = struct.unpack_from('>2f', file, pos); pos += 8
            self.shadowScale = struct.unpack_from('>2f', file, pos); pos += 8
            self.shadowCols = [struct.unpack_from('>4B', file, pos + 4*i) for i in range(2)]; pos += 8

            (self.shadowItalicRatio,
             self.perCharacterTransformOffset) = struct.unpack_from('>fI', file, pos); pos += 8

            pos = initPos + self.textStrOffset
            if self.forceAssignTextLength:
                self.text = readString(file[pos:pos + self.textStrBytes], 0, 2, 'utf-16be')

            else:
                self.text = readString(file[pos:pos + self.textBufBytes], 0, 2, 'utf-16be')

            pos = initPos + self.textIDOffset
            self.textID = readString(file, pos)

            self.perCharacterTransform = None
            if self.perCharacterTransformEnabled:
                if self.perCharacterTransformOffset:
                    pos = initPos + self.perCharacterTransformOffset
                    self.perCharacterTransform = self.PerCharacterTransform(file, pos); pos += 12
                    if self.perCharacterTransform.hasAnimationInfo:
                        self.perCharacterTransformAnimationInfo = FLAN.AnimationBlock.AnimationContent.AnimationInfo(file, pos)

                else:
                    print("Whoopsie-daisy")
                    self.perCharacterTransformEnabled = False 
Example 79
Project: LayoutExporterU   Author: aboood40091   File: bflyt.py    GNU General Public License v3.0 4 votes vote down vote up
def toVersion(file, output, dVersion):
    if file[4:6] != b'\xFE\xFF':
        raise NotImplementedError("Only big endian layouts are supported")  # TODO little endian

    (magic,
     version,
     numSections) = struct.unpack_from('>4s4xI4xH', file)

    assert magic == b'FLYT'

    file = bytearray(file)
    dMajor = dVersion >> 24
    major = version >> 24  # TODO little endian
    if major not in [2, 3, 5]:
        print("Untested BFLYT version: %s\n" % hex(version))

    pos = 0x14
    for _ in range(numSections):
        if file[pos:pos + 4] == b'cnt1':
            cnt = FLYT.Control(file, pos, major)
            size = cnt.blockHeader.size

            file[pos:pos + size] = cnt.save(dMajor)
            pos += cnt.blockHeader.size

        elif file[pos:pos + 4] == b'grp1':
            group = FLYT.Group(file, pos, major)
            size = group.blockHeader.size

            file[pos:pos + size] = group.save(dMajor)
            pos += group.blockHeader.size

        else:
            section = Section(file, pos)
            pos += section.blockHeader.size

    file[:0x14] = struct.pack(
        '>4s2H2IH2x',
        b'FLYT',
        0xFEFF,
        20,
        dVersion,
        len(file),
        numSections,
    )

    with open(output, "wb") as out:
        out.write(file) 
Example 80
Project: ARPET   Author: juliagarriga   File: ps_drone.py    MIT License 4 votes vote down vote up
def getNavdata(packet,choice):
	navdata =	{}
	length =	len(packet)
	dataset = 	struct.unpack_from("IIII", packet, 0)	# Reading (Header, State, Sequence, Vision)
	navdata["state"] = decode_Header(dataset)
	offsetND = 	struct.calcsize("IIII")
	#Demo-mode contains normally Option-Packages with ID=0 (_navdata_demo_t), ID=16 (seems empty) and ID=65535 (checksum)
	# Full Mode contains
	while offsetND < length:
		dataset =  struct.unpack_from("HH", packet, offsetND)	# Reading (Header, Length)
		if dataset[0]== 0 and choice[ 0]: navdata["demo"]				= decode_ID0(packet[offsetND:])
		if dataset[0]== 1 and choice[ 1]: navdata["time"] 				= decode_ID1(packet[offsetND:])
		if dataset[0]== 2 and choice[ 2]: navdata["raw_measures"]		= decode_ID2(packet[offsetND:])
		if dataset[0]== 3 and choice[ 3]: navdata["phys_measures"] 		= decode_ID3(packet[offsetND:])
		if dataset[0]== 4 and choice[ 4]: navdata["gyros_offsets"] 		= decode_ID4(packet[offsetND:])
		if dataset[0]== 5 and choice[ 5]: navdata["euler_angles"]		= decode_ID5(packet[offsetND:])
		if dataset[0]== 6 and choice[ 6]: navdata["references"] 		= decode_ID6(packet[offsetND:])
		if dataset[0]== 7 and choice[ 7]: navdata["trims"]				= decode_ID7(packet[offsetND:])
		if dataset[0]== 8 and choice[ 8]: navdata["rc_references"] 		= decode_ID8(packet[offsetND:])
		if dataset[0]== 9 and choice[ 9]: navdata["pwm"]				= decode_ID9(packet[offsetND:])
		if dataset[0]==10 and choice[10]: navdata["altitude"]			= decode_ID10(packet[offsetND:])
		if dataset[0]==11 and choice[11]: navdata["vision_raw"] 		= decode_ID11(packet[offsetND:])
		if dataset[0]==12 and choice[12]: navdata["vision_of"] 			= decode_ID12(packet[offsetND:])
		if dataset[0]==13 and choice[13]: navdata["vision"]				= decode_ID13(packet[offsetND:])
		if dataset[0]==14 and choice[14]: navdata["vision_perf"]		= decode_ID14(packet[offsetND:])
		if dataset[0]==15 and choice[15]: navdata["trackers_send"] 		= decode_ID15(packet[offsetND:])
		if dataset[0]==16 and choice[16]: navdata["vision_detect"]		= decode_ID16(packet[offsetND:])
		if dataset[0]==17 and choice[17]: navdata["watchdog"] 			= decode_ID17(packet[offsetND:])
		if dataset[0]==18 and choice[18]: navdata["adc_data_frame"] 	= decode_ID18(packet[offsetND:])
		if dataset[0]==19 and choice[19]: navdata["video_stream"] 		= decode_ID19(packet[offsetND:])
		if dataset[0]==20 and choice[20]: navdata["games"]				= decode_ID20(packet[offsetND:])
		if dataset[0]==21 and choice[21]: navdata["pressure_raw"]		= decode_ID21(packet[offsetND:])
		if dataset[0]==22 and choice[22]: navdata["magneto"]			= decode_ID22(packet[offsetND:])
		if dataset[0]==23 and choice[23]: navdata["wind_speed"] 		= decode_ID23(packet[offsetND:])
		if dataset[0]==24 and choice[24]: navdata["kalman_pressure"]	= decode_ID24(packet[offsetND:])
		if dataset[0]==25 and choice[25]: navdata["hdvideo_stream"]		= decode_ID25(packet[offsetND:])
		if dataset[0]==26 and choice[26]: navdata["wifi"]				= decode_ID26(packet[offsetND:])
		if dataset[0]==27 and choice[27]: navdata["zimmu_3000"]			= decode_ID27(packet[offsetND:])
		if dataset[0]==65535 and choice[28]: navdata["chksum"]			= decode_Footer(packet[offsetND:],packet)
		offsetND += dataset[1]
	return(navdata)

###############################=-
###	Threads					###=- 
###############################=-