fromPacket static method

PmPacket fromPacket(
  1. String raw
)
override

fromPacket creates a PmPacket from a string packet in the format of Layrz Protocol v3.

Implementation

static PmPacket fromPacket(String raw) {
  if (!raw.startsWith('<Pm>') || !raw.endsWith('</Pm>')) {
    throw ParseException('Invalid identification packet, should be <Pm>...</Pm>');
  }

  final parts = raw.substring(4, raw.length - 5).split(';');
  if (parts.length != 4) {
    throw MalformedException('Invalid packet parts, should have 4 parts');
  }

  int? receivedCrc = int.tryParse(parts[3], radix: 16);
  int? calculatedCrc = calculateCrc("${parts.sublist(0, parts.length - 1).join(';')};".codeUnits);

  if (receivedCrc != calculatedCrc) {
    throw CrcException('Invalid CRC, received: $receivedCrc, calculated: $calculatedCrc');
  }

  String filename = parts[0];
  String contentType = parts[1];
  Uint8List data;
  try {
    data = base64Decode(parts[2]);
  } catch (e) {
    throw ParseException('Invalid base64 data');
  }

  return PmPacket(
    filename: filename,
    contentType: contentType,
    data: data,
  );
}