Log HAL values to CSV and Prometheus

hal_logger.py is a Python program that writes chosen HAL values to a CSV file as they change. It uses one WatchValues stream, reconnects when the server goes away, and can serve the latest values to Prometheus. It sends no commands.

Before you start

You need the server running on the LinuxCNC machine, bound to 127.0.0.1 (see Install and start the server), and Python 3.10 or newer on the computer that logs. If that is another computer, open an SSH tunnel, which runs until you stop it:

python3 -m venv venv && . venv/bin/activate   # Debian refuses a plain pip install
pip install linuxcnc-grpc
ssh -N -L 127.0.0.1:50051:127.0.0.1:50051 user@cnc-machine

The server has no authentication or TLS. The tunnel supplies the encryption and the login, but anyone with a login on either computer can reach the forwarded port. See Security.

Run it

The program is examples/guides/hal_logger.py in the repository. Download it and run it:

curl -O https://raw.githubusercontent.com/dougcalobrisi/linuxcnc-grpc/main/examples/guides/hal_logger.py
python hal_logger.py -p spindle.0.speed-out -p motion.current-vel --output run.csv

It writes one row per value, then one row per change:

timestamp,name,value
2026-12-04T14:02:11.204+00:00,spindle.0.speed-out,0.0
2026-12-04T14:02:11.205+00:00,motion.current-vel,0.0
2026-12-04T14:02:15.733+00:00,spindle.0.speed-out,12000.0
2026-12-04T14:02:16.031+00:00,motion.current-vel,25.0

--server defaults to localhost:50051. --interval-ms is how often the server reads the values, from 1 to 60000, 100 by default. --output appends to the file and writes the header only to a new file; without it the CSV goes to standard output. Log messages go to standard error. Ctrl+C or SIGTERM closes the watch and the file and exits with status 0.

Choose the pins

Log the pins that answer your question, and no more: every name adds rows. On the LinuxCNC machine, halcmd lists every pin with its type, direction and current value:

halcmd show pin | grep spindle

From another computer, the hal_query example asks the server with a glob pattern. It is not part of the linuxcnc-grpc package: run it from examples/python in a copy of the repository.

cd linuxcnc-grpc/examples/python
python hal_query.py pins "spindle.*"

These pins come with LinuxCNC 2.9’s motion controller, for each spindle, joint and axis your machine has:

PinWhat it holds
spindle.0.speed-outCommanded spindle speed, in RPM.
spindle.0.at-speedTrue when the spindle reports it is at speed.
motion.current-velCurrent tool velocity, in machine units per second.
joint.0.pos-fbFeedback position of joint 0.
axis.x.pos-cmdCommanded position of the X axis.

Spindle load, motor temperature and similar values come from your hardware’s driver, so their names depend on your configuration. Signal names from your .hal files work too, and so do parameter names.

-p takes an exact name and can be repeated. --pattern is matched once, at start, against pin and signal names with QueryPins and QuerySignals. Matching works like Python’s fnmatch: * also matches dots, so spindle.* matches spindle.0.speed-out, and case counts. An empty pattern matches everything, so the program refuses it. One watch takes at most 1000 names, so the program keeps the first 1000. A pin added to HAL later is not picked up until you restart the program. With no -p and no --pattern, the program logs spindle.0.speed-out.

How it works

Values

def value_to_text(hal_value: hal_pb2.HalValue) -> str:
    """One CSV cell: 1/0 for bits, the number otherwise, empty if unset."""
    kind = hal_value.WhichOneof("value")
    if kind is None or kind == "port_value":
        return ""  # a port, or a value the server could not read
    if kind == "bit_value":
        return "1" if hal_value.bit_value else "0"
    if kind == "float_value":
        return repr(hal_value.float_value)  # shortest exact form; nan stays nan
    return str(getattr(hal_value, kind))  # s32, u32, s64 or u64

A HalValue holds one of six types. Bits become 1 and 0, so a plotting tool can draw them. A port, or a value the server could not read, becomes an empty cell. A float can be NaN, written as nan; the server counts two NaN readings in a row as no change.

The first rows

The watch sends a batch only when a value changed, and nothing at start. So after opening it, the program reads each value once with GetValue:

# The watch sends only changes, so read every value once first.
# Opening the watch before this keeps the gap between the two short.
first_rows = []
for name in names:
    response = stub.GetValue(hal_pb2.GetValueCommand(name=name), timeout=RPC_TIMEOUT)
    if not response.success:
        raise ValueNotReadable(f"Cannot read '{name}': {response.error}")
    first_rows.append([now_iso(), name, value_to_text(response.value)])
# Every value was read. If the server has not refused the watch by
# now, write the rows, then show the values and "connected" to
# Prometheus together, never one without the other.
if stream.is_active():
    csv_writer.writerows(first_rows)
    output_file.flush()
    latest.connect({name: text for _, name, text in first_rows})

GetValue reports a name it cannot read with success false, not with an error code, so the program checks the field. It writes the rows only when every value was read and the watch is still open. The Prometheus values and the connected gauge are set in the same step. A change between the watch’s own first read and these reads shows up only with that value’s next change.

Every row has the logging computer’s clock. The GetValue rows carry no server time, and the server’s time on a change is when its poll noticed it, on the LinuxCNC machine’s clock. The file is flushed after every batch, so tail -f shows rows as they arrive.

A dead connection

