fromPacket static method
fromPacket creates a TePacket from a string packet in the format of Layrz Protocol v3.
Implementation
static TePacket fromPacket(String raw) {
if (!raw.startsWith('<Te>') || !raw.endsWith('</Te>')) {
throw ParseException('Invalid identification packet, should be <Te>...</Te>');
}
final parts = raw.substring(4, raw.length - 5).split(';');
if (parts.length != 6) {
throw MalformedException('Invalid packet parts, should have 6 parts');
}
int? receivedCrc = int.tryParse(parts.last, radix: 16);
int? calculatedCrc = calculateCrc("${parts.sublist(0, 5).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');
}
double distanceTraveled;
try {
distanceTraveled = double.parse(parts[2]);
} catch (e) {
throw MalformedException('Invalid distance traveled ${parts[2]}');
}
double maxSpeed;
try {
maxSpeed = double.parse(parts[3]);
} catch (e) {
throw MalformedException('Invalid max speed');
}
Duration duration;
try {
duration = Duration(seconds: int.parse(parts[4]));
} catch (e) {
throw MalformedException('Invalid duration');
}
return TePacket(
timestamp: timestamp,
distanceTraveled: distanceTraveled,
maxSpeed: maxSpeed,
duration: duration,
tripId: parts[1],
);
}