5

I have a piece of hardware that I'm trying to control via my computer's built-in SPI driver. The SPI driver is controlled via ioctl.

I can successfully drive the hardware from a small C program; but when I try to duplicate the C program in Ruby I run into problems.

Using IO#ioctl to set basic registers (with u32 and u8 ints) works fine (I know because I can also use ioctl to read back the values I set); but as soon as I try to set a complex struct, the program fails with

small.rb:51:in 'ioctl': Connection timed out @ rb_ioctl - /dev/spidev32766.0 (Errno::ETIMEDOUT)

I might be running into trouble because the spi_ioc_transfer struct has two pointers to byte buffers but the pointers are typed as unsigned 64-bit ints even on 32-bit platforms -- necessitating a cast to (unsigned long) in C. I'm trying to replicate that in Ruby but am quite unsure of myself.

Below are the C program which works and the Ruby port which doesn't work. The do_latch functions are necessary so I can see the result in my hardware; but are probably not germane to this problem.

C (which works):

#include <stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/spi/spidev.h>

int do_latch() {
    int fd = open("/sys/class/gpio/gpio1014/value", O_RDWR);
    write(fd, "1", 1);
    write(fd, "0", 1);

    close(fd);
}

int do_transfer(int fd, uint8_t *bytes, size_t len) {
    uint8_t *rx_bytes = malloc(sizeof(uint8_t) * len);

    struct spi_ioc_transfer transfer = {
        .tx_buf = (unsigned long)bytes,
        .rx_buf = (unsigned long)rx_bytes,

        .len = len,
        .speed_hz = 100000,

        .delay_usecs = 0,
        .bits_per_word = 8,
        .cs_change = 0,
        .tx_nbits = 0,
        .rx_nbits = 0,
        .pad = 0
    };

    if(ioctl(fd, SPI_IOC_MESSAGE(1), &transfer) < 1) {
        perror("Could not send SPI message"); 
        exit(1); 
    }

    free(rx_bytes);
}

int main() {
    int fd = open("/dev/spidev32766.0", O_RDWR);

    uint8_t mode = 0;
    ioctl(fd, SPI_IOC_WR_MODE, &mode);

    uint8_t lsb_first = 0;
    ioctl(fd, SPI_IOC_WR_LSB_FIRST, lsb_first);

    uint32_t speed_hz = 100000;
    ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, speed_hz);

    size_t data_len = 36;
    uint8_t *tx_data = malloc(sizeof(uint8_t) * data_len);

    memset(tx_data, 0xFF, data_len);

    do_transfer(fd, tx_data, data_len);
    do_latch();

    sleep(2);

    memset(tx_data, 0x00, data_len);

    do_transfer(fd, tx_data, data_len);
    do_latch();

    free(tx_data);
    close(fd);
    return 0;
}

Ruby (which fails on the ioctl line in do_transfer):

SPI_IOC_WR_MODE = 0x40016b01
SPI_IOC_WR_LSB_FIRST = 0x40016b02
SPI_IOC_WR_BITS_PER_WORD = 0x40016b03
SPI_IOC_WR_MAX_SPEED_HZ = 0x40046b04
SPI_IOC_WR_MODE32 = 0x40046b05
SPI_IOC_MESSAGE_1 = 0x40206b00 

def do_latch()
  File.open("/sys/class/gpio/gpio1014/value", File::RDWR) do |file|
    file.write("1")
    file.write("0")
  end
end

def do_transfer(file, bytes)
  ##########################################################################################
  #begin spi_ioc_transfer struct (cat /usr/include/linux/spi/spidev.h)

    #pack bytes into a buffer; create a new buffer (filled with zeroes) for the rx
    tx_buff = bytes.pack("C*")        
    rx_buff = (Array.new(bytes.size) { 0 }).pack("C*")       

    #on 32-bit, the struct uses a zero-extended pointer for the buffers (so it's the same
    #byte layout on 64-bit as well) -- so do some trickery to get the buffer addresses 
    #as 64-bit strings even though this is running on a 32-bit computer
    tx_buff_pointer = [tx_buff].pack("P").unpack("L!")[0]   #u64 (zero-extended pointer)
    rx_buff_pointer = [rx_buff].pack("P").unpack("L!")[0]   #u64 (zero-extended pointer)

    buff_len = bytes.size                                   #u32
    speed_hz = 100000                                       #u32

    delay_usecs = 0                                         #u16
    bits_per_word = 8                                       #u8
    cs_change = 0                                           #u8
    tx_nbits = 0                                            #u8
    rx_nbits = 0                                            #u8
    pad = 0                                                 #u16

    struct_array = [tx_buff_pointer, rx_buff_pointer, buff_len, speed_hz, delay_usecs, bits_per_word, cs_change, tx_nbits, rx_nbits, pad]
    struct_packed = struct_array.pack("QQLLSCCCCS")

    #in C, I pass a pointer to the the structure; so mimic that here
    struct_pointer_packed = [struct_packed].pack("P")
  #end spi_ioc_transfer struct
  ##########################################################################################

  file.ioctl(SPI_IOC_MESSAGE_1, struct_pointer_packed)
