class NMEA {

    static boolean validate(@NonNull String nmea) {
        final int starIndex = nmea.lastIndexOf('*');
        final int length = nmea.length();
        // Ensure that:
        // - string is long enough
        // - starts with $
        // - ends with checksum
        // Could use regex ^\\$.*\\*[0-9a-fA-F]{2} but this is faster:
        if (length < 8 || nmea.charAt(0) != '$' || starIndex != length - 3) {
            Log.e(TAG, "Invalid NMEA sentence: " + nmea);
            return false;
        }
        // Special commands that don't checksum
        if (nmea.startsWith("$AIDSTAT") && nmea.endsWith("*00")) return false;
        if (nmea.startsWith("$ENGINESTATE") && nmea.endsWith("*00")) return false;

        // Compute checksum
        short checksum1 = 0;
        for (int i = 1; i < starIndex; i++) {
            checksum1 ^= nmea.charAt(i);
        }
        final short checksum2 = Short.parseShort(nmea.substring(starIndex + 1), 16);
        if (checksum1 != checksum2) {
            Log.e(TAG, String.format(Locale.US, "Invalid NMEA checksum: %02X != %02X for sentence: %s", checksum1, checksum2, nmea));
            return false;
        }
        return true;
    }

}