parse the data section of a packet, it can range from 0 to many bytes
324734
def parsedata(self, packet):
        ''''''
        data = []
        datalength = ord(packet[3])
        position = 4
        while position < datalength + 4:
            data.append(packet[position])
            position += 1
        return data
951166
def parse_packet(packet):
    """"""
    frame = parse_ltv_packet(packet)
    if frame is None:
        frame = parse_ibeacon_packet(packet)
    return frame
786037
def parse_byte_range(byte_range):
    '''
    '''
    if byte_range.strip() == '':
        return None, None

    m = BYTE_RANGE_RE.match(byte_range)
    if not m:
        raise ValueError('Invalid byte range %s' % byte_range)

    first, last = [x and int(x) for x in m.groups()]
    if last and last < first:
        raise ValueError('Invalid byte range %s' % byte_range)
    return first, last
464468
private void parseData(byte[] data)
	{
		int bytesRead = 0;

		if (grouped)
		{
			group = data[bytesRead];
			bytesRead ++;
		}
		if (encrypted)
		{
			encrType = data[bytesRead];
			bytesRead ++;
		}
		if (lengthIndicator)
		{
			dataLength = Helpers.convertDWordToInt(data, bytesRead);
			bytesRead += 4;
		}

		frameData = new byte[data.length - bytesRead];
		System.arraycopy(data, bytesRead, frameData, 0, frameData.length);
	}
1331522
def parse(self, buffer):
        """"""
        log.debug("parsing a %d byte packet" % len(buffer))
        (opcode,) = struct.unpack(str("!H"), buffer[:2])
        log.debug("opcode is %d" % opcode)
        packet = self.__create(opcode)
        packet.buffer = buffer
        return packet.decode()
771955
def _complete_last_byte(self, packet):
        """"""
        padded_size = self.get_size()
        padding_bytes = padded_size - len(packet)
        if padding_bytes > 0:
            packet += Pad(padding_bytes).pack()
        return packet
1010528
def read(self):
        

        data = self.dev.read()

        if len(data) == 0:
            self.log.warning("READ : Nothing received")
            return

        if data == b'\x00':
            self.log.warning("READ : Empty packet (Got \\x00)")
            return

        pkt = bytearray(data)
        data = self.dev.read(pkt[0])
        pkt.extend(bytearray(data))

        self.log.info("READ : %s" % self.format_packet(pkt))
        self.do_callback(pkt)
        return pkt
1141920
def parse(self):
        
        if len(self.raw_data) < 3:
            ValueError("parse() may only be called on a frame containing at "
                       "least 3 bytes of raw data (see fill())")

        # First two bytes are the length of the data
        raw_len = self.raw_data[1:3]

        # Unpack it
        data_len = struct.unpack("> h", raw_len)[0]

        # Read the data
        data = self.raw_data[3:3 + data_len]
        chksum = self.raw_data[-1]

        # Checksum check
        self.data = data
        if not self.verify(chksum):
            raise ValueError("Invalid checksum")
811517
def read_bytes(self, count):
        """"""
        if self.pos + count > self.remaining_length:
            return NC.ERR_PROTOCOL, None
        
        ba = bytearray(count)
        for x in xrange(0, count):
            ba[x] = self.payload[self.pos]
            self.pos += 1
        
        return NC.ERR_SUCCESS, ba
374020
def CollectData(self):
        
        while 1:  # loop until we get data or a timeout
            _bytes = self._ReadPacket()
            if not _bytes:
                return None
            if len(_bytes) < 4 + 8 + 1 or _bytes[0] < 0x20 or _bytes[0] > 0x2F:
                logging.warning("Wanted data, dropped type=0x%02x, len=%d",
                                _bytes[0], len(_bytes))
                continue

            seq, _type, x, y = struct.unpack("BBBB", _bytes[:4])
            data = [
                struct.unpack(">hhhh", _bytes[x:x + 8])
                for x in range(4,
                               len(_bytes) - 8, 8)
            ]

            if self._last_seq and seq & 0xF != (self._last_seq + 1) & 0xF:
                logging.warning("Data sequence skipped, lost packet?")
            self._last_seq = seq

            if _type == 0:
                if not self._coarse_scale or not self._fine_scale:
                    logging.warning(
                        "Waiting for calibration, dropped data packet.")
                    continue
                out = []
                for main, usb, aux, voltage in data:
                    if main & 1:
                        coarse = ((main & ~1) - self._coarse_zero)
                        out.append(coarse * self._coarse_scale)
                    else:
                        out.append((main - self._fine_zero) * self._fine_scale)
                return out
            elif _type == 1:
                self._fine_zero = data[0][0]
                self._coarse_zero = data[1][0]
            elif _type == 2:
                self._fine_ref = data[0][0]
                self._coarse_ref = data[1][0]
            else:
                logging.warning("Discarding data packet type=0x%02x", _type)
                continue

            # See http://wiki/Main/MonsoonProtocol for details on these values.
            if self._coarse_ref != self._coarse_zero:
                self._coarse_scale = 2.88 / (
                    self._coarse_ref - self._coarse_zero)
            if self._fine_ref != self._fine_zero:
                self._fine_scale = 0.0332 / (self._fine_ref - self._fine_zero)
