fromPacket static method
fromPacket creates a TsPacket from a string packet in the format of Layrz Protocol v3.
Implementation
static TsPacket fromPacket(String raw) {
if (!raw.startsWith('<Ts>') || !raw.endsWith('</Ts>')) {
throw ParseException('Invalid identification packet, should be <Ts>...</Ts>');
}
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 TsPacket(
timestamp: timestamp,
tripId: parts[1],
);
}