end

File.open("/dev/spidev32766.0", File::RDWR) do |file|

  file.ioctl(SPI_IOC_WR_MODE, [0].pack("C"));
  file.ioctl(SPI_IOC_WR_LSB_FIRST, [0].pack("C"));
  file.ioctl(SPI_IOC_WR_MAX_SPEED_HZ, [0].pack("L"));

  data_bytes = Array.new(36) { 0x00 }

  do_transfer(file, data_bytes)
  do_latch()

  sleep(2) 

  data_bytes = []
  data_bytes = Array.new(36) { 0xFF }

  do_transfer(file, data_bytes)
  do_latch()

end

I pulled the magic number constants out by having C print them (they're macros in C). I can validate that most of them work; I'm a little unsure about the ioctl message that fails (SPI_IOC_MESSAGE_1) since that doesn't work and it's a complicated macro. Still, I have no reason to think that it's incorrect and it's always the same when I look at it from C.

When I print out the structure in C and then print it out in Ruby, the only differences are in the buffer addresses, so if something's going wrong, that feels like the right place to look. But I've run out of things to try.

I can also print out the addresses in both versions and they look like what I would expect, 32 bits extended to 64 bits, and match the values in the structure (although the structure is little-endian -- this is an ARM).

Structure in C (that works):

60200200 00000000 a8200200 00000000 24000000 40420f00 00000800 00000000

Structure in Ruby (that fails):

a85da27f 00000000 08399b7f 00000000 24000000 40420f00 00000800 00000000

Is there an obvious mistake that I'm making when I lay out the struct in Ruby? Is there something else that I'm missing?

My next step is to write a library in C and use FFI to access it from Ruby. But that seems like giving up; and using the native ioctl function feels like the better approach if I can ever make it work.

Update

Above, I'm doing

    struct_array = [tx_buff_pointer, rx_buff_pointer, buff_len, speed_hz, delay_usecs, bits_per_word, cs_change, tx_nbits, rx_nbits, pad]
    struct_packed = struct_array.pack("QQLLSCCCCS")

    #in C, I pass a pointer to the the structure; so mimic that here
    struct_pointer_packed = [struct_packed].pack("P")
    file.ioctl(SPI_IOC_MESSAGE_1, struct_pointer_packed)

because I have to pass a pointer to the struct in C. But that's what's causing the error!

Instead, it needs to be

    struct_array = [tx_buff_pointer, rx_buff_pointer, buff_len, speed_hz, delay_usecs, bits_per_word, cs_change, tx_nbits, rx_nbits, pad]
    struct_packed = struct_array.pack("QQLLSCCCCS")

    file.ioctl(SPI_IOC_MESSAGE_1, struct_packed)

I guess Ruby is automatically making it an array when it marshalls it over?

Unfortunately, now it only intermittently works. The second call never works and the first call doesn't work if I pass in all zeros. It's very mysterious.

0

1 Answer 1

1

It is a common issue not to flush the buffer, you could check it out and try it.

Flush: Flushes any buffered data within ios to the underlying operating system (note that this is Ruby internal buffering only; the OS may buffer the data as well).

rb_io_flush(VALUE io)
{
    return rb_io_flush_raw(io, 1);
}
3
  • I tried calling file.flush() after the file.ioctl call but didn't notice any change in behavior. :( Jan 18, 2017 at 22:00
  • The last I could suggest for the moment is to check if the data is actually written at the moment the program is supposed to write it, not at the end. Check if the data is not only flushed from ruby environment but also from the OS to the IO. You can verify it using fsync. It will tell you with an exception if the underlying OS writes the data right away. Jan 19, 2017 at 7:17
  • The part where I said "The do_latch functions are necessary so I can see the result in my hardware; but are probably not germane to this problem." was in fact the problem. I was so busy looking at ioctl that I missed that I wasn't flushing when writing the latch values. Thank you so much! Jan 19, 2017 at 11:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.