Write raw and parsed data to log file for debugging purposes

@param rawPacket : Raw packet as received via the serial port
@param parsedPacket : Parsed packet object
512375
function writeToLogFile(rawPacket, parsedPacket) {
  if (!debugMode) { return; }

  var now = new Date().toUTCString();

  fs.appendFile(config.debugRawDataFile, 'Package received at ' + now + ':\n' + rawPacket + '\n\n', function (err) {
    if (err) {
      console.error('Could not write raw package to ' + config.debugRawDataFile);
    }
  });

  fs.appendFile(config.debugParsedDataFile, 'Package received at ' + now + ':\n' + JSON.stringify(parsedPacket, true, 4) + '\n\n', function (err) {
    if (err) {
      console.error('Could not write parsed package to ' + config.debugParsedDataFile);
    }
  });
}
939791
def raw_on(serial):
    

    def flush_to_msg(serial, msg):
        """Read the rx serial data until we reach an expected message."""
        data = serial.read_until(msg)
        if not data.endswith(msg):
            if COMMAND_LINE_FLAG:
                print(data)
            raise IOError('Could not enter raw REPL.')

    def flush(serial):
        """Flush all rx input without relying on serial.flushInput()."""
        n = serial.inWaiting()
        while n > 0:
            serial.read(n)
            n = serial.inWaiting()

    raw_repl_msg = b'raw REPL; CTRL-B to exit\r\n>'
    # Send CTRL-B to end raw mode if required.
    serial.write(b'\x02')
    # Send CTRL-C three times between pauses to break out of loop.
    for i in range(3):
        serial.write(b'\r\x03')
        time.sleep(0.01)
    flush(serial)
    # Go into raw mode with CTRL-A.
    serial.write(b'\r\x01')
    flush_to_msg(serial, raw_repl_msg)
    # Soft Reset with CTRL-D
    serial.write(b'\x04')
    flush_to_msg(serial, b'soft reboot\r\n')
    # Some MicroPython versions/ports/forks provide a different message after
    # a Soft Reset, check if we are in raw REPL, if not send a CTRL-A again
    data = serial.read_until(raw_repl_msg)
    if not data.endswith(raw_repl_msg):
        serial.write(b'\r\x01')
        flush_to_msg(serial, raw_repl_msg)
    flush(serial)
520889
def unpack(cls, rawpacket):
        

        structs_ = get_structs_for_rawpacket(rawpacket)

        for struct_ in structs_:
            try:
                return cls(*struct_.unpack(rawpacket))
            except struct.error:
                raise
                # Try next one.
                pass

        # Packet ID 0xff is a pseudo-packet representing
        # packets unknown to `python-TSIP` in their raw format.
        #
        return cls(0xff, rawpacket)
347633
def _raw(self, msg):
        
        if len(msg) != self.device.write(self.out_ep, msg, self.interface):
            self.device.write(self.out_ep, self.errorText, self.interface)
            raise TicketNotPrinted()
814010
public void processPacketAESF8(RawPacket pkt, int index) {
        // byte[] iv = new byte[16];

        // 4 bytes of the iv are zero
        // the first byte of the RTP header is not used.
        ivStore[0] = 0;
        ivStore[1] = 0;
        ivStore[2] = 0;
        ivStore[3] = 0;
      
        // Need the encryption flag
        index = index | 0x80000000;

        // set the index and the encrypt flag in network order into IV
        ivStore[4] = (byte) (index >> 24);
        ivStore[5] = (byte) (index >> 16);
        ivStore[6] = (byte) (index >> 8);
        ivStore[7] = (byte) index;
        
        // The fixed header follows and fills the rest of the IV
        ByteBuffer buf = pkt.getBuffer();
        buf.rewind();
        buf.get(ivStore, 8, 8);

        // Encrypted part excludes fixed header (8 bytes), index (4 bytes), and
        // authentication tag (variable according to policy)  
        final int payloadOffset = 8;
        final int payloadLength = pkt.getLength() - (4 + policy.getAuthTagLength());
        SRTPCipherF8.process(cipher, pkt.getBuffer(), payloadOffset, payloadLength, ivStore, cipherF8);
    }
