Add timeout feature to expect()

This commit is contained in:
Martin Lund 2024-04-13 15:30:14 +02:00
parent 3ad090caf7
commit 51300cc4f0
6 changed files with 60 additions and 34 deletions

View file

@ -256,20 +256,27 @@ bool match_regex(regex_t *regex)
return false;
}
// lua: expect(string)
// lua: expect(string, timeout)
static int expect(lua_State *L)
{
const char *string = lua_tostring(L, 1);
long timeout = lua_tointeger(L, 2);
regex_t regex;
int ret = 0;
char c;
if (string == NULL)
if ((string == NULL) || (timeout < 0))
{
ret = -1;
goto error;
}
if (timeout == 0)
{
// Let poll() wait forever
timeout = -1;
}
// Compile the regular expression
ret = regcomp(&regex, string, REG_EXTENDED);
if (ret)
@ -282,7 +289,7 @@ static int expect(lua_State *L)
// Main loop to read and match
while (true)
{
ssize_t bytes_read = read(serial_fd, &c, 1);
ssize_t bytes_read = read_poll(serial_fd, &c, 1, timeout);
if (bytes_read > 0)
{
putchar(c);
@ -293,6 +300,11 @@ static int expect(lua_State *L)
break;
}
}
else
{
// Timeout or error
break;
}
}
// Cleanup