New Project: libhackrf Racket bindings

I’m fond of my HackRF radio, but lost interest in working through GnuRadio Companion, because I don’t want to do any Python programming to extend the blocks. So I started looking into scheme bindings for libhackrf. There is a learning curve, for sure, but it appears that this shouldn’t be too difficult, using the Racket FFI. Here is some code (minus some important error checking) that pulls the hackrf_device_list, i.e., the struct containing information about what HackRF devices are currently plugged in to your USB:

#lang racket/base

(require ffi/unsafe
(define-ffi-definer define-hackrf (ffi-lib "libhackrf"))

(define-hackrf hackrf_init (_fun -> _int))
(define-hackrf hackrf_exit (_fun -> _int))

(define _hackrf_device_list_t-pointer (_cpointer 'hackrf_device_list_t))

(define-hackrf hackrf_device_list (_fun -> _hackrf_device_list_t-pointer))

(define-cstruct _hackrf_device_list_st ([serial_numbers _pointer]
                                        [usb_board_ids _pointer]
                                        [usb_device_index _pointer]
                                        [devicecount _int32]
                                        [usb_devices _pointer]
                                        [usb_devicecount _int32]))

This ties into the C API from hackrf.h (ADDAPI and ADDCALL are blank except in Windows):

struct hackrf_device_list {
	char **serial_numbers;
	enum hackrf_usb_board_id *usb_board_ids;
	int *usb_device_index;
	int devicecount;
	void **usb_devices;
	int usb_devicecount;
typedef struct hackrf_device_list hackrf_device_list_t;

extern ADDAPI int ADDCALL hackrf_init();
extern ADDAPI int ADDCALL hackrf_exit();

extern ADDAPI hackrf_device_list_t* ADDCALL hackrf_device_list();

And here is a demo function to get the device count:

(define (hackrf-device-count)
   (ptr-ref (hackrf_device_list)

With my HackRF plugged in:

racket@hackrf-ffi.rkt> (hackrf_init)
 racket@hackrf-ffi.rkt> (hackrf-device-count)

After unplugging it:

racket@hackrf-ffi.rkt> (hackrf-device-count)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s