refactor: centralize raw frame identity derivation

This commit is contained in:
lingniu
2026-07-01 18:12:04 +08:00
parent c8abc721e1
commit f89ac1c23f
4 changed files with 92 additions and 42 deletions

View File

@@ -0,0 +1,43 @@
package com.lingniu.ingest.facts;
import com.lingniu.ingest.api.ProtocolId;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.HexFormat;
public record RawFrameIdentity(
String checksum,
String vehicleKey,
String frameId
) {
public RawFrameIdentity {
checksum = checksum == null ? "" : checksum;
vehicleKey = vehicleKey == null ? "" : vehicleKey;
frameId = frameId == null ? "" : frameId;
}
public static RawFrameIdentity derive(ProtocolId protocol,
String vin,
String phone,
String rawIdentitySeed,
int messageId,
int subType,
Instant receivedAt,
byte[] rawBytes) {
String checksum = "sha256:" + sha256(rawBytes);
String vehicleKey = VehicleKey.derive(protocol, vin, phone, rawIdentitySeed);
String frameId = FactIds.rawFrameId(protocol, vehicleKey, messageId, subType, receivedAt, checksum);
return new RawFrameIdentity(checksum, vehicleKey, frameId);
}
private static String sha256(byte[] value) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return HexFormat.of().formatHex(digest.digest(value == null ? new byte[0] : value));
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-256 is unavailable", e);
}
}
}

View File

@@ -0,0 +1,36 @@
package com.lingniu.ingest.facts;
import com.lingniu.ingest.api.ProtocolId;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import static org.assertj.core.api.Assertions.assertThat;
class RawFrameIdentityTest {
@Test
void derivesChecksumVehicleKeyAndFrameIdTogether() {
RawFrameIdentity identity = RawFrameIdentity.derive(
ProtocolId.JT808,
"",
"13307795425",
"1782900000000000",
0x0200,
0,
Instant.parse("2026-07-01T10:00:00Z"),
new byte[]{0x7e, 0x02, 0x00, 0x7e});
assertThat(identity.checksum()).startsWith("sha256:");
assertThat(identity.vehicleKey()).isEqualTo("jt808:13307795425");
assertThat(identity.frameId())
.isEqualTo(FactIds.rawFrameId(
ProtocolId.JT808,
"jt808:13307795425",
0x0200,
0,
Instant.parse("2026-07-01T10:00:00Z"),
identity.checksum()))
.startsWith("rf_");
}
}