IMD SolutionComputing LibraryShop main store

Troubleshooting

Decoding hex float32 MQTT payloads in Telegraf

Edge computing and IIoT Published 7 min read By IMD Solution engineering team

Short answer

The JSON parser stores the vs field as text because that is what the config asks for; no parser option decodes bytes. Strip the one-byte device ID, decode the remaining eight hex characters as a little-endian DCBA float32, and run the conversion at ingestion in a Starlark or execd processor so InfluxDB receives a real number.

On this page
  1. Why does Telegraf store the MQTT hex payload as a string?
  2. How many characters is the device ID prefix?
  3. Which byte order does the float32 decode use?
  4. Where should the conversion run: Telegraf or Flux?
  5. Can the converter processor decode the hex string instead?
  6. What does a working decoder look like?
  7. How do you validate the stored value end to end?
  8. What else goes wrong when the field stays text?
  9. Questions asked

Your Telegraf pipeline is not dropping the data; it is finishing early. data_format = "json" with json_string_fields = ["vs"] delivers the payload field as text and hands it to the output unchanged, so InfluxDB stores hex characters where you wanted a number. The fix is a decode step: strip the first two characters, the one-byte device ID, then read the remaining eight hex characters as an IEEE 754 float32 in little-endian DCBA order, which turns 01864e2440 into approximately 2.5672927. Run that step at ingestion in a Starlark or execd processor, and the database finally gets a number.

Why does Telegraf store the MQTT hex payload as a string? #

The parser is doing exactly what the config asks: data_format = "json" with json_string_fields = ["vs"] tells Telegraf to deliver the vs field as text, and no later stage in that pipeline converts bytes, so the hex characters reach InfluxDB unchanged.

The record in question looks like this:

[
  {"bn": "urn:dev:DEVEUI:000000C00001B08A7:", "bt": 1.614612404E9},
  {"n": "payload", "vs": "01864e2440"},
  {"n": "port", "v": 2.0}
]

That shape is SenML, and RFC 8428 defines vs as a string value, so storing text is correct parser behavior; no parser option will decode it for you. Trace where the type is set:

  • The device publishes the JSON record to the broker.
  • The broker forwards it byte for byte; MQTT transport never changes a type.
  • The [[inputs.mqtt_consumer]] JSON parser reads vs, and json_string_fields pins it as a string field.
  • The output plugin writes that string into the measurement.

Notice that port arrives through v as the number 2.0 with no help needed; only vs requires work. If the value instead lands under an unexpected field or measurement name, that is a mapping problem rather than a typing problem, and Turn an MQTT topic into InfluxDB fields with Telegraf covers that layer.

How many characters is the device ID prefix? #

Two hexadecimal characters are one byte, and this device format spends the first byte on the device ID, so strip exactly the first two characters and leave the remaining eight untouched as the four float bytes.

Count characters, not bytes, when you cut. The full sample 01864e2440 is ten characters: two for the ID byte 01, then eight for the float. Cutting four characters instead, the misreading of minus the first two bytes, would delete half of the float and produce a confidently wrong number. Check the length before you decode:

Characters observed What it means Action
Ten, like 01864e2440 one ID byte plus four payload bytes strip two, decode the remaining eight
Eight payload only, with the ID carried elsewhere, for example in the topic or the SenML base name decode all of it
Anything else prefix width or payload layout differs from this format stop and confirm the payload definition first

The decision: strip two characters, verify eight remain, and treat any other length as an unconfirmed format.

Which byte order does the float32 decode use? #

Little-endian DCBA: the stripped string's first pair of hex characters is the float's least significant byte and the last pair carries the sign bit and the high exponent bits, which decodes 864e2440 to approximately 2.5672927.

Byte order belongs to the device payload definition; neither MQTT nor JSON has an opinion about it. Full arithmetic for the sample, stripped to 864e2440:

  1. Bytes in string order: 86 4e 24 40. Little-endian makes 86 the least significant byte, so the float's bit pattern is 0x40244e86.
  2. In binary: 0100 0000 0010 0100 0100 1110 1000 0110.
  3. Sign bit 0, so the value is positive. Exponent bits 1000 0000 = 128, unbiased: 128 - 127 = 1.
  4. Mantissa bits 010 0100 0100 1110 1000 0110 = 2379398, as a fraction 2379398 / 8388608 = 0.28365.
  5. Value = (1 + 0.28365) × 2^1 = 2.5672927, matching the "float - little endian (DCBA)" converter output the device side quotes.

