serial.c 25 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  1. /*
  2. * This file is part of the libsigrok project.
  3. *
  4. * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
  5. * Copyright (C) 2010-2012 Uwe Hermann <uwe@hermann-uwe.de>
  6. * Copyright (C) 2012 Alexandru Gagniuc <mr.nuke.me@gmail.com>
  7. * Copyright (C) 2014 Uffe Jakobsen <uffe@uffe.org>
  8. *
  9. * This program is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation, either version 3 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  21. */
  22. #include <config.h>
  23. #include <string.h>
  24. #include <stdlib.h>
  25. #include <glib.h>
  26. #include <glib/gstdio.h>
  27. #include <libserialport.h>
  28. #include <libsigrok/libsigrok.h>
  29. #include "libsigrok-internal.h"
  30. #ifdef G_OS_WIN32
  31. #include <windows.h> /* for HANDLE */
  32. #endif
  33. /** @cond PRIVATE */
  34. #define LOG_PREFIX "serial"
  35. /** @endcond */
  36. /**
  37. * @file
  38. *
  39. * Serial port handling.
  40. */
  41. /**
  42. * @defgroup grp_serial Serial port handling
  43. *
  44. * Serial port handling functions.
  45. *
  46. * @{
  47. */
  48. /**
  49. * Open the specified serial port.
  50. *
  51. * @param serial Previously initialized serial port structure.
  52. * @param[in] flags Flags to use when opening the serial port. Possible flags
  53. * include SERIAL_RDWR, SERIAL_RDONLY.
  54. *
  55. * If the serial structure contains a serialcomm string, it will be
  56. * passed to serial_set_paramstr() after the port is opened.
  57. *
  58. * @retval SR_OK Success.
  59. * @retval SR_ERR Failure.
  60. *
  61. * @private
  62. */
  63. SR_PRIV int serial_open(struct sr_serial_dev_inst *serial, int flags)
  64. {
  65. int ret;
  66. char *error;
  67. int sp_flags = 0;
  68. if (!serial) {
  69. sr_dbg("Invalid serial port.");
  70. return SR_ERR;
  71. }
  72. sr_spew("Opening serial port '%s' (flags %d).", serial->port, flags);
  73. sp_get_port_by_name(serial->port, &serial->data);
  74. if (flags & SERIAL_RDWR)
  75. sp_flags = (SP_MODE_READ | SP_MODE_WRITE);
  76. else if (flags & SERIAL_RDONLY)
  77. sp_flags = SP_MODE_READ;
  78. ret = sp_open(serial->data, sp_flags);
  79. switch (ret) {
  80. case SP_ERR_ARG:
  81. sr_err("Attempt to open serial port with invalid parameters.");
  82. return SR_ERR_ARG;
  83. case SP_ERR_FAIL:
  84. error = sp_last_error_message();
  85. sr_err("Error opening port (%d): %s.",
  86. sp_last_error_code(), error);
  87. sp_free_error_message(error);
  88. return SR_ERR;
  89. }
  90. if (serial->serialcomm)
  91. return serial_set_paramstr(serial, serial->serialcomm);
  92. else
  93. return SR_OK;
  94. }
  95. /**
  96. * Close the specified serial port.
  97. *
  98. * @param serial Previously initialized serial port structure.
  99. *
  100. * @retval SR_OK Success.
  101. * @retval SR_ERR Failure.
  102. *
  103. * @private
  104. */
  105. SR_PRIV int serial_close(struct sr_serial_dev_inst *serial)
  106. {
  107. int ret;
  108. char *error;
  109. if (!serial) {
  110. sr_dbg("Invalid serial port.");
  111. return SR_ERR;
  112. }
  113. if (!serial->data) {
  114. sr_dbg("Cannot close unopened serial port %s.", serial->port);
  115. return SR_ERR;
  116. }
  117. sr_spew("Closing serial port %s.", serial->port);
  118. ret = sp_close(serial->data);
  119. switch (ret) {
  120. case SP_ERR_ARG:
  121. sr_err("Attempt to close an invalid serial port.");
  122. return SR_ERR_ARG;
  123. case SP_ERR_FAIL:
  124. error = sp_last_error_message();
  125. sr_err("Error closing port (%d): %s.",
  126. sp_last_error_code(), error);
  127. sp_free_error_message(error);
  128. return SR_ERR;
  129. }
  130. sp_free_port(serial->data);
  131. serial->data = NULL;
  132. return SR_OK;
  133. }
  134. /**
  135. * Flush serial port buffers.
  136. *
  137. * @param serial Previously initialized serial port structure.
  138. *
  139. * @retval SR_OK Success.
  140. * @retval SR_ERR Failure.
  141. *
  142. * @private
  143. */
  144. SR_PRIV int serial_flush(struct sr_serial_dev_inst *serial)
  145. {
  146. int ret;
  147. char *error;
  148. if (!serial) {
  149. sr_dbg("Invalid serial port.");
  150. return SR_ERR;
  151. }
  152. if (!serial->data) {
  153. sr_dbg("Cannot flush unopened serial port %s.", serial->port);
  154. return SR_ERR;
  155. }
  156. sr_spew("Flushing serial port %s.", serial->port);
  157. ret = sp_flush(serial->data, SP_BUF_BOTH);
  158. switch (ret) {
  159. case SP_ERR_ARG:
  160. sr_err("Attempt to flush an invalid serial port.");
  161. return SR_ERR_ARG;
  162. case SP_ERR_FAIL:
  163. error = sp_last_error_message();
  164. sr_err("Error flushing port (%d): %s.",
  165. sp_last_error_code(), error);
  166. sp_free_error_message(error);
  167. return SR_ERR;
  168. }
  169. return SR_OK;
  170. }
  171. /**
  172. * Drain serial port buffers.
  173. *
  174. * @param serial Previously initialized serial port structure.
  175. *
  176. * @retval SR_OK Success.
  177. * @retval SR_ERR Failure.
  178. *
  179. * @private
  180. */
  181. SR_PRIV int serial_drain(struct sr_serial_dev_inst *serial)
  182. {
  183. int ret;
  184. char *error;
  185. if (!serial) {
  186. sr_dbg("Invalid serial port.");
  187. return SR_ERR;
  188. }
  189. if (!serial->data) {
  190. sr_dbg("Cannot drain unopened serial port %s.", serial->port);
  191. return SR_ERR;
  192. }
  193. sr_spew("Draining serial port %s.", serial->port);
  194. ret = sp_drain(serial->data);
  195. if (ret == SP_ERR_FAIL) {
  196. error = sp_last_error_message();
  197. sr_err("Error draining port (%d): %s.",
  198. sp_last_error_code(), error);
  199. sp_free_error_message(error);
  200. return SR_ERR;
  201. }
  202. return SR_OK;
  203. }
  204. static int _serial_write(struct sr_serial_dev_inst *serial,
  205. const void *buf, size_t count, int nonblocking, unsigned int timeout_ms)
  206. {
  207. ssize_t ret;
  208. char *error;
  209. if (!serial) {
  210. sr_dbg("Invalid serial port.");
  211. return SR_ERR;
  212. }
  213. if (!serial->data) {
  214. sr_dbg("Cannot use unopened serial port %s.", serial->port);
  215. return SR_ERR;
  216. }
  217. if (nonblocking)
  218. ret = sp_nonblocking_write(serial->data, buf, count);
  219. else
  220. ret = sp_blocking_write(serial->data, buf, count, timeout_ms);
  221. switch (ret) {
  222. case SP_ERR_ARG:
  223. sr_err("Attempted serial port write with invalid arguments.");
  224. return SR_ERR_ARG;
  225. case SP_ERR_FAIL:
  226. error = sp_last_error_message();
  227. sr_err("Write error (%d): %s.", sp_last_error_code(), error);
  228. sp_free_error_message(error);
  229. return SR_ERR;
  230. }
  231. sr_spew("Wrote %zd/%zu bytes.", ret, count);
  232. return ret;
  233. }
  234. /**
  235. * Write a number of bytes to the specified serial port, blocking until finished.
  236. *
  237. * @param serial Previously initialized serial port structure.
  238. * @param[in] buf Buffer containing the bytes to write.
  239. * @param[in] count Number of bytes to write.
  240. * @param[in] timeout_ms Timeout in ms, or 0 for no timeout.
  241. *
  242. * @retval SR_ERR_ARG Invalid argument.
  243. * @retval SR_ERR Other error.
  244. * @retval other The number of bytes written. If this is less than the number
  245. * specified in the call, the timeout was reached.
  246. *
  247. * @private
  248. */
  249. SR_PRIV int serial_write_blocking(struct sr_serial_dev_inst *serial,
  250. const void *buf, size_t count, unsigned int timeout_ms)
  251. {
  252. return _serial_write(serial, buf, count, 0, timeout_ms);
  253. }
  254. /**
  255. * Write a number of bytes to the specified serial port, return immediately.
  256. *
  257. * @param serial Previously initialized serial port structure.
  258. * @param[in] buf Buffer containing the bytes to write.
  259. * @param[in] count Number of bytes to write.
  260. *
  261. * @retval SR_ERR_ARG Invalid argument.
  262. * @retval SR_ERR Other error.
  263. * @retval other The number of bytes written.
  264. *
  265. * @private
  266. */
  267. SR_PRIV int serial_write_nonblocking(struct sr_serial_dev_inst *serial,
  268. const void *buf, size_t count)
  269. {
  270. return _serial_write(serial, buf, count, 1, 0);
  271. }
  272. static int _serial_read(struct sr_serial_dev_inst *serial, void *buf,
  273. size_t count, int nonblocking, unsigned int timeout_ms)
  274. {
  275. ssize_t ret;
  276. char *error;
  277. if (!serial) {
  278. sr_dbg("Invalid serial port.");
  279. return SR_ERR;
  280. }
  281. if (!serial->data) {
  282. sr_dbg("Cannot use unopened serial port %s.", serial->port);
  283. return SR_ERR;
  284. }
  285. if (nonblocking)
  286. ret = sp_nonblocking_read(serial->data, buf, count);
  287. else
  288. ret = sp_blocking_read(serial->data, buf, count, timeout_ms);
  289. switch (ret) {
  290. case SP_ERR_ARG:
  291. sr_err("Attempted serial port read with invalid arguments.");
  292. return SR_ERR_ARG;
  293. case SP_ERR_FAIL:
  294. error = sp_last_error_message();
  295. sr_err("Read error (%d): %s.", sp_last_error_code(), error);
  296. sp_free_error_message(error);
  297. return SR_ERR;
  298. }
  299. if (ret > 0)
  300. sr_spew("Read %zd/%zu bytes.", ret, count);
  301. return ret;
  302. }
  303. /**
  304. * Read a number of bytes from the specified serial port, block until finished.
  305. *
  306. * @param serial Previously initialized serial port structure.
  307. * @param buf Buffer where to store the bytes that are read.
  308. * @param[in] count The number of bytes to read.
  309. * @param[in] timeout_ms Timeout in ms, or 0 for no timeout.
  310. *
  311. * @retval SR_ERR_ARG Invalid argument.
  312. * @retval SR_ERR Other error.
  313. * @retval other The number of bytes read. If this is less than the number
  314. * requested, the timeout was reached.
  315. *
  316. * @private
  317. */
  318. SR_PRIV int serial_read_blocking(struct sr_serial_dev_inst *serial, void *buf,
  319. size_t count, unsigned int timeout_ms)
  320. {
  321. return _serial_read(serial, buf, count, 0, timeout_ms);
  322. }
  323. /**
  324. * Try to read up to @a count bytes from the specified serial port, return
  325. * immediately with what's available.
  326. *
  327. * @param serial Previously initialized serial port structure.
  328. * @param buf Buffer where to store the bytes that are read.
  329. * @param[in] count The number of bytes to read.
  330. *
  331. * @retval SR_ERR_ARG Invalid argument.
  332. * @retval SR_ERR Other error.
  333. * @retval other The number of bytes read.
  334. *
  335. * @private
  336. */
  337. SR_PRIV int serial_read_nonblocking(struct sr_serial_dev_inst *serial, void *buf,
  338. size_t count)
  339. {
  340. return _serial_read(serial, buf, count, 1, 0);
  341. }
  342. /**
  343. * Set serial parameters for the specified serial port.
  344. *
  345. * @param serial Previously initialized serial port structure.
  346. * @param[in] baudrate The baudrate to set.
  347. * @param[in] bits The number of data bits to use (5, 6, 7 or 8).
  348. * @param[in] parity The parity setting to use (0 = none, 1 = even, 2 = odd).
  349. * @param[in] stopbits The number of stop bits to use (1 or 2).
  350. * @param[in] flowcontrol The flow control settings to use (0 = none,
  351. * 1 = RTS/CTS, 2 = XON/XOFF).
  352. * @param[in] rts Status of RTS line (0 or 1; required by some interfaces).
  353. * @param[in] dtr Status of DTR line (0 or 1; required by some interfaces).
  354. *
  355. * @retval SR_OK Success.
  356. * @retval SR_ERR Failure.
  357. *
  358. * @private
  359. */
  360. SR_PRIV int serial_set_params(struct sr_serial_dev_inst *serial, int baudrate,
  361. int bits, int parity, int stopbits,
  362. int flowcontrol, int rts, int dtr)
  363. {
  364. int ret;
  365. char *error;
  366. struct sp_port_config *config;
  367. if (!serial) {
  368. sr_dbg("Invalid serial port.");
  369. return SR_ERR;
  370. }
  371. if (!serial->data) {
  372. sr_dbg("Cannot configure unopened serial port %s.", serial->port);
  373. return SR_ERR;
  374. }
  375. sr_spew("Setting serial parameters on port %s.", serial->port);
  376. sp_new_config(&config);
  377. sp_set_config_baudrate(config, baudrate);
  378. sp_set_config_bits(config, bits);
  379. switch (parity) {
  380. case 0:
  381. sp_set_config_parity(config, SP_PARITY_NONE);
  382. break;
  383. case 1:
  384. sp_set_config_parity(config, SP_PARITY_EVEN);
  385. break;
  386. case 2:
  387. sp_set_config_parity(config, SP_PARITY_ODD);
  388. break;
  389. default:
  390. return SR_ERR_ARG;
  391. }
  392. sp_set_config_stopbits(config, stopbits);
  393. sp_set_config_rts(config, flowcontrol == 1 ? SP_RTS_FLOW_CONTROL : rts);
  394. sp_set_config_cts(config, flowcontrol == 1 ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE);
  395. sp_set_config_dtr(config, dtr);
  396. sp_set_config_dsr(config, SP_DSR_IGNORE);
  397. sp_set_config_xon_xoff(config, flowcontrol == 2 ? SP_XONXOFF_INOUT : SP_XONXOFF_DISABLED);
  398. ret = sp_set_config(serial->data, config);
  399. sp_free_config(config);
  400. switch (ret) {
  401. case SP_ERR_ARG:
  402. sr_err("Invalid arguments for setting serial port parameters.");
  403. return SR_ERR_ARG;
  404. case SP_ERR_FAIL:
  405. error = sp_last_error_message();
  406. sr_err("Error setting serial port parameters (%d): %s.",
  407. sp_last_error_code(), error);
  408. sp_free_error_message(error);
  409. return SR_ERR;
  410. }
  411. return SR_OK;
  412. }
  413. /**
  414. * Set serial parameters for the specified serial port from parameter string.
  415. *
  416. * @param serial Previously initialized serial port structure.
  417. * @param[in] paramstr A serial communication parameters string of the form
  418. * "<baudrate>/<bits><parity><stopbits>{/<option>}".\n
  419. * Examples: "9600/8n1", "600/7o2/dtr=1/rts=0" or "460800/8n1/flow=2".\n
  420. * \<baudrate\>=integer Baud rate.\n
  421. * \<bits\>=5|6|7|8 Number of data bits.\n
  422. * \<parity\>=n|e|o None, even, odd.\n
  423. * \<stopbits\>=1|2 One or two stop bits.\n
  424. * Options:\n
  425. * dtr=0|1 Set DTR off resp. on.\n
  426. * flow=0|1|2 Flow control. 0 for none, 1 for RTS/CTS, 2 for XON/XOFF.\n
  427. * rts=0|1 Set RTS off resp. on.\n
  428. * Please note that values and combinations of these parameters must be
  429. * supported by the concrete serial interface hardware and the drivers for it.
  430. *
  431. * @retval SR_OK Success.
  432. * @retval SR_ERR Failure.
  433. *
  434. * @private
  435. */
  436. SR_PRIV int serial_set_paramstr(struct sr_serial_dev_inst *serial,
  437. const char *paramstr)
  438. {
  439. /** @cond PRIVATE */
  440. #define SERIAL_COMM_SPEC "^(\\d+)/([5678])([neo])([12])(.*)$"
  441. /** @endcond */
  442. GRegex *reg;
  443. GMatchInfo *match;
  444. int speed, databits, parity, stopbits, flow, rts, dtr, i;
  445. char *mstr, **opts, **kv;
  446. speed = databits = parity = stopbits = flow = 0;
  447. rts = dtr = -1;
  448. sr_spew("Parsing parameters from \"%s\".", paramstr);
  449. reg = g_regex_new(SERIAL_COMM_SPEC, 0, 0, NULL);
  450. if (g_regex_match(reg, paramstr, 0, &match)) {
  451. if ((mstr = g_match_info_fetch(match, 1)))
  452. speed = strtoul(mstr, NULL, 10);
  453. g_free(mstr);
  454. if ((mstr = g_match_info_fetch(match, 2)))
  455. databits = strtoul(mstr, NULL, 10);
  456. g_free(mstr);
  457. if ((mstr = g_match_info_fetch(match, 3))) {
  458. switch (mstr[0]) {
  459. case 'n':
  460. parity = SP_PARITY_NONE;
  461. break;
  462. case 'e':
  463. parity = SP_PARITY_EVEN;
  464. break;
  465. case 'o':
  466. parity = SP_PARITY_ODD;
  467. break;
  468. }
  469. }
  470. g_free(mstr);
  471. if ((mstr = g_match_info_fetch(match, 4)))
  472. stopbits = strtoul(mstr, NULL, 10);
  473. g_free(mstr);
  474. if ((mstr = g_match_info_fetch(match, 5)) && mstr[0] != '\0') {
  475. if (mstr[0] != '/') {
  476. sr_dbg("missing separator before extra options");
  477. speed = 0;
  478. } else {
  479. /* A set of "key=value" options separated by / */
  480. opts = g_strsplit(mstr + 1, "/", 0);
  481. for (i = 0; opts[i]; i++) {
  482. kv = g_strsplit(opts[i], "=", 2);
  483. if (!strncmp(kv[0], "rts", 3)) {
  484. if (kv[1][0] == '1')
  485. rts = 1;
  486. else if (kv[1][0] == '0')
  487. rts = 0;
  488. else {
  489. sr_dbg("invalid value for rts: %c", kv[1][0]);
  490. speed = 0;
  491. }
  492. } else if (!strncmp(kv[0], "dtr", 3)) {
  493. if (kv[1][0] == '1')
  494. dtr = 1;
  495. else if (kv[1][0] == '0')
  496. dtr = 0;
  497. else {
  498. sr_dbg("invalid value for dtr: %c", kv[1][0]);
  499. speed = 0;
  500. }
  501. } else if (!strncmp(kv[0], "flow", 4)) {
  502. if (kv[1][0] == '0')
  503. flow = 0;
  504. else if (kv[1][0] == '1')
  505. flow = 1;
  506. else if (kv[1][0] == '2')
  507. flow = 2;
  508. else {
  509. sr_dbg("invalid value for flow: %c", kv[1][0]);
  510. speed = 0;
  511. }
  512. }
  513. g_strfreev(kv);
  514. }
  515. g_strfreev(opts);
  516. }
  517. }
  518. g_free(mstr);
  519. }
  520. g_match_info_unref(match);
  521. g_regex_unref(reg);
  522. if (speed) {
  523. return serial_set_params(serial, speed, databits, parity,
  524. stopbits, flow, rts, dtr);
  525. } else {
  526. sr_dbg("Could not infer speed from parameter string.");
  527. return SR_ERR_ARG;
  528. }
  529. }
  530. /**
  531. * Read a line from the specified serial port.
  532. *
  533. * @param serial Previously initialized serial port structure.
  534. * @param buf Buffer where to store the bytes that are read.
  535. * @param buflen Size of the buffer.
  536. * @param[in] timeout_ms How long to wait for a line to come in.
  537. *
  538. * Reading stops when CR of LR is found, which is stripped from the buffer.
  539. *
  540. * @retval SR_OK Success.
  541. * @retval SR_ERR Failure.
  542. *
  543. * @private
  544. */
  545. SR_PRIV int serial_readline(struct sr_serial_dev_inst *serial, char **buf,
  546. int *buflen, gint64 timeout_ms)
  547. {
  548. gint64 start, remaining;
  549. int maxlen, len;
  550. if (!serial) {
  551. sr_dbg("Invalid serial port.");
  552. return SR_ERR;
  553. }
  554. if (!serial->data) {
  555. sr_dbg("Cannot use unopened serial port %s.", serial->port);
  556. return -1;
  557. }
  558. start = g_get_monotonic_time();
  559. remaining = timeout_ms;
  560. maxlen = *buflen;
  561. *buflen = len = 0;
  562. while (1) {
  563. len = maxlen - *buflen - 1;
  564. if (len < 1)
  565. break;
  566. len = sp_blocking_read(serial->data, *buf + *buflen, 1, remaining);
  567. if (len > 0) {
  568. *buflen += len;
  569. *(*buf + *buflen) = '\0';
  570. if (*buflen > 0 && (*(*buf + *buflen - 1) == '\r'
  571. || *(*buf + *buflen - 1) == '\n')) {
  572. /* Strip CR/LF and terminate. */
  573. *(*buf + --*buflen) = '\0';
  574. break;
  575. }
  576. }
  577. /* Reduce timeout by time elapsed. */
  578. remaining = timeout_ms - ((g_get_monotonic_time() - start) / 1000);
  579. if (remaining <= 0)
  580. /* Timeout */
  581. break;
  582. if (len < 1)
  583. g_usleep(2000);
  584. }
  585. if (*buflen)
  586. sr_dbg("Received %d: '%s'.", *buflen, *buf);
  587. return SR_OK;
  588. }
  589. /**
  590. * Try to find a valid packet in a serial data stream.
  591. *
  592. * @param serial Previously initialized serial port structure.
  593. * @param buf Buffer containing the bytes to write.
  594. * @param buflen Size of the buffer.
  595. * @param[in] packet_size Size, in bytes, of a valid packet.
  596. * @param is_valid Callback that assesses whether the packet is valid or not.
  597. * @param[in] timeout_ms The timeout after which, if no packet is detected, to
  598. * abort scanning.
  599. * @param[in] baudrate The baudrate of the serial port. This parameter is not
  600. * critical, but it helps fine tune the serial port polling
  601. * delay.
  602. *
  603. * @retval SR_OK Valid packet was found within the given timeout.
  604. * @retval SR_ERR Failure.
  605. *
  606. * @private
  607. */
  608. SR_PRIV int serial_stream_detect(struct sr_serial_dev_inst *serial,
  609. uint8_t *buf, size_t *buflen,
  610. size_t packet_size,
  611. packet_valid_callback is_valid,
  612. uint64_t timeout_ms, int baudrate)
  613. {
  614. uint64_t start, time, byte_delay_us;
  615. size_t ibuf, i, maxlen;
  616. ssize_t len;
  617. maxlen = *buflen;
  618. sr_dbg("Detecting packets on %s (timeout = %" PRIu64
  619. "ms, baudrate = %d).", serial->port, timeout_ms, baudrate);
  620. if (maxlen < (packet_size / 2) ) {
  621. sr_err("Buffer size must be at least twice the packet size.");
  622. return SR_ERR;
  623. }
  624. /* Assume 8n1 transmission. That is 10 bits for every byte. */
  625. byte_delay_us = 10 * ((1000 * 1000) / baudrate);
  626. start = g_get_monotonic_time();
  627. i = ibuf = len = 0;
  628. while (ibuf < maxlen) {
  629. len = serial_read_nonblocking(serial, &buf[ibuf], 1);
  630. if (len > 0) {
  631. ibuf += len;
  632. } else if (len == 0) {
  633. /* No logging, already done in serial_read(). */
  634. } else {
  635. /* Error reading byte, but continuing anyway. */
  636. }
  637. time = g_get_monotonic_time() - start;
  638. time /= 1000;
  639. if ((ibuf - i) >= packet_size) {
  640. /* We have at least a packet's worth of data. */
  641. if (is_valid(&buf[i])) {
  642. sr_spew("Found valid %zu-byte packet after "
  643. "%" PRIu64 "ms.", (ibuf - i), time);
  644. *buflen = ibuf;
  645. return SR_OK;
  646. } else {
  647. sr_spew("Got %zu bytes, but not a valid "
  648. "packet.", (ibuf - i));
  649. }
  650. /* Not a valid packet. Continue searching. */
  651. i++;
  652. }
  653. if (time >= timeout_ms) {
  654. /* Timeout */
  655. sr_dbg("Detection timed out after %" PRIu64 "ms.", time);
  656. break;
  657. }
  658. if (len < 1)
  659. g_usleep(byte_delay_us);
  660. }
  661. *buflen = ibuf;
  662. sr_err("Didn't find a valid packet (read %zu bytes).", *buflen);
  663. return SR_ERR;
  664. }
  665. /**
  666. * Extract the serial device and options from the options linked list.
  667. *
  668. * @param options List of options passed from the command line.
  669. * @param serial_device Pointer where to store the extracted serial device.
  670. * @param serial_options Pointer where to store the optional extracted serial
  671. * options.
  672. *
  673. * @return SR_OK if a serial_device is found, SR_ERR if no device is found. The
  674. * returned string should not be freed by the caller.
  675. *
  676. * @private
  677. */
  678. SR_PRIV int sr_serial_extract_options(GSList *options, const char **serial_device,
  679. const char **serial_options)
  680. {
  681. GSList *l;
  682. struct sr_config *src;
  683. *serial_device = NULL;
  684. for (l = options; l; l = l->next) {
  685. src = l->data;
  686. switch (src->key) {
  687. case SR_CONF_CONN:
  688. *serial_device = g_variant_get_string(src->data, NULL);
  689. sr_dbg("Parsed serial device: %s.", *serial_device);
  690. break;
  691. case SR_CONF_SERIALCOMM:
  692. *serial_options = g_variant_get_string(src->data, NULL);
  693. sr_dbg("Parsed serial options: %s.", *serial_options);
  694. break;
  695. }
  696. }
  697. if (!*serial_device) {
  698. sr_dbg("No serial device specified.");
  699. return SR_ERR;
  700. }
  701. return SR_OK;
  702. }
  703. /** @cond PRIVATE */
  704. #ifdef G_OS_WIN32
  705. typedef HANDLE event_handle;
  706. #else
  707. typedef int event_handle;
  708. #endif
  709. /** @endcond */
  710. /** @private */
  711. SR_PRIV int serial_source_add(struct sr_session *session,
  712. struct sr_serial_dev_inst *serial, int events, int timeout,
  713. sr_receive_data_callback cb, void *cb_data)
  714. {
  715. struct sp_event_set *event_set;
  716. gintptr poll_fd;
  717. unsigned int poll_events;
  718. enum sp_event mask = 0;
  719. if ((events & (G_IO_IN|G_IO_ERR)) && (events & G_IO_OUT)) {
  720. sr_err("Cannot poll input/error and output simultaneously.");
  721. return SR_ERR_ARG;
  722. }
  723. if (sp_new_event_set(&event_set) != SP_OK)
  724. return SR_ERR;
  725. if (events & G_IO_IN)
  726. mask |= SP_EVENT_RX_READY;
  727. if (events & G_IO_OUT)
  728. mask |= SP_EVENT_TX_READY;
  729. if (events & G_IO_ERR)
  730. mask |= SP_EVENT_ERROR;
  731. if (sp_add_port_events(event_set, serial->data, mask) != SP_OK) {
  732. sp_free_event_set(event_set);
  733. return SR_ERR;
  734. }
  735. if (event_set->count != 1) {
  736. sr_err("Unexpected number (%u) of event handles to poll.",
  737. event_set->count);
  738. sp_free_event_set(event_set);
  739. return SR_ERR;
  740. }
  741. poll_fd = (gintptr) ((event_handle *)event_set->handles)[0];
  742. mask = event_set->masks[0];
  743. sp_free_event_set(event_set);
  744. poll_events = 0;
  745. if (mask & SP_EVENT_RX_READY)
  746. poll_events |= G_IO_IN;
  747. if (mask & SP_EVENT_TX_READY)
  748. poll_events |= G_IO_OUT;
  749. if (mask & SP_EVENT_ERROR)
  750. poll_events |= G_IO_ERR;
  751. /*
  752. * Using serial->data as the key for the event source is not quite
  753. * proper, as it makes it impossible to create another event source
  754. * for the same serial port. However, these fixed keys will soon be
  755. * removed from the API anyway, so this is OK for now.
  756. */
  757. return sr_session_fd_source_add(session, serial->data,
  758. poll_fd, poll_events, timeout, cb, cb_data);
  759. }
  760. /** @private */
  761. SR_PRIV int serial_source_remove(struct sr_session *session,
  762. struct sr_serial_dev_inst *serial)
  763. {
  764. return sr_session_source_remove_internal(session, serial->data);
  765. }
  766. /**
  767. * Create/allocate a new sr_serial_port structure.
  768. *
  769. * @param name The OS dependent name of the serial port. Must not be NULL.
  770. * @param description An end user friendly description for the serial port.
  771. * Can be NULL (in that case the empty string is used
  772. * as description).
  773. *
  774. * @return The newly allocated sr_serial_port struct.
  775. */
  776. static struct sr_serial_port *sr_serial_new(const char *name,
  777. const char *description)
  778. {
  779. struct sr_serial_port *serial;
  780. if (!name)
  781. return NULL;
  782. serial = g_malloc(sizeof(struct sr_serial_port));
  783. serial->name = g_strdup(name);
  784. serial->description = g_strdup(description ? description : "");
  785. return serial;
  786. }
  787. /**
  788. * Free a previously allocated sr_serial_port structure.
  789. *
  790. * @param serial The sr_serial_port struct to free. Must not be NULL.
  791. */
  792. SR_API void sr_serial_free(struct sr_serial_port *serial)
  793. {
  794. if (!serial)
  795. return;
  796. g_free(serial->name);
  797. g_free(serial->description);
  798. g_free(serial);
  799. }
  800. /**
  801. * List available serial devices.
  802. *
  803. * @return A GSList of strings containing the path of the serial devices or
  804. * NULL if no serial device is found. The returned list must be freed
  805. * by the caller.
  806. */
  807. SR_API GSList *sr_serial_list(const struct sr_dev_driver *driver)
  808. {
  809. GSList *tty_devs = NULL;
  810. struct sp_port **ports;
  811. struct sr_serial_port *port;
  812. int i;
  813. /* Currently unused, but will be used by some drivers later on. */
  814. (void)driver;
  815. if (sp_list_ports(&ports) != SP_OK)
  816. return NULL;
  817. for (i = 0; ports[i]; i++) {
  818. port = sr_serial_new(sp_get_port_name(ports[i]),
  819. sp_get_port_description(ports[i]));
  820. tty_devs = g_slist_append(tty_devs, port);
  821. }
  822. sp_free_port_list(ports);
  823. return tty_devs;
  824. }
  825. /**
  826. * Find USB serial devices via the USB vendor ID and product ID.
  827. *
  828. * @param[in] vendor_id Vendor ID of the USB device.
  829. * @param[in] product_id Product ID of the USB device.
  830. *
  831. * @return A GSList of strings containing the path of the serial device or
  832. * NULL if no serial device is found. The returned list must be freed
  833. * by the caller.
  834. *
  835. * @private
  836. */
  837. SR_PRIV GSList *sr_serial_find_usb(uint16_t vendor_id, uint16_t product_id)
  838. {
  839. GSList *tty_devs = NULL;
  840. struct sp_port **ports;
  841. int i, vid, pid;
  842. if (sp_list_ports(&ports) != SP_OK)
  843. return NULL;
  844. for (i = 0; ports[i]; i++)
  845. if (sp_get_port_transport(ports[i]) == SP_TRANSPORT_USB &&
  846. sp_get_port_usb_vid_pid(ports[i], &vid, &pid) == SP_OK &&
  847. vid == vendor_id && pid == product_id) {
  848. tty_devs = g_slist_prepend(tty_devs,
  849. g_strdup(sp_get_port_name(ports[i])));
  850. }
  851. sp_free_port_list(ports);
  852. return tty_devs;
  853. }
  854. /** @private */
  855. SR_PRIV int serial_timeout(struct sr_serial_dev_inst *port, int num_bytes)
  856. {
  857. struct sp_port_config *config;
  858. int timeout_ms, bits, baud, tmp;
  859. /* Default to 1s. */
  860. timeout_ms = 1000;
  861. if (sp_new_config(&config) < 0)
  862. return timeout_ms;
  863. bits = baud = 0;
  864. do {
  865. if (sp_get_config(port->data, config) < 0)
  866. break;
  867. /* Start bit. */
  868. bits = 1;
  869. if (sp_get_config_bits(config, &tmp) < 0)
  870. break;
  871. bits += tmp;
  872. if (sp_get_config_stopbits(config, &tmp) < 0)
  873. break;
  874. bits += tmp;
  875. if (sp_get_config_baudrate(config, &tmp) < 0)
  876. break;
  877. baud = tmp;
  878. } while (FALSE);
  879. if (bits && baud) {
  880. /* Throw in 10ms for misc OS overhead. */
  881. timeout_ms = 10;
  882. timeout_ms += ((1000.0 / baud) * bits) * num_bytes;
  883. }
  884. sp_free_config(config);
  885. return timeout_ms;
  886. }
  887. /** @} */