fromPacket static method

PsPacket fromPacket(
  1. String raw
)
override

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

Implementation

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

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

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

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

  DateTime timestamp;
  try {
    timestamp = DateTime.fromMillisecondsSinceEpoch(int.parse(parts[0]) * 1000, isUtc: true);
  } catch (e) {
    throw MalformedException('Invalid timestamp');
  }

  return PsPacket(
    timestamp: timestamp,
    params: Packet.parseExtraArgs(parts[1]),
  );
}