Reading the same bytes big-endian instead yields about -4e-35: a tiny, plausible-looking number rather than an error, which is exactly why a known-value check matters. Confirm the order from the device payload documentation or by transmitting a value you know and comparing.

Where should the conversion run: Telegraf or Flux? #

Convert at ingestion, inside Telegraf: a processors.starlark or processors.execd stage stores a true number in InfluxDB, while the reporter's review of the Flux 0.x reference found no hex or binary conversion, so strings.substring() alone cannot finish the job.

Where What it can do with this payload Decision
processors.starlark strips and decodes inside the Telegraf process; a numeric field is stored first choice
processors.execd or inputs.execd same job through a helper process in any language use when the logic already exists, for example in Python
Flux at query time strings.substring() cuts the prefix but leaves text; the reported Flux 0.x review found no binary or hex conversion do not rely on it for the decode
Raw string only preserves the incoming hex text keep as an extra field for traceability, never as the only copy

Scope note: the Flux finding is one engineer's review of the Flux 0.x standard library, not a measured limit of every later release. If your deployed release documents a byte-level conversion, test it on the known sample; otherwise convert at ingestion, where every consumer of the data benefits.

Can the converter processor decode the hex string instead? #

Probably not out of the box: the converter processor is documented for type casts and for moving values between fields, tags and timestamps, while this payload needs a byte-level decode, so treat any binary-float option your release documents as unproven until the worked sample passes.

The converter plugin's documentation covers transforming tags into fields or timestamps and converting fields into tags or timestamps: type-level work. A public Telegraf issue asking for a base64-encoded IEEE 754 float32 decoder was pointed at the converter's field-conversion list, which tells you two things at once: binary decode is a converter-shaped job, and what your build actually supports depends on the release. A hex string with a leading ID byte is not a plain decimal-to-float cast, so before writing any script, check the converter page for your exact Telegraf version; if it documents a binary float32 decode with byte order, run it against the known sample and keep the scripted path below as the fallback whenever that test fails.

What does a working decoder look like? #

Two moves cover it: cut the first two characters, then rebuild sign, exponent and mantissa from the four bytes with the arithmetic in the previous section; the Python version below is the reference, and the Starlark version is what runs in the processor.

Reference decode in Python:

from struct import unpack

def decode_vs(vs):
    # vs: full string, e.g. "01864e2440" - one ID byte then four payload bytes
    payload = bytes.fromhex(vs[2:])
    if len(payload) != 4:
        raise ValueError("expected one ID byte and four payload bytes")
    return unpack("<f", payload)[0]

print(decode_vs("01864e2440"))  # 2.5672927

And the same arithmetic as a Starlark function for processors.starlark:

# decode.star - IEEE 754 float32 from the hex payload, little-endian (DCBA)
# math.pow needs the math module; import it the way the Starlark processor examples show

def decode_float32(hex_text):
    # hex_text: string of exactly 8 hex characters, device ID already stripped
    d4 = int(hex_text[0:2], 16)  # least significant byte
    d3 = int(hex_text[2:4], 16)
    d2 = int(hex_text[4:6], 16)
    d1 = int(hex_text[6:8], 16)  # most significant byte, holds the sign
    if d1 >= 128:
        sign = -1
    else:
        sign = 1
    exp = (d1 << 1) + (d2 >> 7) - 127
    mant = ((d2 & 127) * 65536 + d3 * 256 + d4) / 8388608
    return sign * (1 + mant) * math.pow(2, exp)

print(decode_float32("864e2440"))  # must match the Python result

Wiring is the same shape either way: point the processor at the script, and in the per-metric function the processor calls (its README documents the exact signature), read the vs field, cut the first two characters, run the length guard, decode, and write the number back to the same field. Copy the original text into a second field, vs_raw say, as an example name, before you overwrite it, and skip or flag any message whose remainder has the wrong length instead of writing a decoded guess.