1089335
def parse_range_header(header, maxlen=0):
    ''' '''
    if not header or header[:6] != 'bytes=': return
    ranges = [r.split('-', 1) for r in header[6:].split(',') if '-' in r]
    for start, end in ranges:
        try:
            if not start:  # bytes=-100    -> last 100 bytes
                start, end = max(0, maxlen-int(end)), maxlen
            elif not end:  # bytes=100-    -> all but the first 99 bytes
                start, end = int(start), maxlen
            else:          # bytes=100-200 -> bytes 100-200 (inclusive)
                start, end = int(start), min(int(end)+1, maxlen)
            if 0 <= start < end <= maxlen:
                yield start, end
        except ValueError:
            pass
917340
def parse_close(data: bytes) -> Tuple[int, str]:
    
    length = len(data)
    if length >= 2:
        code, = struct.unpack("!H", data[:2])
        check_close(code)
        reason = data[2:].decode("utf-8")
        return code, reason
    elif length == 0:
        return 1005, ""
    else:
        assert length == 1
        raise WebSocketProtocolError("Close frame too short")
994842
def parse_packet(data, format=None):
    
    unpacked = struct.unpack(BASE_FORMAT, data[:_FORMAT_SIZE])
    psize, protocol, mac, gateway, time, ptype = unpacked
    header = Header(psize, protocol, mac, gateway, time, ptype)
    return header, data[_FORMAT_SIZE:]
475134
def _parse_packet(rawdata):
    

    if (len(rawdata) < len(_MAGIC) + 1) or (_MAGIC != rawdata[:len(_MAGIC)]):
        # Wrong protocol
        return (None, None)

    opcode = rawdata[len(_MAGIC):len(_MAGIC)+1]
    payload = rawdata[len(_MAGIC)+1:]

    return (opcode, payload)
810371
def _parse(self):
        
        timestamp = 0
        invalid = False
        while True:
            byte = yield
            hdr = byte
            
            # Sync packet.
            if hdr == 0:
                packets = 0
                while True:
                    # Check for final 1 bit after at least 5 all-zero sync packets
                    if (packets >= 5) and (byte == 0x80):
                        break
                    elif byte == 0:
                        packets += 1
                    else:
                        # Get early non-zero packet, reset sync packet counter.
                        #packets = 0
                        invalid = True
                        break
                    byte = yield
                self._itm_page = 0
            # Overflow packet.
            elif hdr == 0x70:
                self._send_event(events.TraceOverflow(timestamp))
            # Protocol packet.
            elif (hdr & 0x3) == 0:
                c = (hdr >> 7) & 0x1
                d = (hdr >> 4) & 0b111
                # Local timestamp.
                if (hdr & 0xf) == 0 and d not in (0x0, 0x3):
                    ts = 0
                    tc = 0
                    # Local timestamp packet format 1.
                    if c == 1:
                        tc = (hdr >> 4) & 0x3
                        while c == 1:
                            byte = yield
                            ts = (ts << 7) | (byte & 0x7f)
                            c = (byte >> 7) & 0x1
                    # Local timestamp packet format 2.
                    else:
                        ts = (hdr >> 4) & 0x7
                    timestamp += ts
                    self._send_event(events.TraceTimestamp(tc, timestamp))
                # Global timestamp.
                elif hdr in (0b10010100, 0b10110100):
                    t = (hdr >> 5) & 0x1
                    # TODO handle global timestamp
                # Extension.
                elif (hdr & 0x8) == 0x8:
                    sh = (hdr >> 2) & 0x1
                    if c == 0:
                        ex = (hdr >> 4) & 0x7
                    else:
                        ex = 0
                        while c == 1:
                            byte = yield
                            ex = (ex << 7) | (byte & 0x7f)
                            c = (byte >> 7) & 0x1
                    if sh == 0:
                        # Extension packet with sh==0 sets ITM stimulus page.
                        self._itm_page = ex
                    else:
                        #self._send_event(events.TraceEvent("Extension: SH={:d} EX={:#x}\n".format(sh, ex), timestamp))
                        invalid = True
                # Reserved packet.
                else:
                    invalid = True
            # Source packet.
            else:
                ss = hdr & 0x3
                l = 1 << (ss - 1)
                a = (hdr >> 3) & 0x1f
                if l == 1:
                    payload = yield
                elif l == 2:
                    byte1 = yield
                    byte2 = yield
                    payload = (byte1 | 
                                (byte2 << 8))
                else:
                    byte1 = yield
                    byte2 = yield
                    byte3 = yield
                    byte4 = yield
                    payload = (byte1 | 
                                (byte2 << 8) |
                                (byte3 << 16) |
                                (byte4 << 24))
                
                # Instrumentation packet.
                if (hdr & 0x4) == 0:
                    port = (self._itm_page * 32) + a
                    self._send_event(events.TraceITMEvent(port, payload, l, timestamp))
                # Hardware source packets...
                # Event counter
                elif a == 0:
                    self._send_event(events.TraceEventCounter(payload, timestamp))
                # Exception trace
                elif a == 1:
                    exceptionNumber = payload & 0x1ff
                    exceptionName = self._core.exception_number_to_name(exceptionNumber, True)
                    fn = (payload >> 12) & 0x3
                    if 1 <= fn <= 3:
                        self._send_event(events.TraceExceptionEvent(exceptionNumber, exceptionName, fn, timestamp))
                    else:
                        invalid = True
                # Periodic PC
                elif a == 2:                        
                    # A payload of 0 indicates a period PC sleep event.
                    self._send_event(events.TracePeriodicPC(payload, timestamp))
                # Data trace
                elif 8 <= a <= 23:
                    type = (hdr >> 6) & 0x3
                    cmpn = (hdr >> 4) & 0x3
                    bit3 = (hdr >> 3) & 0x1
                    # PC value
                    if type == 0b01 and bit3 == 0:
                        self._send_event(events.TraceDataTraceEvent(cmpn=cmpn, pc=payload, ts=timestamp))
                    # Address
                    elif type == 0b01 and bit3 == 1:
                        self._send_event(events.TraceDataTraceEvent(cmpn=cmpn, addr=payload, ts=timestamp))
                    # Data value
                    elif type == 0b10:
                        self._send_event(events.TraceDataTraceEvent(cmpn=cmpn, value=payload, rnw=(bit3 == 0), sz=l, ts=timestamp))
                    else:
                        invalid = True
                # Invalid DWT 'a' value.
                else:
                    invalid = True