A quiet watch is normal on an idle machine, so silence cannot show that the network went away. Every 30 seconds a second thread reads one value with a 5-second deadline. If the call fails with UNAVAILABLE or DEADLINE_EXCEEDED, it cancels the watch and the program reconnects:

def check_connection(stream, stub, probe_name, watch_ended, failures) -> None:
    """Cancel a quiet watch whose server no longer answers."""
    while not watch_ended.wait(CONNECTION_CHECK_INTERVAL):
        try:
            # Only whether the server answers matters here. An answer with
            # success=false means the name is gone, and the watch then ends
            # on its own with INTERNAL.
            stub.GetValue(hal_pb2.GetValueCommand(name=probe_name), timeout=RPC_TIMEOUT)
        except grpc.RpcError as error:
            if error.code() in RETRYABLE_CODES:
                failures.append(error)
                stream.cancel()
                return
        except ValueError:
            return  # the channel was closed: the watch is over

Reconnecting

The program retries UNAVAILABLE and DEADLINE_EXCEEDED with a new channel, after 1 second and then twice as long each time, up to 30 seconds. It logs the linuxcnc-grpc-reason entry. After a reconnect it reads every value again, so the CSV shows the values the machine came back with.

Before the first watch has worked, any other failure ends the program with exit status 1:

FailureWhat it means for the logger
INVALID_ARGUMENTA name does not exist; check the spelling with halcmd show pin.
GetValue with success falseThe same, seen by the first read.
INTERNALThe server could not read HAL when the watch started, or a watched name could not be read five polls in a row.
RESOURCE_EXHAUSTEDThe server has too many streams open (see Limits).

Once a watch has stayed open for 2 seconds, the program retries these too. A restart of LinuxCNC is the reason. On a normal shutdown of LinuxCNC the watch usually ends with INTERNAL, because the pins are gone, or with UNAVAILABLE and no reason. It does not end with linuxcnc-gone. The server then exits and a supervisor has to start it again (see When LinuxCNC stops). While LinuxCNC starts, the watched pins can still be missing for a moment. The logger keeps retrying through all of this and goes on when the pins are back.

Feed Grafana

Prometheus

python hal_logger.py -p spindle.0.speed-out -p motion.current-vel --prometheus-port 9105

The program then serves the latest values at http://127.0.0.1:9105/metrics:

# HELP linuxcnc_hal_value Latest value of a watched HAL item.
# TYPE linuxcnc_hal_value gauge
linuxcnc_hal_value{name="motion.current-vel"} 25.0
linuxcnc_hal_value{name="spindle.0.speed-out"} 12000.0
# HELP linuxcnc_hal_logger_connected 1 while the watch is open.
# TYPE linuxcnc_hal_logger_connected gauge
linuxcnc_hal_logger_connected 1

While the watch is down, the values are left out and linuxcnc_hal_logger_connected is 0, so Grafana shows a gap instead of old numbers. The endpoint listens on 127.0.0.1 only, because it has no authentication: run Prometheus on the same computer, or reach it through an SSH tunnel. Add a scrape job to prometheus.yml:

scrape_configs:
  - job_name: linuxcnc_hal
    scrape_interval: 1s
    static_configs:
      - targets: ["127.0.0.1:9105"]

Prometheus keeps only the value it finds at each scrape. A change that comes and goes between two scrapes is in the CSV but not in Prometheus.

InfluxDB

examples/guides/csv_to_influx.py reads the logger’s CSV from standard input and writes each row to InfluxDB 2:

curl -O https://raw.githubusercontent.com/dougcalobrisi/linuxcnc-grpc/main/examples/guides/csv_to_influx.py
export INFLUX_URL=http://127.0.0.1:8086 INFLUX_ORG=shop INFLUX_BUCKET=hal INFLUX_TOKEN=...
python hal_logger.py -p spindle.0.speed-out | python csv_to_influx.py

Each row becomes a point like hal,name=spindle.0.speed-out value=12000.0 1796392935733, with the time in milliseconds. Every value is written as a float, so a field never changes type. Empty cells, NaN and infinity are skipped, because line protocol cannot write them. A write that fails prints a warning, and the script goes on with the next row.

InfluxDB keeps one point per name and timestamp. Two rows for one name within the same millisecond therefore become one point with the later value, which can happen with --interval-ms 1.

Other languages

The program exists in Python only. In Go, Node.js or Rust, start from the hal_query example of that language, in examples/go, examples/node or examples/rust. Its watch command already opens a WatchValues stream and prints each change. Copy three things from this page: the conversion of a value to text, the first read with GetValue, and the connection check. The linuxcnc-grpc-reason entry is in the trailing metadata of the error that ends the stream (see Errors and reasons). In Node.js, s64_value and u64_value are exact only up to 2^53 (see 64-bit integers in Node.js).

Limits

The logger shows HAL as the server samples it, not every change HAL makes. HAL updates most pins every servo period, typically 1 ms; the server reads each watched value once per interval.

  • A change undone before the next read is lost: a 20 ms pulse on a bit pin can be missing.
  • A row’s timestamp can be up to one interval, plus network delay, after the change.
  • A value that changes all the time, such as a position while the machine moves, gives one row per interval.
  • Each watch holds one of the server’s stream slots while it runs (see Limits).

To record every servo period, record on the machine itself: LinuxCNC’s realtime sampler component copies pin values into a FIFO, and halsampler writes them to a file or standard output.