681222
def _raw_pack(key_handle, flags, data):
    
    # #define YHSM_HMAC_RESET          0x01    // Flag to indicate reset at first packet
    # #define YHSM_HMAC_FINAL          0x02    // Flag to indicate that the hash shall be calculated
    # typedef struct {
    #   uint32_t keyHandle;                 // Key handle
    #   uint8_t flags;                      // Flags
    #   uint8_t numBytes;                   // Number of bytes in data packet
    #   uint8_t data[YHSM_MAX_PKT_SIZE - 6]; // Data to be written
    # } YHSM_HMAC_SHA1_GENERATE_REQ;
    return struct.pack('<IBB', key_handle, flags, len(data)) + data
736015
protected final void serializeTo( RawDataBuffer out )
    {
    	// Level 1 - Always unserialized
    	byte lvl1Flags = (byte)((priority & 0x0F)+
    	                        (redelivered ? (1 << 4) : 0)+
    	                        (deliveryMode == DeliveryMode.PERSISTENT ? (1 << 5) : 0)+
    	                        (expiration != 0 ? (1 << 6) : 0)+ // Expiration value present
    	                        (id != null ? (1 << 7) : 0)); // ID value present
    	out.writeByte(lvl1Flags);
    	if (expiration != 0)
    		out.writeLong(expiration);
    	if (id != null)
    		out.writeUTF(id);
    	DestinationSerializer.serializeTo(destination, out);
    	
        // Level 2 - Unserialized if required by a message selector
    	byte lvl2Flags = (byte)((correlId != null ? (1 << 0) : 0)+
    	                        (replyTo != null ? (1 << 1) : 0)+
    	                        (timestamp != 0 ? (1 << 2) : 0)+
    	                        (type != null ? (1 << 3) : 0)+
    	                        (propertyMap != null && !propertyMap.isEmpty() ? (1 << 4) : 0));
    	out.writeByte(lvl2Flags);
    	if (correlId != null)
    		out.writeUTF(correlId);
    	if (replyTo != null)
    		DestinationSerializer.serializeTo(replyTo, out);
    	if (timestamp != 0)
    		out.writeLong(timestamp);
    	if (type != null)
    		out.writeUTF(type);
    	if (propertyMap != null && !propertyMap.isEmpty())
    		writeMapTo(propertyMap, out);
        
        // Level 3 - Body - Only unserialized on the client side
        serializeBodyTo(out);
    }
1234131
async def _send_chunk(self, chunk):
        
        self.__log_debug('> %s', chunk)
        await self.__transport._send_data(serialize_packet(
            self._local_port,
            self._remote_port,
            self._remote_verification_tag,
            chunk))
1129162
private void handlePacket(SelectableChannel channel, IncomingPacket incomingPacket) {
    String typeName = incomingPacket.unpackString();
    REQID rid = incomingPacket.unpackREQID();
    Message.Builder bldr = requestMap.get(typeName);
    boolean isRequest = false;
    if (bldr != null) {
      // This is a request
      isRequest = true;
    } else {
      bldr = messageMap.get(typeName);
    }
    if (bldr != null) {
      // Clear the earlier state of Message.Builder
      // Otherwise it would merge new Message with old state
      bldr.clear();

      incomingPacket.unpackMessage(bldr);
      if (bldr.isInitialized()) {
        Message msg = bldr.build();
        if (isRequest) {
          onRequest(rid, (SocketChannel) channel, msg);
        } else {
          onMessage((SocketChannel) channel, msg);
        }
      } else {
        // Message failed to be deser
        LOG.severe("Could not deserialize protobuf of type " + typeName);
        handleError(channel);
      }
      return;
    } else {
      LOG.severe("Unexpected protobuf type received " + typeName);
      handleError(channel);
    }
  }
