Decode your first native packet
Open your installed SDK directory or extract the portable native ZIP. Run the archive-root commands below from that directory. Keep lib/, examples/, and example.klv together. Start with no token set. For a web application, follow the browser and Node.js quickstart.
Select a language below. The C#, Go, Java, and Python commands use the Windows filename misb0601.dll. On Linux use misb0601.so. On macOS use misb0601.dylib.
- C
- C++
- C#
- Go
- Java
- Python
From the extracted archive root, use the command pair for your platform. Putting the executable beside the library lets it find the runtime.
# Windows x64 (MinGW)
gcc -Iinclude examples/c/example.c lib/misb0601.dll -o lib/read.exe
./lib/read.exe example.klv
# Linux x64
cc -Iinclude examples/c/example.c lib/misb0601.so -Wl,-rpath,'$ORIGIN' -o lib/read
./lib/read example.klv
# macOS arm64
cc -Iinclude examples/c/example.c lib/misb0601.dylib -Wl,-rpath,@loader_path -o lib/read
./lib/read example.klv
#include <stdio.h>
#include <stdlib.h>
#include "misb0601.h"
#include "roundtrip.h"
#include "fields.h"
#include "stream.h"
#include <string.h>
int main(int argc, char **argv) {
if (argc < 2) return 1;
FILE *file = fopen(argv[1], "rb");
if (!file) return 1;
uint8_t packet[65536];
size_t size = fread(packet, 1, sizeof(packet), file);
int complete = fgetc(file) == EOF && !ferror(file);
fclose(file);
if (!complete) return 1;
misb0601_license_status license = {0};
Misb0601LicenseInitialize(getenv("LIBMISB_NATIVE_TOKEN"), &license);
puts(license.is_decoder_demo ? "demo" : "licensed");
misb0601_buffer json = {0};
int status = Misb0601DecodeJSON(packet, size, MISB0601_SORT_BY_TAG, MISB0601_JSON_KEYS_TAGS,
MISB0601_JSON_COMPACT, MISB0601_TIMESTAMPS_RAW, &json);
if (json.len) fwrite(json.data, 1, json.len, stdout);
putchar('\n');
Misb0601BufferFree(&json);
if (argc == 3 && strcmp(argv[2], "--fields") == 0) read_fields(packet, size);
int extra_ok = argc < 3 || strcmp(argv[2], "--roundtrip") != 0 || roundtrip();
if (argc == 3 && strcmp(argv[2], "--stream") == 0) extra_ok = stream_packet(packet, size);
Misb0601LicenseShutdown();
return !extra_ok || (status != MISB0601_STATUS_OK && status != MISB0601_STATUS_PARTIAL);
}
From the archive root, use a C++17 compiler and the command pair for your platform.
# Windows x64 (MinGW)
g++ -std=c++17 -Iinclude examples/cpp/example.cpp lib/misb0601.dll -o lib/read.exe
./lib/read.exe lib/misb0601.dll example.klv
# Linux x64
c++ -std=c++17 -Iinclude examples/cpp/example.cpp lib/misb0601.so -ldl -Wl,-rpath,'$ORIGIN' -o lib/read
./lib/read ./lib/misb0601.so example.klv
# macOS arm64
c++ -std=c++17 -Iinclude examples/cpp/example.cpp lib/misb0601.dylib -Wl,-rpath,@loader_path -o lib/read
./lib/read ./lib/misb0601.dylib example.klv
#include "misb0601.hpp"
#include "roundtrip.hpp"
#include "fields.hpp"
#include "../c/stream.h"
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>
int main(int argc, char **argv) {
if (argc < 3) return 1;
misb0601::Library lib(argv[1]);
auto token = std::getenv("LIBMISB_NATIVE_TOKEN");
auto license = lib.ValidateLicense(token ? token : "");
std::cout << (license.isDecoderDemo ? "demo" : "licensed") << '\n';
std::ifstream file(argv[2], std::ios::binary);
if (!file) return 1;
std::vector<uint8_t> packet{std::istreambuf_iterator<char>(file), {}};
misb0601::DecoderOptions options;
options.timestampMode = MISB0601_TIMESTAMPS_RAW;
std::cout << lib.DecodeJson(packet.data(), packet.size(), options).ReadString() << '\n';
if (argc == 4 && std::string(argv[3]) == "--fields") read_fields(lib, packet);
if (argc == 4 && std::string(argv[3]) == "--roundtrip") roundtrip(lib, options);
bool ok = argc != 4 || std::string(argv[3]) != "--stream" || stream_packet(packet.data(), packet.size());
lib.ShutdownLicense();
return ok ? 0 : 1;
}
Install the .NET 8 SDK. From the archive root, restore the example using the supplied NuGet package.
cd examples/csharp
dotnet restore --source ../../nuget
dotnet run --no-restore -- ../../lib/misb0601.dll ../../example.klv
using LibMisb.Misb0601;
if (args.Length < 2) throw new ArgumentException("Supply the library and packet paths.");
using var library = Misb0601Library.Load(args[0]);
var status = library.ValidateLicense(Environment.GetEnvironmentVariable("LIBMISB_NATIVE_TOKEN") ?? "");
try
{
Console.WriteLine(status.IsDecoderDemo ? "demo" : "licensed");
var decoder = library.CreateDecoder(new Misb0601DecoderOptions(TimestampMode: Misb0601TimestampMode.Raw));
var packet = File.ReadAllBytes(args[1]);
using var result = decoder.DecodeJson(packet);
Console.WriteLine(result.ReadUtf8());
if (args.Contains("--stream")) PacketStream.Run(args[0], packet);
if (args.Contains("--fields")) Fields.Read(decoder, packet);
if (args.Contains("--roundtrip")) RoundTrip.Run(library, decoder);
}
finally
{
library.ShutdownLicense();
}
Use Go 1.22 or later with cgo enabled and a C compiler on your PATH. The example's go.mod already points at the standalone module in the archive.
cd examples/go
go run . ../../lib/misb0601.dll ../../example.klv
For your own application, require github.com/impleotv/libmisb-sdk-go v0.0.0 and add a local replace directive pointing at the extracted go/ directory.
package main
import (
"fmt"
sdk "github.com/impleotv/libmisb-sdk-go/misb0601abi"
"os"
)
func main() {
if len(os.Args) < 3 {
panic("supply library and packet paths")
}
lib, err := sdk.Load(os.Args[1])
must(err)
defer lib.Close()
status, err := lib.ValidateLicense(os.Getenv("LIBMISB_NATIVE_TOKEN"))
must(err)
defer lib.ShutdownLicense()
if status.IsDecoderDemo {
fmt.Println("demo")
} else {
fmt.Println("licensed")
}
options := sdk.DefaultDecoderOptions()
options.TimestampMode = sdk.TimestampsRaw
decoder := lib.CreateDecoder(options)
packet, err := os.ReadFile(os.Args[2])
must(err)
fields, err := decoder.DecodeJSON(packet)
must(err)
fmt.Println(string(fields))
if len(os.Args) == 4 && os.Args[3] == "--fields" {
readFields(decoder, packet)
}
if len(os.Args) == 4 && os.Args[3] == "--stream" {
streamPacket(decoder, packet)
}
if len(os.Args) == 4 && os.Args[3] == "--roundtrip" {
roundtrip(lib, decoder)
}
}
func must(err error) {
if err != nil {
panic(err)
}
}
Use a 64-bit JDK 22 or later. From the archive root, run the source file directly. The two arguments select the shared library and the binary ST 0601 packet.
java --enable-native-access=ALL-UNNAMED examples/java/DecodePacket.java lib/misb0601.dll example.klv
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemoryLayout;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.SymbolLookup;
import java.lang.invoke.MethodHandle;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import static java.lang.foreign.MemoryLayout.PathElement.groupElement;
import static java.lang.foreign.ValueLayout.*;
/** Decodes one binary ST 0601 packet using the 64-bit misb0601.h ABI. */
public class DecodePacket {
private static final int OK = 0, PARTIAL = 3;
private static final MemoryLayout BUFFER = MemoryLayout.structLayout(
ADDRESS.withName("data"), JAVA_LONG.withName("len"), JAVA_LONG.withName("capacity"));
private static final MemoryLayout LICENSE = MemoryLayout.structLayout(
JAVA_INT.withName("initialized"), JAVA_INT.withName("mode"), JAVA_INT.withName("is_decoder_demo"),
JAVA_INT.withName("is_encoder_demo"), JAVA_INT.withName("is_validate_demo"),
JAVA_INT.withName("max_decoders"), JAVA_INT.withName("max_encoders"), JAVA_INT.withName("max_validators"));
private final SymbolLookup library;
private final MethodHandle lastError;
private final MethodHandle free;
private DecodePacket(Path path) {
// Keep the loaded runtime resident for the life of this process.
library = SymbolLookup.libraryLookup(path.toAbsolutePath(), Arena.global());
lastError = bind("Misb0601LastErrorMessage", FunctionDescriptor.of(JAVA_INT, ADDRESS));
free = bind("Misb0601BufferFree", FunctionDescriptor.ofVoid(ADDRESS));
}
private MethodHandle bind(String name, FunctionDescriptor signature) {
return Linker.nativeLinker().downcallHandle(library.find(name).orElseThrow(
() -> new UnsatisfiedLinkError(name)), signature);
}
private static String text(MemorySegment buffer) {
long length = buffer.get(JAVA_LONG, BUFFER.byteOffset(groupElement("len")));
if (length == 0) return "";
MemorySegment data = buffer.get(ADDRESS, BUFFER.byteOffset(groupElement("data")));
return new String(data.reinterpret(length).toArray(JAVA_BYTE), StandardCharsets.UTF_8);
}
private String diagnostic(Arena arena, int status) throws Throwable {
MemorySegment message = arena.allocate(BUFFER);
try {
int result = (int) lastError.invokeExact(message);
return "ST 0601 status " + status + (result == OK ? ": " + text(message) : "");
} finally {
free.invokeExact(message);
}
}
private void run(byte[] packet, Arena arena) throws Throwable {
MethodHandle initialize = bind("Misb0601LicenseInitialize", FunctionDescriptor.of(JAVA_INT, ADDRESS, ADDRESS));
MethodHandle shutdown = bind("Misb0601LicenseShutdown", FunctionDescriptor.of(JAVA_INT));
MethodHandle decode = bind("Misb0601DecodeJSON", FunctionDescriptor.of(
JAVA_INT, ADDRESS, JAVA_LONG, JAVA_INT, JAVA_INT, JAVA_INT, JAVA_INT, ADDRESS));
String token = System.getenv("LIBMISB_NATIVE_TOKEN");
MemorySegment license = arena.allocate(LICENSE);
MemorySegment tokenText = token == null ? MemorySegment.NULL : arena.allocateFrom(token);
int status = (int) initialize.invokeExact(tokenText, license);
if (status != OK && status != PARTIAL) throw new IllegalStateException(diagnostic(arena, status));
try {
boolean demo = license.get(JAVA_INT, LICENSE.byteOffset(groupElement("is_decoder_demo"))) != 0;
System.out.println(demo ? "demo" : "licensed");
MemorySegment input = arena.allocateFrom(JAVA_BYTE, packet);
MemorySegment json = arena.allocate(BUFFER);
try {
// Sort by tag, use numeric tag keys, compact JSON and raw integer timestamps.
status = (int) decode.invokeExact(input, input.byteSize(), 1, 1, 0, 0, json);
if (status == PARTIAL) System.err.println(diagnostic(arena, status));
else if (status != OK) throw new IllegalArgumentException(diagnostic(arena, status));
System.out.println(text(json));
} finally {
free.invokeExact(json);
}
} finally {
int shutdownStatus = (int) shutdown.invokeExact();
if (shutdownStatus != OK) throw new IllegalStateException(diagnostic(arena, shutdownStatus));
}
}
public static void main(String[] args) throws Throwable {
if (args.length != 2) throw new IllegalArgumentException("Usage: DecodePacket <library> <packet.klv>");
if (ADDRESS.byteSize() != 8) throw new IllegalStateException("A 64-bit JDK is required");
byte[] packet = Files.readAllBytes(Path.of(args[1]));
try (Arena arena = Arena.ofConfined()) {
new DecodePacket(Path.of(args[0])).run(packet, arena);
}
}
}
Use Python 3.10 or later. In your virtual environment, run these commands from the archive root.
python -m pip install --no-index --find-links python libmisb-misb0601
python examples/python/example.py lib/misb0601.dll example.klv
import json
import os
import sys
from pathlib import Path
from misb0601 import Misb0601DecoderOptions, Misb0601Library, Misb0601TimestampMode
from fields import read_fields
from roundtrip import roundtrip
from stream import stream_packet
library = Misb0601Library(sys.argv[1])
status = library.validate_license(os.getenv("LIBMISB_NATIVE_TOKEN", ""))
try:
print("demo" if status.is_decoder_demo else "licensed")
options = Misb0601DecoderOptions(timestamp_mode=Misb0601TimestampMode.RAW)
decoder = library.create_decoder(options)
packet = Path(sys.argv[2]).read_bytes()
fields = json.loads(decoder.decode_json(packet))
print(json.dumps(fields))
if "--stream" in sys.argv[3:]:
stream_packet(sys.argv[1], packet)
if "--fields" in sys.argv[3:]:
read_fields(decoder, packet)
if "--roundtrip" in sys.argv[3:]:
roundtrip(library, decoder)
finally:
library.shutdown_license()
Recognize the result
The first line is demo. The next line contains these fields (key order and whitespace may vary):
{"1":23503,"2":9007199254740993,"65":19}
Tag 65 identifies revision 19. Tag 2 is a timestamp in microseconds. Tag 1 is the checksum. Continue to reading fields or encoding and validation.