The following px4 module reads next 100 bytes of a text file (several kilobytes) when user command received:
class SampleModule final : public ModuleBase<SampleModule>, public ModuleParams
{
int _fd = -1;
public:
static int custom_command(int argc, char *argv[])
{
if (argc == 1 && !strcmp(argv[0], "test"))
return get_instance()->test_command();
return print_usage("unknown command");
}
int test_command()
{
if (_fd < 0) {
_fd = px4_open("/fs/microsd/1.txt", O_RDONLY);
if (_fd < 0) {
PX4_ERR("can't open file, %d", errno);
return -1;
}
}
char buf[100];
int st = px4_read(_fd, buf, 100);
if (st < 0) {
PX4_ERR("can't read from %d, because %d", _fd, errno);
return -1;
} else {
PX4_INFO("read %d bytes", st);
}
return 0;
}
};
The problem is the function read
(or px4_read
) works at the first call only. On the second call I am getting the reading error
nsh> sample_module start
nsh> sample_module status
INFO [sample_module] running
nsh> sample_module test
INFO [sample_module] read 100 bytes
nsh> sample_module test
ERROR [sample_module] can't read from 3, because 13
It seems, that the file descriptor _fd
is not valid after the method custom_command
completes.
But the function read
works fine if I call it several times consecutive at one custom_command
call. Probably, the posix file functions have specific behavior and I should use them in a different manner, should I?
I launch this code in HITL mode on the holybro durandal v1
board.