cl-opendaq

2026-11-29

Common Lisp bindings for openDAQ.

Upstream URL

github.com/adolenc/cl-opendaq

Author

Andrej Dolenc

License

MIT
README

openDAQ Common Lisp bindings

Common Lisp bindings for interacting with openDAQ devices. Developed against SBCL. Prebuilt native binaries for x64 Linux, x64 Windows, and ARM macOS are downloaded automatically on first load (only for your platform, ~15 MB).

Quickstart

Install the library as a Quicklisp local project by cloning it into ~/quicklisp/local-projects/opendaq/.

Then, run the following in your REPL:

(ql:quickload :opendaq)

(defparameter *instance* (make-instance 'daq:instance))

(format t "Available devices: ~%~{ - ~A~%~}~%"
  (mapcar #'daq:connection-string (daq:available-devices *instance*)))

(let* ((device (daq:add-device *instance* "daqref://device0"))
       (channel (daq:as (daq:find-component *instance* "Dev/RefDev0/IO/AI/RefCh0") 'daq:channel))
       (signal (first (daq:signals channel)))
       (reader (make-instance 'daq:stream-reader :signal signal)))
  (setf (daq:property-value device "GlobalSampleRate") 100
        (daq:property-value channel "Frequency") 0.5)
  (daq:read reader 100 :timeout-ms 2000))

This should give you an output of 100 samples from the simulator device set to run at 100Hz, a sine wave at 0.5Hz.

If that fails, run a healthcheck to verify that the library can find and load the native openDAQ libraries correctly:

(daq:healthcheck)

See the examples/ folder for some more example scripts.

Native binaries

The first (ql:quickload :opendaq) downloads the prebuilt openDAQ libraries for your platform from this repository's GitHub release pinned in native-binaries.sexp, verifies their SHA256 checksum, and caches them under ~/.cache/cl-opendaq/ (%LOCALAPPDATA%\cache\cl-opendaq\ on Windows). Subsequent loads reuse the cache. The download needs curl and tar, which ship with Linux, macOS, and Windows 10+.

The loader looks for the libraries in this order:

  1. the directory named by the OPENDAQ_LISP_NATIVE_DIR environment variable,
  2. bin/<platform>/ inside the system directory (a local make bindings build),
  3. the per-user download cache, downloading into it when necessary.

Set OPENDAQ_NO_DOWNLOAD to forbid the automatic download (e.g. in offline or CI environments); you can still trigger it explicitly with (daq:install-native-libraries). Set OPENDAQ_NATIVE_ARCHIVE_URL to fetch the archive from a mirror instead of GitHub (checksum verification is skipped for mirrors).

Some details

The library is composed of 2 packages: :opendaq (nicknamed :daq) and :opendaq.low-level:

  • :opendaq.low-level contains low-level bindings that closely mirror the C API by utilizing CFFI. These are autogenerated from the C header files (in openDAQ/bindings/c/) and are not intended for direct use by end-users.
  • :opendaq contains a high-level API that wraps the low-level bindings in a more idiomatic and user-friendly way. This is the intended interface for end-users.

The high-level API uses CLOS to attempt to mirror openDAQ classes and their hierarchy, and uses generics/methods on them for function calls. It drops the get/set prefixes from the function names, and instead uses setf wrappers for setters.

A method is normally named by its bare stem (daq:signals, daq:lock): one generic, shared across every class that has it. When the same call takes different arities across classes (CLOS requires congruent lambda lists), it is either folded into one generic with trailing &optional parameters or given a receiver-prefixed name (daq:device-private-lock). Note that a leading word isn't always such a prefix - it may be openDAQ's own (getDeviceRevision → daq:device-revision) or a static per-interface method with no receiver to dispatch on (getInterfaceId → daq:<class>-interface-id).

The hierarchy is parsed automatically from the C header files via the DECLARE_OPENDAQ_INTERFACE(IChild, IParent) macros. The root of the hierarchy is daq:managed-object, which owns a raw pointer and registers a trivial-garbage finalizer to call daq:release-ref when the wrapper is collected, so you never have to release openDAQ objects manually.

The bindings depend only on plain cffi. For the one C type passed by value, the daqIntfID GUID, generator passes its 16 opaque bytes per the platform ABI: two 64-bit words on Linux/macOS, a pointer on Windows. Passing struct by value would normally need cffi-libffi (which compiles a C shim at load time and so fails on hosts without a C compiler, e.g. a stock Windows install) so this is a deliberate design choice to avoid that dependency.

Boxing / unboxing

The high-level API insulates you from openDAQ's C types. Arguments accept plain Lisp values (boxing, on input) and return values are plain Lisp types (unboxing, on output); the two directions are inverses, so one table covers both:

Lisp valueopenDAQ core typeBoxed type
string:stringdaq:string-object
integer:intdaq:integer-object
float:floatdaq:float-object
t / nil:booldaq:boolean-object
ratio:ratiodaq:ratio-object
(complex re im):complex-numberdaq:complex-number-object
any daq objectits raw pointerdaq object

daqNumber is output-only: it unboxes to a float, but no Lisp type boxes to it specifically (a float always boxes to daq:float-object).

Helper functions

A few functions are implemented manually to help you get out of tricky situations. The two conversion functions are split by which world the result lives in - daq:as recasts between openDAQ wrappers and never leaves openDAQ, while daq:unbox crosses into Lisp, discovering the value's type from the object itself so it needs no type argument:

  • (daq:as daq-obj 'daq-type) - reinterpret an object as the more specific daq-type, returning a wrapper of that type (an unchecked cast; only valid when obj really is that type - see daq:typep below)
  • (daq:unbox daq-obj) - the natural Lisp value of daq-obj: a boxed scalar yields its native value (per the table above), a daq list a Lisp list, and a daq dict a hash-table, with elements unboxed recursively; an element with no Lisp form (e.g. a device sitting in a list) stays a wrapper for you to daq:as-cast. Works on a generic base-object with no cast needed - (daq:unbox (gethash "Name" (daq:parameters event))) ⇒ "Frequency", (daq:unbox (daq:selection-values prop)) ⇒ ("Low" "Mid" "High") - and returns an already-native Lisp value unchanged
  • (daq:typep daq-obj 'daq-type) - test whether daq-obj is a daq-type, i.e. implements that interface (a real query, unlike the unchecked daq:as)
  • (daq:component-type daq-obj) - the most-derived component interface daq-obj implements (daq:channel, daq:signal, daq:device, …) as a class symbol, or nil
  • (daq:domain-tick->timestamp source tick) - convert a domain tick to a local-time timestamp (source is a signal, data descriptor, or multi reader; (daq:domain-time-converter source) returns a reusable per-tick closure)

Note that daq:property-value already applies the unboxing for you: reading a property returns its value in natural Lisp form - a scalar comes back unboxed (a plain integer, float, string, …), a func/proc property comes back as a Lisp function you can funcall, and anything else (object, struct, list, dict) comes back as a wrapper. So daq:unbox is only needed for raw base-objects from elsewhere (a dict value, a core event's parameters, a property's default-value, …).

openDAQ Object Construction

Every openDAQ object is built with make-instance, e.g. (make-instance 'daq:stream-reader :signal signal).

Some things are not distinct openDAQ interfaces but variants of one type that openDAQ builds through factory functions - for example a property is always an int/string/selection/… property, never a bare Property. These (and a type's alternate constructors such as stream-reader-from-port for stream-reader) are exposed as base/variant subclasses:

(make-instance 'daq:property/int :name "Frequency" :default-value 10 :visible t)
(make-instance 'daq:property/selection :name "Mode" :selection-values modes :default-value 0 :visible t)
(make-instance 'daq:data-rule/linear :delta 2 :start 0)
(make-instance 'daq:logger-sink/std-err)
(make-instance 'daq:stream-reader/from-port :port port)   ; an alternate stream-reader constructor

Each such class is a subclass of the type it builds (i.e. (typep (make-instance 'daq:property/int …) 'daq:property) is true), so the result works anywhere that type is expected. This covers property builders, data/dimension rules, search filters, scalings, logger sinks, and similar factory-built types. (apropos for / lists them.)

Types that openDAQ constructs from a Builder object instead take a :builder keyword on their regular make-instance rather than a separate class (e.g. (make-instance 'daq:scaling :builder b), with :builder taking precedence if the type's direct arguments are also supplied); for daq:instance the builder defaults to one pointing at the bundled native modules, so (make-instance 'daq:instance) needs no arguments.

Events

openDAQ events (core/structure events, property change notifications, …) are subscribed to by passing a Lisp function straight to daq:add-handler; it is called with the sender and event args (already wrapped) each time the event fires, and reference counting is handled for you:

(daq:add-handler
  (daq:on-core-event (daq:context *instance*))
  (lambda (sender args)
    (let ((event (daq:as args 'daq:core-event-args)))
      (format t "~A~%" (daq:event-name event)))))

daq:add-handler returns the created daq:event-handler, which can be passed to daq:remove-handler to unsubscribe.

Procedures and functions from Lisp closures

Wherever openDAQ expects a Procedure or Function object (a func/proc property's value, a custom search filter, …), pass a Lisp function as the :value:

(setf (daq:property-value obj "Sum") (make-instance 'daq:function-object :value (lambda (a b) (+ a b))))

(make-instance 'daq:search-filter/custom
               :accepts-function (make-instance 'daq:function-object
                                                :value (lambda (prop) (daq:visible (daq:as prop 'daq:property))))
               :visit-function (make-instance 'daq:function-object :value (constantly nil)))

openDAQ invokes the closure - from Lisp or from native code - with the params decoded to natural Lisp values (scalars and containers unboxed, anything else wrapped for daq:as); a daq:function-object's return value is boxed back for the caller the same way. A condition signalled inside the closure is reported to the caller as an openDAQ error rather than unwinding across the C boundary. Since openDAQ has no destruction hook for callables, each closure-backed procedure/function keeps its closure (and a small compiled trampoline) alive for the rest of the session.

Development

The attached makefile is used for simplification of development. It handles cloning the pinned openDAQ source, building the native libraries, copying them into bin/linux-x64/, and regenerating the generated Lisp bindings. It also has targets for starting a REPL with the system loaded and running the test suite.

Makefile

make bindings # clone pinned openDAQ source, build native libs, copy them into bin/linux-x64/, and call `make regenerate-bindings`
make regenerate-bindings # regenerate generated/low-level-bindings.lisp and generated/high-level-bindings.lisp from the C headers in the cloned openDAQ source
make pack-binaries # pack each bin/<platform>/ into dist/opendaq-bin-<platform>.tar.gz release archives with a SHA256SUMS file
make repl     # start SBCL with the opendaq system loaded
make test     # run the FiveAM test suite
make clean    # remove bin/, tmp/ and dist/

Override OPENDAQ_REF in the Makefile if you want a different upstream version. Override OPENDAQ_RUNTIME_TRIPLE if you want make bindings, make repl, and make test to use a different bin/<platform>/ directory name.

Folder structure

  • *.lisp/.asd - handwritten lisp files for the run-time API
  • generated/ - autogenerated low-level and high-level bindings
  • examples/ - some stand-alone example scripts
  • tools/ - scripts used to generate the bindings in generated/ (note that tools/parse_bindings.py is a generic python script that can be used to generate bindings for any language)
  • t/ - FiveAM test files, mostly ported from the c bindings test suite
  • bin/ - locally built native openDAQ libraries (not committed; produced by make bindings), split by platform subdirectory. End users instead get the release archives pinned in native-binaries.sexp, which the Build native binaries GitHub Actions workflow publishes as release assets
  • tmp/ - temporary clone/build workspace used by make bindings

Dependencies (4)

  • cffi
  • fiveam
  • local-time
  • trivial-garbage

Dependents (0)

    • GitHub
    • Quicklisp