#include "poll_modbus.h"

#include <aspoprotocol.h>
#include <aspoutil.h>
#include <unistd.h>

int run_read(int fd, int ressz, uint8_t *res, int to) {
  ssize_t cntio;
  int ix;
  struct timeval tv = { 0, to * 1000 };
  fd_set sr;
  FD_ZERO(&sr);
  FD_SET(fd, &sr);

  LOG_VIFERRNO( (ix = select(fd+1, &sr, NULL, NULL, &tv)) < 0, LOG_ERR, " fd %d", fd ) {
    return -1;
  }
  if (ix == 0) {
    /*NOTICE("timeout on fd %d", fd); */
    return 0;
  }
  
  /* get and check response */
  LOG_IFERRNO( (cntio = read( fd, res, ressz)) < 0, LOG_ERR) return -1;
  /*LOG_VIF( cntio != ressz, LOG_ERR, " fd (%d) cntio (%d) ressz (%d)", fd, cntio, ressz) return -1; // rm this, buffer may be larger than what get */

  return cntio;
}