How do you validate the stored value end to end? #

Prove the pipeline with a known nonzero payload and a type check in the database: decode the sample, compare against the independent Python result, then confirm the stored field is numeric rather than a quoted string.

  1. Capture one raw message and keep the exact vs text unchanged for comparison.
  2. Strip the ID and run the length guard before any decode.
  3. Decode the stripped payload with both the Python reference and the processor; the two results must agree.
  4. Use a payload whose true value you know from the device itself, not a zero-filled test message.
  5. Write to a test measurement first, query it, and confirm the field type is numeric, not text.
  6. Only then point the processor at the production measurement.

When the decoded value feeds an alarm or anything that drives the process, cross-check the first decoded readings against the device's own display or register read before you trust the chain: the decode is bit-exact, but it reproduces a wrong byte order just as faithfully.

What else goes wrong when the field stays text? #

String-typed data silently disables every numeric feature downstream: InfluxDB excludes string fields from aggregations such as mean and median, dashboards show text instead of trends, and alert rules cannot threshold a value they cannot do arithmetic on.

The decode is therefore not cosmetic; it decides whether the payload is usable at all. While you tune the processor, the same string-typing root cause appears from the other direction in Why Telegraf writes MQTT float values into the string measurement, which helps if other numeric fields are landing as text too.

The decisions, per case: strip exactly two characters; decode the remaining payload as little-endian DCBA float32; convert at ingestion in a Starlark or execd processor rather than in a query; accept the built-in converter only after it passes the known-sample test; and keep the raw hex field only as long as you need packet-level traceability.

Questions asked

What do the other fields in the SenML record mean?

The record shape is SenML, defined in RFC 8428: bn is the base name, here a device URN; bt is the base time in epoch seconds; n names each item; v carries a plain number, which is why port arrives as 2.0 without conversion; vs is the string value, the only field in this payload that needs a decode.

What does a second sample payload, 0181261a42, decode to?

Strip the device ID to get 81261a42. The sign bit is 0, the exponent bits give 132 - 127 = 5, and the mantissa is 1713793 divided by 8388608, about 0.2043, so the value is (1 + 0.2043) × 32, approximately 38.5376. Use it as a second known-value test beside the first sample.

Why does a zero payload not prove the byte order?

All-zero bytes decode to 0.0 under every byte order, so a zero test passes even when the order is wrong; the engineer testing this device saw exactly that. Validate with a nonzero payload of known value and compare the decoder output against an independent decode such as the Python reference.

Does the decoded float carry an engineering unit?

No. The decode returns the raw IEEE 754 number the device packed into the four bytes; the unit, whether degrees, amps or anything else, comes from the device payload specification, and any scaling it defines is applied after the decode, inside the same processor function or downstream.

Keep reading

  • Explainer

    Why Telegraf writes MQTT float values into the string measurement

    MQTT payloads are untyped bytes and the broker routes on the topic alone, so two mqtt_consumer instances on the same filter each receive every message. Numeric text parses both as a float and as a string, which puts every float into the string measurement; status text fails the float parse and appears only as a string. Make the two topic filters mutually exclusive, or publish Line Protocol and parse it with one consumer set to the influx data format.

    Edge computing and IIoT

  • How-to

    Keep both arrival time and payload timestamp in Telegraf

    Setting json_time_key replaces the metric timestamp with the payload time, so the arrival time is lost before any output sees it. Drop that option, keep the payload timestamp as a field, and use a Starlark processor that returns two metrics: one point keeps the arrival timestamp with the payload time as a field, the clone takes the payload value as its timestamp.

    Edge computing and IIoT

  • How-to

    Turn an MQTT topic into InfluxDB fields with Telegraf

    Telegraf reads /temperature/boiler/room3 with payload 21.7 as a metric carrying a topic tag and a value field. A five-processor chain (regex, converter, regex, regex, pivot) renames the measurement, builds location=room3 and pivots the middle segment into the field key; one Starlark processor does the same in eight lines. Either way the output line is temperature,location=room3 boiler=21.7 with the original timestamp.

    Edge computing and IIoT

Java ETK MQTT connection status and offline buffering