fromPacket static method
fromPacket creates a PcPacket from a string packet in the format of Layrz Protocol v3.
Implementation
static PcPacket fromPacket(String raw) {
if (!raw.startsWith('<Pc>') || !raw.endsWith('</Pc>')) {
throw ParseException('Invalid identification packet, should be <Pc>...</Pc>');
}
final parts = raw.substring(4, raw.length - 5).split(';');
if (parts.length != 4) {
throw MalformedException('Invalid packet parts, should have 4 parts');
}
int? receivedCrc = int.tryParse(parts[3], radix: 16);
int? calculatedCrc = calculateCrc("${parts.sublist(0, 3).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');
}
int commandId;
try {
commandId = int.parse(parts[1]);
} catch (e) {
throw MalformedException('Invalid command_id, should be an int');
}
return PcPacket(
timestamp: timestamp,
commandId: commandId,
message: parts[2],
);
}