312392
public void startPacket()
        throws IOException
    {
        if (_refs != null) {
            _refs.clear();
            _refCount = 0;
        }

        flushBuffer();

        _isPacket = true;
        _offset = 4;
        _buffer[0] = (byte) 0x05; // 0x05 = binary
        _buffer[1] = (byte) 0x55;
        _buffer[2] = (byte) 0x55;
        _buffer[3] = (byte) 0x55;
    }
72906
def _write(self, data):
        
        frame = APIFrame(data, self._escaped).output()
        self.serial.write(frame)
46587
public void processPacketAESCM(RawPacket pkt) {
		long ssrc = pkt.getSSRC();
		int seqNo = pkt.getSequenceNumber();
		long index = ((long) this.roc << 16) | seqNo;

		ivStore[0] = saltKey[0];
		ivStore[1] = saltKey[1];
		ivStore[2] = saltKey[2];
		ivStore[3] = saltKey[3];

		int i;
		for (i = 4; i < 8; i++) {
			ivStore[i] = (byte) ((0xFF & (ssrc >> ((7 - i) * 8))) ^ this.saltKey[i]);
		}

		for (i = 8; i < 14; i++) {
			ivStore[i] = (byte) ((0xFF & (byte) (index >> ((13 - i) * 8))) ^ this.saltKey[i]);
		}

		ivStore[14] = ivStore[15] = 0;

		final int payloadOffset = pkt.getHeaderLength();
		final int payloadLength = pkt.getPayloadLength();

		cipherCtr.process(cipher, pkt.getBuffer(), payloadOffset, payloadLength, ivStore);
	}
1263942
static RawPacket nextPacket(final InputStream is) throws IOException {
        byte[] lengthBuffer = readLengthSeq(is);
        int length = (lengthBuffer[0] & 0xff) + ((lengthBuffer[1] & 0xff) << 8) + ((lengthBuffer[2] & 0xff) << 16);
        if (length == -1) {
            return null;
        }

        if (length < 0) {
            throw new IOException("Got negative packet size: " + length);
        }

        final int packetSeq = lengthBuffer[3];

        final byte[] rawBytes = new byte[length];

        final int nr = ReadUtil.safeRead(is, rawBytes);
        if (nr != length) {
            throw new IOException("EOF. Expected " + length + ", got " + nr);
        }

        return new RawPacket(ByteBuffer.wrap(rawBytes).order(ByteOrder.LITTLE_ENDIAN),
                             packetSeq);
    }
917264
public static ResultPacket createResultPacket(final RawPacket rawPacket) throws IOException {
        byte b = rawPacket.getByteBuffer().get(0);
        switch (b) {

            case ERROR:
                return new ErrorPacket(rawPacket);
            case OK:
                return new OKPacket(rawPacket);
            case EOF:
                return new EOFPacket(rawPacket);
            default:
                return new ResultSetPacket(rawPacket);
        }
    }
924231
def add_data(self, rawdata):
        """"""

        for data in rawdata:
            try:
                item = data[0]
                if item[0] == 2:
                    # Flush messages but we got nothing to flush
                    continue
                if item[0] != 0:
                    warnings.warn(f"Unknown message type '{item[0]}'", Warning)
                    continue
                item = item[1]
                # convert target to string because error codes are ints
                target = str(item[0])
                try:
                    data = item[1]
                except IndexError:
                    data = dict()
                try:
                    method = getattr(self, self.__head + target)
                    method(data)
                except AttributeError:
                    self._handle_unhandled(target, data)
            except IndexError:
                LOGGER.warning("Wrongly constructed message received: %r", data)

        self.conn.process_queues()
502589
public static void dump(DataSet data, PrintStream out) {
    try (Log log = Log.create(out)) {
      log.write(CallInfo.create(), data);
    }
  }
1326580
public List<RawPacket> startBinlogDump(final int position, final String logfile) throws SQLException {
        try {
            return this.protocol.startBinlogDump(position, logfile);
        } catch (BinlogDumpException e) {
            throw SQLExceptionMapper.getSQLException("Could not dump binlog", e);
        }
    }