fromPacket static method

AoPacket fromPacket(
  1. String raw
)
override

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

Implementation

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

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

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

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

  int? seconds = int.tryParse(parts[0]);
  if (seconds == null) {
    throw MalformedException('Invalid timestamp, should be an integer');
  }
  return AoPacket(timestamp: DateTime.fromMillisecondsSinceEpoch(seconds * 1000, isUtc: true));
}