fromPacket static method

PdPacket fromPacket(
  1. String raw
)
override

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

Implementation

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

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

  int? receivedCrc = int.tryParse(parts[9], radix: 16);
  int? calculatedCrc = calculateCrc("${parts.sublist(0, 9).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');
  }

  final position = Position(
    latitude: double.tryParse(parts[1]),
    longitude: double.tryParse(parts[2]),
    altitude: double.tryParse(parts[3]),
    speed: double.tryParse(parts[4]),
    direction: double.tryParse(parts[5]),
    satellites: int.tryParse(parts[6]),
    hdop: double.tryParse(parts[7]),
  );

  return PdPacket(
    timestamp: timestamp,
    position: position,
    extra: Packet.parseExtraArgs(parts[8]),
  );
}