255511
def parse(self, data):
        

        self.validate_packet(data)

        packet_length = data[0]
        packet_type = data[1]
        sub_type = data[2]
        sequence_number = data[3]
        command_type = data[4]
        transceiver_type = data[5]
        transceiver_type_text = _MSG1_RECEIVER_TYPE.get(data[5])
        firmware_version = data[6]

        flags = self._int_to_binary_list(data[7])
        flags.extend(self._int_to_binary_list(data[8]))
        flags.extend(self._int_to_binary_list(data[9]))

        enabled, disabled = self._log_enabled_protocols(flags, PROTOCOLS)

        return {
            'packet_length': packet_length,
            'packet_type': packet_type,
            'packet_type_name': self.PACKET_TYPES.get(packet_type),
            'sequence_number': sequence_number,
            'sub_type': sub_type,
            'sub_type_name': self.PACKET_SUBTYPES.get(sub_type),
            'command_type': command_type,
            'transceiver_type': transceiver_type,
            'transceiver_type_text': transceiver_type_text,
            'firmware_version': firmware_version,
            'enabled_protocols': enabled,
            'disabled_protocols': disabled,
        }
695010
def parse(self, plist):
        
        if not isinstance(plist, PacketList):
            plist = PacketList(plist)
        for pkt in plist[LLTD]:
            if LLTDQueryLargeTlv in pkt:
                key = "%s:%s:%d" % (pkt.real_dst, pkt.real_src, pkt.seq)
                self.types_offsets[key] = (pkt[LLTDQueryLargeTlv].type,
                                           pkt[LLTDQueryLargeTlv].offset)
            elif LLTDQueryLargeTlvResp in pkt:
                try:
                    key = "%s:%s:%d" % (pkt.real_src, pkt.real_dst, pkt.seq)
                    content, offset = self.types_offsets[key]
                except KeyError:
                    continue
                loc = slice(offset, offset + pkt[LLTDQueryLargeTlvResp].len)
                key = "%s > %s [%s]" % (
                    pkt.real_src, pkt.real_dst,
                    LLTDQueryLargeTlv.fields_desc[0].i2s.get(content, content),
                )
                data = self.data.setdefault(key, array("B"))
                datalen = len(data)
                if datalen < loc.stop:
                    data.extend(array("B", b"\x00" * (loc.stop - datalen)))
                data[loc] = array("B", pkt[LLTDQueryLargeTlvResp].value)