NMEA { static boolean validate(@NonNull String nmea) { final int starIndex = nmea.lastIndexOf('*'); final int length = nmea.length(); if (length < 8 || nmea.charAt(0) != '$' || starIndex != length - 3) { Log.e(TAG, "Invalid NMEA sentence: " + nmea); return false; } if (nmea.startsWith("$AIDSTAT") && nmea.endsWith("*00")) return false; if (nmea.startsWith("$ENGINESTATE") && nmea.endsWith("*00")) return false; 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; }    }
@Test public void nmeaValidate() { assertTrue(validate("$GPATT,45.781233,10.862333,1796.3,45.0,2.6,2.6,*72")); assertFalse(validate("$GPATT,45.781233,10.862333,1796.3,45.0,2.6,2.6,*71")); assertFalse(validate("GPATT,45.781233,10.862333,1796.3,45.0,2.6,2.6,*72")); assertFalse(validate("$GPATT,***")); assertFalse(validate("$GPATT*")); assertFalse(validate("$AIDSTAT,1,2,3*00")); }
@Test public void nmeaChecksum() { assertTrue(validate("$GPATT,45.781233,10.862333,1796.3,45.0,2.6,2.6,*72")); assertFalse(validate("$GPATT,45.781233,10.862333,1796.3,45.0,2.6,2.6,*99")); }