fpgautils.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. /*
  2. * Copyright 2013 Con Kolivas <kernel@kolivas.org>
  3. * Copyright 2012 Luke Dashjr
  4. * Copyright 2012 Andrew Smith
  5. *
  6. * This program is free software; you can redistribute it and/or modify it
  7. * under the terms of the GNU General Public License as published by the Free
  8. * Software Foundation; either version 3 of the License, or (at your option)
  9. * any later version. See COPYING for more details.
  10. */
  11. #include "config.h"
  12. #include <sys/types.h>
  13. #include <dirent.h>
  14. #include <string.h>
  15. #include "miner.h"
  16. #ifndef WIN32
  17. #include <errno.h>
  18. #include <termios.h>
  19. #include <sys/ioctl.h>
  20. #include <sys/stat.h>
  21. #include <unistd.h>
  22. #include <fcntl.h>
  23. #ifndef O_CLOEXEC
  24. #define O_CLOEXEC 0
  25. #endif
  26. #else
  27. #include <windows.h>
  28. #include <io.h>
  29. #endif
  30. #ifdef HAVE_LIBUDEV
  31. #include <libudev.h>
  32. #include <sys/ioctl.h>
  33. #endif
  34. #include "elist.h"
  35. #include "logging.h"
  36. #include "miner.h"
  37. #include "fpgautils.h"
  38. #ifdef WIN32
  39. ssize_t win32read(int fd, void *buf, size_t count)
  40. {
  41. OVERLAPPED osRead = { 0 };
  42. HANDLE fh;
  43. DWORD win32errno;
  44. size_t actual;
  45. bool success = false;
  46. fh = (HANDLE)_get_osfhandle(fd);
  47. if (fh == INVALID_HANDLE_VALUE)
  48. return -1;
  49. // Create the overlapped event. Must be closed before exiting
  50. // to avoid a handle leak.
  51. osRead.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  52. if (osRead.hEvent == NULL)
  53. return -1;
  54. // Issue read operation.
  55. if (!ReadFile(fh, buf, count, (PDWORD)&actual, &osRead)) {
  56. win32errno = GetLastError();
  57. if (win32errno != ERROR_IO_PENDING) {
  58. success = false;
  59. } else {
  60. // Write is pending
  61. if (!GetOverlappedResult(fh, &osRead, (PDWORD)&actual, TRUE)) {
  62. win32errno = GetLastError();
  63. success = false;
  64. } else {
  65. // asynchronous read completed
  66. success = true;
  67. }
  68. }
  69. } else {
  70. // read completed immediately
  71. success = true;
  72. }
  73. CloseHandle(osRead.hEvent);
  74. SetLastError(win32errno);
  75. return (success) ? (ssize_t)actual : -1;
  76. }
  77. ssize_t win32write(int fd, const void *buf, size_t count)
  78. {
  79. OVERLAPPED osWrite = { 0 };
  80. HANDLE fh;
  81. DWORD win32errno;
  82. size_t actual;
  83. bool success = false;
  84. fh = (HANDLE)_get_osfhandle(fd);
  85. if (fh == INVALID_HANDLE_VALUE)
  86. return -1;
  87. // Create this write operation's OVERLAPPED structure's hEvent.
  88. osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  89. if (osWrite.hEvent == NULL)
  90. return -1;
  91. // Issue read operation.
  92. if (!WriteFile(fh, buf, count, (PDWORD)&actual, &osWrite)) {
  93. win32errno = GetLastError();
  94. if (win32errno != ERROR_IO_PENDING) {
  95. success = false;
  96. } else {
  97. // Write is pending
  98. if (!GetOverlappedResult(fh, &osWrite, (PDWORD)&actual, TRUE)) {
  99. win32errno = GetLastError();
  100. success = false;
  101. } else {
  102. // asynchronous read completed
  103. success = true;
  104. }
  105. }
  106. } else {
  107. // read completed immediately
  108. success = true;
  109. }
  110. CloseHandle(osWrite.hEvent);
  111. SetLastError(win32errno);
  112. return (success) ? (ssize_t)actual : -1;
  113. }
  114. #endif
  115. #ifdef HAVE_LIBUDEV
  116. int serial_autodetect_udev(detectone_func_t detectone, const char*prodname)
  117. {
  118. struct udev *udev = udev_new();
  119. struct udev_enumerate *enumerate = udev_enumerate_new(udev);
  120. struct udev_list_entry *list_entry;
  121. char found = 0;
  122. udev_enumerate_add_match_subsystem(enumerate, "tty");
  123. udev_enumerate_add_match_property(enumerate, "ID_MODEL", prodname);
  124. udev_enumerate_scan_devices(enumerate);
  125. udev_list_entry_foreach(list_entry, udev_enumerate_get_list_entry(enumerate)) {
  126. struct udev_device *device = udev_device_new_from_syspath(
  127. udev_enumerate_get_udev(enumerate),
  128. udev_list_entry_get_name(list_entry)
  129. );
  130. if (!device)
  131. continue;
  132. const char *devpath = udev_device_get_devnode(device);
  133. if (devpath && detectone(devpath))
  134. ++found;
  135. udev_device_unref(device);
  136. }
  137. udev_enumerate_unref(enumerate);
  138. udev_unref(udev);
  139. return found;
  140. }
  141. #else
  142. int serial_autodetect_udev(__maybe_unused detectone_func_t detectone, __maybe_unused const char*prodname)
  143. {
  144. return 0;
  145. }
  146. #endif
  147. int serial_autodetect_devserial(__maybe_unused detectone_func_t detectone, __maybe_unused const char*prodname)
  148. {
  149. #ifndef WIN32
  150. DIR *D;
  151. struct dirent *de;
  152. const char udevdir[] = "/dev/serial/by-id";
  153. char devpath[sizeof(udevdir) + 1 + NAME_MAX];
  154. char *devfile = devpath + sizeof(udevdir);
  155. char found = 0;
  156. D = opendir(udevdir);
  157. if (!D)
  158. return 0;
  159. memcpy(devpath, udevdir, sizeof(udevdir) - 1);
  160. devpath[sizeof(udevdir) - 1] = '/';
  161. while ( (de = readdir(D)) ) {
  162. if (!strstr(de->d_name, prodname))
  163. continue;
  164. strcpy(devfile, de->d_name);
  165. if (detectone(devpath))
  166. ++found;
  167. }
  168. closedir(D);
  169. return found;
  170. #else
  171. return 0;
  172. #endif
  173. }
  174. int _serial_detect(struct device_drv *drv, detectone_func_t detectone, autoscan_func_t autoscan, bool forceauto, bool inhibitauto)
  175. {
  176. struct string_elist *iter, *tmp;
  177. const char *dev, *colon;
  178. char found = 0;
  179. size_t namel = strlen(drv->name);
  180. size_t dnamel = strlen(drv->dname);
  181. list_for_each_entry_safe(iter, tmp, &scan_devices, list) {
  182. dev = iter->string;
  183. if ((colon = strchr(dev, ':')) && colon[1] != '\0') {
  184. size_t idlen = colon - dev;
  185. // allow either name:device or dname:device
  186. if ((idlen != namel || strncasecmp(dev, drv->name, idlen))
  187. && (idlen != dnamel || strncasecmp(dev, drv->dname, idlen)))
  188. continue;
  189. dev = colon + 1;
  190. }
  191. if (!strcmp(dev, "auto"))
  192. forceauto = true;
  193. else if (!strcmp(dev, "noauto"))
  194. inhibitauto = true;
  195. else if (detectone(dev)) {
  196. string_elist_del(iter);
  197. inhibitauto = true;
  198. ++found;
  199. }
  200. }
  201. if ((forceauto || !inhibitauto) && autoscan)
  202. found += autoscan();
  203. return found;
  204. }
  205. // This code is purely for debugging but is very useful for that
  206. // It also took quite a bit of effort so I left it in
  207. // #define TERMIOS_DEBUG 1
  208. // Here to include it at compile time
  209. // It's off by default
  210. #ifndef WIN32
  211. #ifdef TERMIOS_DEBUG
  212. #define BITSSET "Y"
  213. #define BITSNOTSET "N"
  214. int tiospeed(speed_t speed)
  215. {
  216. switch (speed) {
  217. case B0:
  218. return 0;
  219. case B50:
  220. return 50;
  221. case B75:
  222. return 75;
  223. case B110:
  224. return 110;
  225. case B134:
  226. return 134;
  227. case B150:
  228. return 150;
  229. case B200:
  230. return 200;
  231. case B300:
  232. return 300;
  233. case B600:
  234. return 600;
  235. case B1200:
  236. return 1200;
  237. case B1800:
  238. return 1800;
  239. case B2400:
  240. return 2400;
  241. case B4800:
  242. return 4800;
  243. case B9600:
  244. return 9600;
  245. case B19200:
  246. return 19200;
  247. case B38400:
  248. return 38400;
  249. case B57600:
  250. return 57600;
  251. case B115200:
  252. return 115200;
  253. case B230400:
  254. return 230400;
  255. case B460800:
  256. return 460800;
  257. case B500000:
  258. return 500000;
  259. case B576000:
  260. return 576000;
  261. case B921600:
  262. return 921600;
  263. case B1000000:
  264. return 1000000;
  265. case B1152000:
  266. return 1152000;
  267. case B1500000:
  268. return 1500000;
  269. case B2000000:
  270. return 2000000;
  271. case B2500000:
  272. return 2500000;
  273. case B3000000:
  274. return 3000000;
  275. case B3500000:
  276. return 3500000;
  277. case B4000000:
  278. return 4000000;
  279. default:
  280. return -1;
  281. }
  282. }
  283. void termios_debug(const char *devpath, struct termios *my_termios, const char *msg)
  284. {
  285. applog(LOG_DEBUG, "TIOS: Open %s attributes %s: ispeed=%d ospeed=%d",
  286. devpath, msg, tiospeed(cfgetispeed(my_termios)), tiospeed(cfgetispeed(my_termios)));
  287. #define ISSETI(b) ((my_termios->c_iflag | (b)) ? BITSSET : BITSNOTSET)
  288. applog(LOG_DEBUG, "TIOS: c_iflag: IGNBRK=%s BRKINT=%s IGNPAR=%s PARMRK=%s INPCK=%s ISTRIP=%s INLCR=%s IGNCR=%s ICRNL=%s IUCLC=%s IXON=%s IXANY=%s IOFF=%s IMAXBEL=%s IUTF8=%s",
  289. ISSETI(IGNBRK), ISSETI(BRKINT), ISSETI(IGNPAR), ISSETI(PARMRK),
  290. ISSETI(INPCK), ISSETI(ISTRIP), ISSETI(INLCR), ISSETI(IGNCR),
  291. ISSETI(ICRNL), ISSETI(IUCLC), ISSETI(IXON), ISSETI(IXANY),
  292. ISSETI(IXOFF), ISSETI(IMAXBEL), ISSETI(IUTF8));
  293. #define ISSETO(b) ((my_termios->c_oflag | (b)) ? BITSSET : BITSNOTSET)
  294. #define VALO(b) (my_termios->c_oflag | (b))
  295. applog(LOG_DEBUG, "TIOS: c_oflag: OPOST=%s OLCUC=%s ONLCR=%s OCRNL=%s ONOCR=%s ONLRET=%s OFILL=%s OFDEL=%s NLDLY=%d CRDLY=%d TABDLY=%d BSDLY=%d VTDLY=%d FFDLY=%d",
  296. ISSETO(OPOST), ISSETO(OLCUC), ISSETO(ONLCR), ISSETO(OCRNL),
  297. ISSETO(ONOCR), ISSETO(ONLRET), ISSETO(OFILL), ISSETO(OFDEL),
  298. VALO(NLDLY), VALO(CRDLY), VALO(TABDLY), VALO(BSDLY),
  299. VALO(VTDLY), VALO(FFDLY));
  300. #define ISSETC(b) ((my_termios->c_cflag | (b)) ? BITSSET : BITSNOTSET)
  301. #define VALC(b) (my_termios->c_cflag | (b))
  302. applog(LOG_DEBUG, "TIOS: c_cflag: CBAUDEX=%s CSIZE=%d CSTOPB=%s CREAD=%s PARENB=%s PARODD=%s HUPCL=%s CLOCAL=%s"
  303. #ifdef LOBLK
  304. " LOBLK=%s"
  305. #endif
  306. " CMSPAR=%s CRTSCTS=%s",
  307. ISSETC(CBAUDEX), VALC(CSIZE), ISSETC(CSTOPB), ISSETC(CREAD),
  308. ISSETC(PARENB), ISSETC(PARODD), ISSETC(HUPCL), ISSETC(CLOCAL),
  309. #ifdef LOBLK
  310. ISSETC(LOBLK),
  311. #endif
  312. ISSETC(CMSPAR), ISSETC(CRTSCTS));
  313. #define ISSETL(b) ((my_termios->c_lflag | (b)) ? BITSSET : BITSNOTSET)
  314. applog(LOG_DEBUG, "TIOS: c_lflag: ISIG=%s ICANON=%s XCASE=%s ECHO=%s ECHOE=%s ECHOK=%s ECHONL=%s ECHOCTL=%s ECHOPRT=%s ECHOKE=%s"
  315. #ifdef DEFECHO
  316. " DEFECHO=%s"
  317. #endif
  318. " FLUSHO=%s NOFLSH=%s TOSTOP=%s PENDIN=%s IEXTEN=%s",
  319. ISSETL(ISIG), ISSETL(ICANON), ISSETL(XCASE), ISSETL(ECHO),
  320. ISSETL(ECHOE), ISSETL(ECHOK), ISSETL(ECHONL), ISSETL(ECHOCTL),
  321. ISSETL(ECHOPRT), ISSETL(ECHOKE),
  322. #ifdef DEFECHO
  323. ISSETL(DEFECHO),
  324. #endif
  325. ISSETL(FLUSHO), ISSETL(NOFLSH), ISSETL(TOSTOP), ISSETL(PENDIN),
  326. ISSETL(IEXTEN));
  327. #define VALCC(b) (my_termios->c_cc[b])
  328. applog(LOG_DEBUG, "TIOS: c_cc: VINTR=0x%02x VQUIT=0x%02x VERASE=0x%02x VKILL=0x%02x VEOF=0x%02x VMIN=%u VEOL=0x%02x VTIME=%u VEOL2=0x%02x"
  329. #ifdef VSWTCH
  330. " VSWTCH=0x%02x"
  331. #endif
  332. " VSTART=0x%02x VSTOP=0x%02x VSUSP=0x%02x"
  333. #ifdef VDSUSP
  334. " VDSUSP=0x%02x"
  335. #endif
  336. " VLNEXT=0x%02x VWERASE=0x%02x VREPRINT=0x%02x VDISCARD=0x%02x"
  337. #ifdef VSTATUS
  338. " VSTATUS=0x%02x"
  339. #endif
  340. ,
  341. VALCC(VINTR), VALCC(VQUIT), VALCC(VERASE), VALCC(VKILL),
  342. VALCC(VEOF), VALCC(VMIN), VALCC(VEOL), VALCC(VTIME),
  343. VALCC(VEOL2),
  344. #ifdef VSWTCH
  345. VALCC(VSWTCH),
  346. #endif
  347. VALCC(VSTART), VALCC(VSTOP), VALCC(VSUSP),
  348. #ifdef VDSUSP
  349. VALCC(VDSUSP),
  350. #endif
  351. VALCC(VLNEXT), VALCC(VWERASE),
  352. VALCC(VREPRINT), VALCC(VDISCARD)
  353. #ifdef VSTATUS
  354. ,VALCC(VSTATUS)
  355. #endif
  356. );
  357. }
  358. #endif
  359. #endif
  360. int serial_open_ex(const char *devpath, unsigned long baud, signed short timeout, signed short __maybe_unused minbytes, bool purge, bool __maybe_unused win32overlapped)
  361. {
  362. #ifdef WIN32
  363. HANDLE hSerial = CreateFile(devpath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, (win32overlapped) ? FILE_FLAG_OVERLAPPED : 0, NULL);
  364. if (unlikely(hSerial == INVALID_HANDLE_VALUE))
  365. {
  366. DWORD e = GetLastError();
  367. switch (e) {
  368. case ERROR_ACCESS_DENIED:
  369. applog(LOG_ERR, "Do not have user privileges required to open %s", devpath);
  370. break;
  371. case ERROR_SHARING_VIOLATION:
  372. applog(LOG_ERR, "%s is already in use by another process", devpath);
  373. break;
  374. default:
  375. applog(LOG_DEBUG, "Open %s failed, GetLastError:%d", devpath, (int)e);
  376. break;
  377. }
  378. return -1;
  379. }
  380. // thanks to af_newbie for pointers about this
  381. COMMCONFIG comCfg = {0};
  382. comCfg.dwSize = sizeof(COMMCONFIG);
  383. comCfg.wVersion = 1;
  384. comCfg.dcb.DCBlength = sizeof(DCB);
  385. comCfg.dcb.BaudRate = baud;
  386. comCfg.dcb.fBinary = 1;
  387. comCfg.dcb.fDtrControl = DTR_CONTROL_ENABLE;
  388. comCfg.dcb.fRtsControl = RTS_CONTROL_ENABLE;
  389. comCfg.dcb.ByteSize = 8;
  390. SetCommConfig(hSerial, &comCfg, sizeof(comCfg));
  391. // Code must specify a valid timeout value (0 means don't timeout)
  392. const DWORD ctoms = (timeout * 100);
  393. COMMTIMEOUTS cto = {ctoms, 0, ctoms, 0, ctoms};
  394. SetCommTimeouts(hSerial, &cto);
  395. if (purge) {
  396. PurgeComm(hSerial, PURGE_RXABORT);
  397. PurgeComm(hSerial, PURGE_TXABORT);
  398. PurgeComm(hSerial, PURGE_RXCLEAR);
  399. PurgeComm(hSerial, PURGE_TXCLEAR);
  400. }
  401. return _open_osfhandle((intptr_t)hSerial, 0);
  402. #else
  403. int fdDev = open(devpath, O_RDWR | O_CLOEXEC | O_NOCTTY);
  404. if (unlikely(fdDev == -1))
  405. {
  406. if (errno == EACCES)
  407. applog(LOG_ERR, "Do not have user privileges required to open %s", devpath);
  408. else
  409. applog(LOG_DEBUG, "Open %s failed, errno:%d", devpath, errno);
  410. return -1;
  411. }
  412. struct termios my_termios;
  413. tcgetattr(fdDev, &my_termios);
  414. #ifdef TERMIOS_DEBUG
  415. termios_debug(devpath, &my_termios, "before");
  416. #endif
  417. switch (baud) {
  418. case 0:
  419. break;
  420. case 19200:
  421. cfsetispeed(&my_termios, B19200);
  422. cfsetospeed(&my_termios, B19200);
  423. break;
  424. case 38400:
  425. cfsetispeed(&my_termios, B38400);
  426. cfsetospeed(&my_termios, B38400);
  427. break;
  428. case 57600:
  429. cfsetispeed(&my_termios, B57600);
  430. cfsetospeed(&my_termios, B57600);
  431. break;
  432. case 115200:
  433. cfsetispeed(&my_termios, B115200);
  434. cfsetospeed(&my_termios, B115200);
  435. break;
  436. // TODO: try some higher speeds with the Icarus and BFL to see
  437. // if they support them and if setting them makes any difference
  438. // N.B. B3000000 doesn't work on Icarus
  439. default:
  440. applog(LOG_WARNING, "Unrecognized baud rate: %lu", baud);
  441. }
  442. my_termios.c_cflag &= ~(CSIZE | PARENB);
  443. my_termios.c_cflag |= CS8;
  444. my_termios.c_cflag |= CREAD;
  445. my_termios.c_cflag |= CLOCAL;
  446. my_termios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK |
  447. ISTRIP | INLCR | IGNCR | ICRNL | IXON);
  448. my_termios.c_oflag &= ~OPOST;
  449. my_termios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
  450. // Code must specify a valid timeout value (0 means don't timeout)
  451. my_termios.c_cc[VTIME] = (cc_t)timeout;
  452. my_termios.c_cc[VMIN] = (cc_t)minbytes;
  453. #ifdef TERMIOS_DEBUG
  454. termios_debug(devpath, &my_termios, "settings");
  455. #endif
  456. tcsetattr(fdDev, TCSANOW, &my_termios);
  457. #ifdef TERMIOS_DEBUG
  458. tcgetattr(fdDev, &my_termios);
  459. termios_debug(devpath, &my_termios, "after");
  460. #endif
  461. if (purge)
  462. tcflush(fdDev, TCIOFLUSH);
  463. return fdDev;
  464. #endif
  465. }
  466. ssize_t _serial_read(int fd, char *buf, size_t bufsiz, char *eol)
  467. {
  468. ssize_t len, tlen = 0;
  469. while (bufsiz) {
  470. len = read(fd, buf, eol ? 1 : bufsiz);
  471. if (unlikely(len == -1))
  472. break;
  473. tlen += len;
  474. if (eol && *eol == buf[0])
  475. break;
  476. buf += len;
  477. bufsiz -= len;
  478. }
  479. return tlen;
  480. }
  481. static FILE *_open_bitstream(const char *path, const char *subdir, const char *filename)
  482. {
  483. char fullpath[PATH_MAX];
  484. strcpy(fullpath, path);
  485. strcat(fullpath, "/");
  486. if (subdir) {
  487. strcat(fullpath, subdir);
  488. strcat(fullpath, "/");
  489. }
  490. strcat(fullpath, filename);
  491. return fopen(fullpath, "rb");
  492. }
  493. #define _open_bitstream(path, subdir) do { \
  494. f = _open_bitstream(path, subdir, filename); \
  495. if (f) \
  496. return f; \
  497. } while(0)
  498. #define _open_bitstream3(path) do { \
  499. _open_bitstream(path, dname); \
  500. _open_bitstream(path, "bitstreams"); \
  501. _open_bitstream(path, NULL); \
  502. } while(0)
  503. FILE *open_bitstream(const char *dname, const char *filename)
  504. {
  505. FILE *f;
  506. _open_bitstream3(opt_kernel_path);
  507. _open_bitstream3(cgminer_path);
  508. _open_bitstream3(".");
  509. return NULL;
  510. }
  511. #ifndef WIN32
  512. static bool _select_wait_read(int fd, struct timeval *timeout)
  513. {
  514. fd_set rfds;
  515. FD_ZERO(&rfds);
  516. FD_SET(fd, &rfds);
  517. if (select(fd+1, &rfds, NULL, NULL, timeout) > 0)
  518. return true;
  519. else
  520. return false;
  521. }
  522. // Default timeout 100ms - only for device initialisation
  523. const struct timeval tv_timeout_default = { 0, 100000 };
  524. // Default inter character timeout = 1ms - only for device initialisation
  525. const struct timeval tv_inter_char_default = { 0, 1000 };
  526. // Device initialisation function - NOT for work processing
  527. size_t _select_read(int fd, char *buf, size_t bufsiz, struct timeval *timeout, struct timeval *char_timeout, int finished)
  528. {
  529. struct timeval tv_time, tv_char;
  530. ssize_t siz, red = 0;
  531. char got;
  532. // timeout is the maximum time to wait for the first character
  533. tv_time.tv_sec = timeout->tv_sec;
  534. tv_time.tv_usec = timeout->tv_usec;
  535. if (!_select_wait_read(fd, &tv_time))
  536. return 0;
  537. while (4242) {
  538. if ((siz = read(fd, buf, 1)) < 0)
  539. return red;
  540. got = *buf;
  541. buf += siz;
  542. red += siz;
  543. bufsiz -= siz;
  544. if (bufsiz < 1 || (finished >= 0 && got == finished))
  545. return red;
  546. // char_timeout is the maximum time to wait for each subsequent character
  547. // this is OK for initialisation, but bad for work processing
  548. // work processing MUST have a fixed size so this doesn't come into play
  549. tv_char.tv_sec = char_timeout->tv_sec;
  550. tv_char.tv_usec = char_timeout->tv_usec;
  551. if (!_select_wait_read(fd, &tv_char))
  552. return red;
  553. }
  554. return red;
  555. }
  556. // Device initialisation function - NOT for work processing
  557. size_t _select_write(int fd, char *buf, size_t siz, struct timeval *timeout)
  558. {
  559. struct timeval tv_time, tv_now, tv_finish;
  560. fd_set rfds;
  561. ssize_t wrote = 0, ret;
  562. cgtime(&tv_now);
  563. timeradd(&tv_now, timeout, &tv_finish);
  564. // timeout is the maximum time to spend trying to write
  565. tv_time.tv_sec = timeout->tv_sec;
  566. tv_time.tv_usec = timeout->tv_usec;
  567. FD_ZERO(&rfds);
  568. FD_SET(fd, &rfds);
  569. while (siz > 0 && (tv_now.tv_sec < tv_finish.tv_sec || (tv_now.tv_sec == tv_finish.tv_sec && tv_now.tv_usec < tv_finish.tv_usec)) && select(fd+1, NULL, &rfds, NULL, &tv_time) > 0) {
  570. if ((ret = write(fd, buf, 1)) > 0) {
  571. buf++;
  572. wrote++;
  573. siz--;
  574. }
  575. else if (ret < 0)
  576. return wrote;
  577. cgtime(&tv_now);
  578. }
  579. return wrote;
  580. }
  581. int get_serial_cts(int fd)
  582. {
  583. int flags;
  584. if (!fd)
  585. return -1;
  586. ioctl(fd, TIOCMGET, &flags);
  587. return (flags & TIOCM_CTS) ? 1 : 0;
  588. }
  589. #else
  590. int get_serial_cts(const int fd)
  591. {
  592. if (!fd)
  593. return -1;
  594. const HANDLE fh = (HANDLE)_get_osfhandle(fd);
  595. if (!fh)
  596. return -1;
  597. DWORD flags;
  598. if (!GetCommModemStatus(fh, &flags))
  599. return -1;
  600. return (flags & MS_CTS_ON) ? 1 : 0;
  601. }
  602. #endif // ! WIN32