modbus-rtu.c 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220
  1. /*
  2. * Copyright © 2001-2011 Stéphane Raimbault <stephane.raimbault@gmail.com>
  3. *
  4. * SPDX-License-Identifier: LGPL-2.1+
  5. */
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <errno.h>
  9. #include <fcntl.h>
  10. #include <string.h>
  11. #ifndef _MSC_VER
  12. #include <unistd.h>
  13. #endif
  14. #include <assert.h>
  15. #include "modbus-private.h"
  16. #include "modbus-rtu.h"
  17. #include "modbus-rtu-private.h"
  18. #if HAVE_DECL_TIOCSRS485 || HAVE_DECL_TIOCM_RTS
  19. #include <sys/ioctl.h>
  20. #endif
  21. #if HAVE_DECL_TIOCSRS485
  22. #include <linux/serial.h>
  23. #endif
  24. /* Table of CRC values for high-order byte */
  25. static const uint8_t table_crc_hi[] = {
  26. 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
  27. 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
  28. 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
  29. 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
  30. 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
  31. 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
  32. 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
  33. 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
  34. 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
  35. 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
  36. 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
  37. 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
  38. 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
  39. 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
  40. 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
  41. 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
  42. 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
  43. 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
  44. 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
  45. 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
  46. 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
  47. 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
  48. 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
  49. 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
  50. 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
  51. 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
  52. };
  53. /* Table of CRC values for low-order byte */
  54. static const uint8_t table_crc_lo[] = {
  55. 0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06,
  56. 0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD,
  57. 0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
  58. 0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A,
  59. 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4,
  60. 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
  61. 0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3,
  62. 0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4,
  63. 0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
  64. 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29,
  65. 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED,
  66. 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
  67. 0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60,
  68. 0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67,
  69. 0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
  70. 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68,
  71. 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E,
  72. 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
  73. 0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71,
  74. 0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92,
  75. 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
  76. 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B,
  77. 0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B,
  78. 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
  79. 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42,
  80. 0x43, 0x83, 0x41, 0x81, 0x80, 0x40
  81. };
  82. /* Define the slave ID of the remote device to talk in master mode or set the
  83. * internal slave ID in slave mode */
  84. static int _modbus_set_slave(modbus_t *ctx, int slave)
  85. {
  86. /* Broadcast address is 0 (MODBUS_BROADCAST_ADDRESS) */
  87. if (slave >= 0 && slave <= 247) {
  88. ctx->slave = slave;
  89. } else {
  90. errno = EINVAL;
  91. return -1;
  92. }
  93. return 0;
  94. }
  95. /* Builds a RTU request header */
  96. static int _modbus_rtu_build_request_basis(modbus_t *ctx, int function,
  97. int addr, int nb,
  98. uint8_t *req)
  99. {
  100. assert(ctx->slave != -1);
  101. req[0] = ctx->slave;
  102. req[1] = function;
  103. req[2] = addr >> 8;
  104. req[3] = addr & 0x00ff;
  105. req[4] = nb >> 8;
  106. req[5] = nb & 0x00ff;
  107. return _MODBUS_RTU_PRESET_REQ_LENGTH;
  108. }
  109. /* Builds a RTU response header */
  110. static int _modbus_rtu_build_response_basis(sft_t *sft, uint8_t *rsp)
  111. {
  112. /* In this case, the slave is certainly valid because a check is already
  113. * done in _modbus_rtu_listen */
  114. rsp[0] = sft->slave;
  115. rsp[1] = sft->function;
  116. return _MODBUS_RTU_PRESET_RSP_LENGTH;
  117. }
  118. static uint16_t crc16(uint8_t *buffer, uint16_t buffer_length)
  119. {
  120. uint8_t crc_hi = 0xFF; /* high CRC byte initialized */
  121. uint8_t crc_lo = 0xFF; /* low CRC byte initialized */
  122. unsigned int i; /* will index into CRC lookup */
  123. /* pass through message buffer */
  124. while (buffer_length--) {
  125. i = crc_hi ^ *buffer++; /* calculate the CRC */
  126. crc_hi = crc_lo ^ table_crc_hi[i];
  127. crc_lo = table_crc_lo[i];
  128. }
  129. return (crc_hi << 8 | crc_lo);
  130. }
  131. static int _modbus_rtu_prepare_response_tid(const uint8_t *req, int *req_length)
  132. {
  133. (*req_length) -= _MODBUS_RTU_CHECKSUM_LENGTH;
  134. /* No TID */
  135. return 0;
  136. }
  137. static int _modbus_rtu_send_msg_pre(uint8_t *req, int req_length)
  138. {
  139. uint16_t crc = crc16(req, req_length);
  140. req[req_length++] = crc >> 8;
  141. req[req_length++] = crc & 0x00FF;
  142. return req_length;
  143. }
  144. #if defined(_WIN32)
  145. /* This simple implementation is sort of a substitute of the select() call,
  146. * working this way: the win32_ser_select() call tries to read some data from
  147. * the serial port, setting the timeout as the select() call would. Data read is
  148. * stored into the receive buffer, that is then consumed by the win32_ser_read()
  149. * call. So win32_ser_select() does both the event waiting and the reading,
  150. * while win32_ser_read() only consumes the receive buffer.
  151. */
  152. static void win32_ser_init(struct win32_ser *ws)
  153. {
  154. /* Clear everything */
  155. memset(ws, 0x00, sizeof(struct win32_ser));
  156. /* Set file handle to invalid */
  157. ws->fd = INVALID_HANDLE_VALUE;
  158. }
  159. /* FIXME Try to remove length_to_read -> max_len argument, only used by win32 */
  160. static int win32_ser_select(struct win32_ser *ws, int max_len,
  161. const struct timeval *tv)
  162. {
  163. COMMTIMEOUTS comm_to;
  164. unsigned int msec = 0;
  165. /* Check if some data still in the buffer to be consumed */
  166. if (ws->n_bytes > 0) {
  167. return 1;
  168. }
  169. /* Setup timeouts like select() would do.
  170. FIXME Please someone on Windows can look at this?
  171. Does it possible to use WaitCommEvent?
  172. When tv is NULL, MAXDWORD isn't infinite!
  173. */
  174. if (tv == NULL) {
  175. msec = MAXDWORD;
  176. } else {
  177. msec = tv->tv_sec * 1000 + tv->tv_usec / 1000;
  178. if (msec < 1)
  179. msec = 1;
  180. }
  181. comm_to.ReadIntervalTimeout = msec;
  182. comm_to.ReadTotalTimeoutMultiplier = 0;
  183. comm_to.ReadTotalTimeoutConstant = msec;
  184. comm_to.WriteTotalTimeoutMultiplier = 0;
  185. comm_to.WriteTotalTimeoutConstant = 1000;
  186. SetCommTimeouts(ws->fd, &comm_to);
  187. /* Read some bytes */
  188. if ((max_len > PY_BUF_SIZE) || (max_len < 0)) {
  189. max_len = PY_BUF_SIZE;
  190. }
  191. if (ReadFile(ws->fd, &ws->buf, max_len, &ws->n_bytes, NULL)) {
  192. /* Check if some bytes available */
  193. if (ws->n_bytes > 0) {
  194. /* Some bytes read */
  195. return 1;
  196. } else {
  197. /* Just timed out */
  198. return 0;
  199. }
  200. } else {
  201. /* Some kind of error */
  202. return -1;
  203. }
  204. }
  205. static int win32_ser_read(struct win32_ser *ws, uint8_t *p_msg,
  206. unsigned int max_len)
  207. {
  208. unsigned int n = ws->n_bytes;
  209. if (max_len < n) {
  210. n = max_len;
  211. }
  212. if (n > 0) {
  213. memcpy(p_msg, ws->buf, n);
  214. }
  215. ws->n_bytes -= n;
  216. return n;
  217. }
  218. #endif
  219. #if HAVE_DECL_TIOCM_RTS
  220. static void _modbus_rtu_ioctl_rts(modbus_t *ctx, int on)
  221. {
  222. int fd = ctx->s;
  223. int flags;
  224. ioctl(fd, TIOCMGET, &flags);
  225. if (on) {
  226. flags |= TIOCM_RTS;
  227. } else {
  228. flags &= ~TIOCM_RTS;
  229. }
  230. ioctl(fd, TIOCMSET, &flags);
  231. }
  232. #endif
  233. static ssize_t _modbus_rtu_send(modbus_t *ctx, const uint8_t *req, int req_length)
  234. {
  235. #if defined(_WIN32)
  236. modbus_rtu_t *ctx_rtu = ctx->backend_data;
  237. DWORD n_bytes = 0;
  238. return (WriteFile(ctx_rtu->w_ser.fd, req, req_length, &n_bytes, NULL)) ? (ssize_t)n_bytes : -1;
  239. #else
  240. #if HAVE_DECL_TIOCM_RTS
  241. modbus_rtu_t *ctx_rtu = ctx->backend_data;
  242. if (ctx_rtu->rts != MODBUS_RTU_RTS_NONE) {
  243. ssize_t size;
  244. if (ctx->debug) {
  245. fprintf(stderr, "Sending request using RTS signal\n");
  246. }
  247. ctx_rtu->set_rts(ctx, ctx_rtu->rts == MODBUS_RTU_RTS_UP);
  248. usleep(_MODBUS_RTU_TIME_BETWEEN_RTS_SWITCH);
  249. size = write(ctx->s, req, req_length);
  250. usleep(ctx_rtu->onebyte_time * req_length + _MODBUS_RTU_TIME_BETWEEN_RTS_SWITCH);
  251. ctx_rtu->set_rts(ctx, ctx_rtu->rts != MODBUS_RTU_RTS_UP);
  252. return size;
  253. } else {
  254. #endif
  255. return write(ctx->s, req, req_length);
  256. #if HAVE_DECL_TIOCM_RTS
  257. }
  258. #endif
  259. #endif
  260. }
  261. static int _modbus_rtu_receive(modbus_t *ctx, uint8_t *req)
  262. {
  263. int rc;
  264. modbus_rtu_t *ctx_rtu = ctx->backend_data;
  265. if (ctx_rtu->confirmation_to_ignore) {
  266. _modbus_receive_msg(ctx, req, MSG_CONFIRMATION);
  267. /* Ignore errors and reset the flag */
  268. ctx_rtu->confirmation_to_ignore = FALSE;
  269. rc = 0;
  270. if (ctx->debug) {
  271. printf("Confirmation to ignore\n");
  272. }
  273. } else {
  274. rc = _modbus_receive_msg(ctx, req, MSG_INDICATION);
  275. if (rc == 0) {
  276. /* The next expected message is a confirmation to ignore */
  277. ctx_rtu->confirmation_to_ignore = TRUE;
  278. }
  279. }
  280. return rc;
  281. }
  282. static ssize_t _modbus_rtu_recv(modbus_t *ctx, uint8_t *rsp, int rsp_length)
  283. {
  284. #if defined(_WIN32)
  285. return win32_ser_read(&((modbus_rtu_t *)ctx->backend_data)->w_ser, rsp, rsp_length);
  286. #else
  287. return read(ctx->s, rsp, rsp_length);
  288. #endif
  289. }
  290. static int _modbus_rtu_flush(modbus_t *);
  291. static int _modbus_rtu_pre_check_confirmation(modbus_t *ctx, const uint8_t *req,
  292. const uint8_t *rsp, int rsp_length)
  293. {
  294. /* Check responding slave is the slave we requested (except for broacast
  295. * request) */
  296. if (req[0] != rsp[0] && req[0] != MODBUS_BROADCAST_ADDRESS) {
  297. if (ctx->debug) {
  298. fprintf(stderr,
  299. "The responding slave %d isn't the requested slave %d\n",
  300. rsp[0], req[0]);
  301. }
  302. errno = EMBBADSLAVE;
  303. return -1;
  304. } else {
  305. return 0;
  306. }
  307. }
  308. /* The check_crc16 function shall return 0 is the message is ignored and the
  309. message length if the CRC is valid. Otherwise it shall return -1 and set
  310. errno to EMBADCRC. */
  311. static int _modbus_rtu_check_integrity(modbus_t *ctx, uint8_t *msg,
  312. const int msg_length)
  313. {
  314. uint16_t crc_calculated;
  315. uint16_t crc_received;
  316. int slave = msg[0];
  317. /* Filter on the Modbus unit identifier (slave) in RTU mode to avoid useless
  318. * CRC computing. */
  319. if (slave != ctx->slave && slave != MODBUS_BROADCAST_ADDRESS) {
  320. if (ctx->debug) {
  321. printf("Request for slave %d ignored (not %d)\n", slave, ctx->slave);
  322. }
  323. /* Following call to check_confirmation handles this error */
  324. return 0;
  325. }
  326. crc_calculated = crc16(msg, msg_length - 2);
  327. crc_received = (msg[msg_length - 2] << 8) | msg[msg_length - 1];
  328. /* Check CRC of msg */
  329. if (crc_calculated == crc_received) {
  330. return msg_length;
  331. } else {
  332. if (ctx->debug) {
  333. fprintf(stderr, "ERROR CRC received 0x%0X != CRC calculated 0x%0X\n",
  334. crc_received, crc_calculated);
  335. }
  336. if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) {
  337. _modbus_rtu_flush(ctx);
  338. }
  339. errno = EMBBADCRC;
  340. return -1;
  341. }
  342. }
  343. /* Sets up a serial port for RTU communications */
  344. static int _modbus_rtu_connect(modbus_t *ctx)
  345. {
  346. #if defined(_WIN32)
  347. DCB dcb;
  348. #else
  349. struct termios tios;
  350. speed_t speed;
  351. int flags;
  352. #endif
  353. modbus_rtu_t *ctx_rtu = ctx->backend_data;
  354. if (ctx->debug) {
  355. printf("Opening %s at %d bauds (%c, %d, %d)\n",
  356. ctx_rtu->device, ctx_rtu->baud, ctx_rtu->parity,
  357. ctx_rtu->data_bit, ctx_rtu->stop_bit);
  358. }
  359. #if defined(_WIN32)
  360. /* Some references here:
  361. * http://msdn.microsoft.com/en-us/library/aa450602.aspx
  362. */
  363. win32_ser_init(&ctx_rtu->w_ser);
  364. /* ctx_rtu->device should contain a string like "COMxx:" xx being a decimal
  365. * number */
  366. ctx_rtu->w_ser.fd = CreateFileA(ctx_rtu->device,
  367. GENERIC_READ | GENERIC_WRITE,
  368. 0,
  369. NULL,
  370. OPEN_EXISTING,
  371. 0,
  372. NULL);
  373. /* Error checking */
  374. if (ctx_rtu->w_ser.fd == INVALID_HANDLE_VALUE) {
  375. if (ctx->debug) {
  376. fprintf(stderr, "ERROR Can't open the device %s (LastError %d)\n",
  377. ctx_rtu->device, (int)GetLastError());
  378. }
  379. return -1;
  380. }
  381. /* Save params */
  382. ctx_rtu->old_dcb.DCBlength = sizeof(DCB);
  383. if (!GetCommState(ctx_rtu->w_ser.fd, &ctx_rtu->old_dcb)) {
  384. if (ctx->debug) {
  385. fprintf(stderr, "ERROR Error getting configuration (LastError %d)\n",
  386. (int)GetLastError());
  387. }
  388. CloseHandle(ctx_rtu->w_ser.fd);
  389. ctx_rtu->w_ser.fd = INVALID_HANDLE_VALUE;
  390. return -1;
  391. }
  392. /* Build new configuration (starting from current settings) */
  393. dcb = ctx_rtu->old_dcb;
  394. /* Speed setting */
  395. switch (ctx_rtu->baud) {
  396. case 110:
  397. dcb.BaudRate = CBR_110;
  398. break;
  399. case 300:
  400. dcb.BaudRate = CBR_300;
  401. break;
  402. case 600:
  403. dcb.BaudRate = CBR_600;
  404. break;
  405. case 1200:
  406. dcb.BaudRate = CBR_1200;
  407. break;
  408. case 2400:
  409. dcb.BaudRate = CBR_2400;
  410. break;
  411. case 4800:
  412. dcb.BaudRate = CBR_4800;
  413. break;
  414. case 9600:
  415. dcb.BaudRate = CBR_9600;
  416. break;
  417. case 14400:
  418. dcb.BaudRate = CBR_14400;
  419. break;
  420. case 19200:
  421. dcb.BaudRate = CBR_19200;
  422. break;
  423. case 38400:
  424. dcb.BaudRate = CBR_38400;
  425. break;
  426. case 57600:
  427. dcb.BaudRate = CBR_57600;
  428. break;
  429. case 115200:
  430. dcb.BaudRate = CBR_115200;
  431. break;
  432. case 230400:
  433. /* CBR_230400 - not defined */
  434. dcb.BaudRate = 230400;
  435. break;
  436. case 250000:
  437. dcb.BaudRate = 250000;
  438. break;
  439. case 460800:
  440. dcb.BaudRate = 460800;
  441. break;
  442. case 500000:
  443. dcb.BaudRate = 500000;
  444. break;
  445. case 921600:
  446. dcb.BaudRate = 921600;
  447. break;
  448. case 1000000:
  449. dcb.BaudRate = 1000000;
  450. break;
  451. default:
  452. dcb.BaudRate = CBR_9600;
  453. if (ctx->debug) {
  454. fprintf(stderr, "WARNING Unknown baud rate %d for %s (B9600 used)\n",
  455. ctx_rtu->baud, ctx_rtu->device);
  456. }
  457. }
  458. /* Data bits */
  459. switch (ctx_rtu->data_bit) {
  460. case 5:
  461. dcb.ByteSize = 5;
  462. break;
  463. case 6:
  464. dcb.ByteSize = 6;
  465. break;
  466. case 7:
  467. dcb.ByteSize = 7;
  468. break;
  469. case 8:
  470. default:
  471. dcb.ByteSize = 8;
  472. break;
  473. }
  474. /* Stop bits */
  475. if (ctx_rtu->stop_bit == 1)
  476. dcb.StopBits = ONESTOPBIT;
  477. else /* 2 */
  478. dcb.StopBits = TWOSTOPBITS;
  479. /* Parity */
  480. if (ctx_rtu->parity == 'N') {
  481. dcb.Parity = NOPARITY;
  482. dcb.fParity = FALSE;
  483. } else if (ctx_rtu->parity == 'E') {
  484. dcb.Parity = EVENPARITY;
  485. dcb.fParity = TRUE;
  486. } else {
  487. /* odd */
  488. dcb.Parity = ODDPARITY;
  489. dcb.fParity = TRUE;
  490. }
  491. /* Hardware handshaking left as default settings retrieved */
  492. /* No software handshaking */
  493. dcb.fTXContinueOnXoff = TRUE;
  494. dcb.fOutX = FALSE;
  495. dcb.fInX = FALSE;
  496. /* Binary mode (it's the only supported on Windows anyway) */
  497. dcb.fBinary = TRUE;
  498. /* Don't want errors to be blocking */
  499. dcb.fAbortOnError = FALSE;
  500. /* Setup port */
  501. if (!SetCommState(ctx_rtu->w_ser.fd, &dcb)) {
  502. if (ctx->debug) {
  503. fprintf(stderr, "ERROR Error setting new configuration (LastError %d)\n",
  504. (int)GetLastError());
  505. }
  506. CloseHandle(ctx_rtu->w_ser.fd);
  507. ctx_rtu->w_ser.fd = INVALID_HANDLE_VALUE;
  508. return -1;
  509. }
  510. #else
  511. /* The O_NOCTTY flag tells UNIX that this program doesn't want
  512. to be the "controlling terminal" for that port. If you
  513. don't specify this then any input (such as keyboard abort
  514. signals and so forth) will affect your process
  515. Timeouts are ignored in canonical input mode or when the
  516. NDELAY option is set on the file via open or fcntl */
  517. flags = O_RDWR | O_NOCTTY | O_NDELAY | O_EXCL;
  518. #ifdef O_CLOEXEC
  519. flags |= O_CLOEXEC;
  520. #endif
  521. ctx->s = open(ctx_rtu->device, flags);
  522. if (ctx->s == -1) {
  523. if (ctx->debug) {
  524. fprintf(stderr, "ERROR Can't open the device %s (%s)\n",
  525. ctx_rtu->device, strerror(errno));
  526. }
  527. return -1;
  528. }
  529. /* Save */
  530. tcgetattr(ctx->s, &ctx_rtu->old_tios);
  531. memset(&tios, 0, sizeof(struct termios));
  532. /* C_ISPEED Input baud (new interface)
  533. C_OSPEED Output baud (new interface)
  534. */
  535. switch (ctx_rtu->baud) {
  536. case 110:
  537. speed = B110;
  538. break;
  539. case 300:
  540. speed = B300;
  541. break;
  542. case 600:
  543. speed = B600;
  544. break;
  545. case 1200:
  546. speed = B1200;
  547. break;
  548. case 2400:
  549. speed = B2400;
  550. break;
  551. case 4800:
  552. speed = B4800;
  553. break;
  554. case 9600:
  555. speed = B9600;
  556. break;
  557. case 19200:
  558. speed = B19200;
  559. break;
  560. case 38400:
  561. speed = B38400;
  562. break;
  563. #ifdef B57600
  564. case 57600:
  565. speed = B57600;
  566. break;
  567. #endif
  568. #ifdef B115200
  569. case 115200:
  570. speed = B115200;
  571. break;
  572. #endif
  573. #ifdef B230400
  574. case 230400:
  575. speed = B230400;
  576. break;
  577. #endif
  578. #ifdef B460800
  579. case 460800:
  580. speed = B460800;
  581. break;
  582. #endif
  583. #ifdef B500000
  584. case 500000:
  585. speed = B500000;
  586. break;
  587. #endif
  588. #ifdef B576000
  589. case 576000:
  590. speed = B576000;
  591. break;
  592. #endif
  593. #ifdef B921600
  594. case 921600:
  595. speed = B921600;
  596. break;
  597. #endif
  598. #ifdef B1000000
  599. case 1000000:
  600. speed = B1000000;
  601. break;
  602. #endif
  603. #ifdef B1152000
  604. case 1152000:
  605. speed = B1152000;
  606. break;
  607. #endif
  608. #ifdef B1500000
  609. case 1500000:
  610. speed = B1500000;
  611. break;
  612. #endif
  613. #ifdef B2500000
  614. case 2500000:
  615. speed = B2500000;
  616. break;
  617. #endif
  618. #ifdef B3000000
  619. case 3000000:
  620. speed = B3000000;
  621. break;
  622. #endif
  623. #ifdef B3500000
  624. case 3500000:
  625. speed = B3500000;
  626. break;
  627. #endif
  628. #ifdef B4000000
  629. case 4000000:
  630. speed = B4000000;
  631. break;
  632. #endif
  633. default:
  634. speed = B9600;
  635. if (ctx->debug) {
  636. fprintf(stderr,
  637. "WARNING Unknown baud rate %d for %s (B9600 used)\n",
  638. ctx_rtu->baud, ctx_rtu->device);
  639. }
  640. }
  641. /* Set the baud rate */
  642. if ((cfsetispeed(&tios, speed) < 0) ||
  643. (cfsetospeed(&tios, speed) < 0)) {
  644. close(ctx->s);
  645. ctx->s = -1;
  646. return -1;
  647. }
  648. /* C_CFLAG Control options
  649. CLOCAL Local line - do not change "owner" of port
  650. CREAD Enable receiver
  651. */
  652. tios.c_cflag |= (CREAD | CLOCAL);
  653. /* CSIZE, HUPCL, CRTSCTS (hardware flow control) */
  654. /* Set data bits (5, 6, 7, 8 bits)
  655. CSIZE Bit mask for data bits
  656. */
  657. tios.c_cflag &= ~CSIZE;
  658. switch (ctx_rtu->data_bit) {
  659. case 5:
  660. tios.c_cflag |= CS5;
  661. break;
  662. case 6:
  663. tios.c_cflag |= CS6;
  664. break;
  665. case 7:
  666. tios.c_cflag |= CS7;
  667. break;
  668. case 8:
  669. default:
  670. tios.c_cflag |= CS8;
  671. break;
  672. }
  673. /* Stop bit (1 or 2) */
  674. if (ctx_rtu->stop_bit == 1)
  675. tios.c_cflag &=~ CSTOPB;
  676. else /* 2 */
  677. tios.c_cflag |= CSTOPB;
  678. /* PARENB Enable parity bit
  679. PARODD Use odd parity instead of even */
  680. if (ctx_rtu->parity == 'N') {
  681. /* None */
  682. tios.c_cflag &=~ PARENB;
  683. } else if (ctx_rtu->parity == 'E') {
  684. /* Even */
  685. tios.c_cflag |= PARENB;
  686. tios.c_cflag &=~ PARODD;
  687. } else {
  688. /* Odd */
  689. tios.c_cflag |= PARENB;
  690. tios.c_cflag |= PARODD;
  691. }
  692. /* Read the man page of termios if you need more information. */
  693. /* This field isn't used on POSIX systems
  694. tios.c_line = 0;
  695. */
  696. /* C_LFLAG Line options
  697. ISIG Enable SIGINTR, SIGSUSP, SIGDSUSP, and SIGQUIT signals
  698. ICANON Enable canonical input (else raw)
  699. XCASE Map uppercase \lowercase (obsolete)
  700. ECHO Enable echoing of input characters
  701. ECHOE Echo erase character as BS-SP-BS
  702. ECHOK Echo NL after kill character
  703. ECHONL Echo NL
  704. NOFLSH Disable flushing of input buffers after
  705. interrupt or quit characters
  706. IEXTEN Enable extended functions
  707. ECHOCTL Echo control characters as ^char and delete as ~?
  708. ECHOPRT Echo erased character as character erased
  709. ECHOKE BS-SP-BS entire line on line kill
  710. FLUSHO Output being flushed
  711. PENDIN Retype pending input at next read or input char
  712. TOSTOP Send SIGTTOU for background output
  713. Canonical input is line-oriented. Input characters are put
  714. into a buffer which can be edited interactively by the user
  715. until a CR (carriage return) or LF (line feed) character is
  716. received.
  717. Raw input is unprocessed. Input characters are passed
  718. through exactly as they are received, when they are
  719. received. Generally you'll deselect the ICANON, ECHO,
  720. ECHOE, and ISIG options when using raw input
  721. */
  722. /* Raw input */
  723. tios.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
  724. /* C_IFLAG Input options
  725. Constant Description
  726. INPCK Enable parity check
  727. IGNPAR Ignore parity errors
  728. PARMRK Mark parity errors
  729. ISTRIP Strip parity bits
  730. IXON Enable software flow control (outgoing)
  731. IXOFF Enable software flow control (incoming)
  732. IXANY Allow any character to start flow again
  733. IGNBRK Ignore break condition
  734. BRKINT Send a SIGINT when a break condition is detected
  735. INLCR Map NL to CR
  736. IGNCR Ignore CR
  737. ICRNL Map CR to NL
  738. IUCLC Map uppercase to lowercase
  739. IMAXBEL Echo BEL on input line too long
  740. */
  741. if (ctx_rtu->parity == 'N') {
  742. /* None */
  743. tios.c_iflag &= ~INPCK;
  744. } else {
  745. tios.c_iflag |= INPCK;
  746. }
  747. /* Software flow control is disabled */
  748. tios.c_iflag &= ~(IXON | IXOFF | IXANY);
  749. /* C_OFLAG Output options
  750. OPOST Postprocess output (not set = raw output)
  751. ONLCR Map NL to CR-NL
  752. ONCLR ant others needs OPOST to be enabled
  753. */
  754. /* Raw ouput */
  755. tios.c_oflag &=~ OPOST;
  756. /* C_CC Control characters
  757. VMIN Minimum number of characters to read
  758. VTIME Time to wait for data (tenths of seconds)
  759. UNIX serial interface drivers provide the ability to
  760. specify character and packet timeouts. Two elements of the
  761. c_cc array are used for timeouts: VMIN and VTIME. Timeouts
  762. are ignored in canonical input mode or when the NDELAY
  763. option is set on the file via open or fcntl.
  764. VMIN specifies the minimum number of characters to read. If
  765. it is set to 0, then the VTIME value specifies the time to
  766. wait for every character read. Note that this does not mean
  767. that a read call for N bytes will wait for N characters to
  768. come in. Rather, the timeout will apply to the first
  769. character and the read call will return the number of
  770. characters immediately available (up to the number you
  771. request).
  772. If VMIN is non-zero, VTIME specifies the time to wait for
  773. the first character read. If a character is read within the
  774. time given, any read will block (wait) until all VMIN
  775. characters are read. That is, once the first character is
  776. read, the serial interface driver expects to receive an
  777. entire packet of characters (VMIN bytes total). If no
  778. character is read within the time allowed, then the call to
  779. read returns 0. This method allows you to tell the serial
  780. driver you need exactly N bytes and any read call will
  781. return 0 or N bytes. However, the timeout only applies to
  782. the first character read, so if for some reason the driver
  783. misses one character inside the N byte packet then the read
  784. call could block forever waiting for additional input
  785. characters.
  786. VTIME specifies the amount of time to wait for incoming
  787. characters in tenths of seconds. If VTIME is set to 0 (the
  788. default), reads will block (wait) indefinitely unless the
  789. NDELAY option is set on the port with open or fcntl.
  790. */
  791. /* Unused because we use open with the NDELAY option */
  792. tios.c_cc[VMIN] = 0;
  793. tios.c_cc[VTIME] = 0;
  794. if (tcsetattr(ctx->s, TCSANOW, &tios) < 0) {
  795. close(ctx->s);
  796. ctx->s = -1;
  797. return -1;
  798. }
  799. #endif
  800. return 0;
  801. }
  802. int modbus_rtu_set_serial_mode(modbus_t *ctx, int mode)
  803. {
  804. if (ctx == NULL) {
  805. errno = EINVAL;
  806. return -1;
  807. }
  808. if (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU) {
  809. #if HAVE_DECL_TIOCSRS485
  810. modbus_rtu_t *ctx_rtu = ctx->backend_data;
  811. struct serial_rs485 rs485conf;
  812. memset(&rs485conf, 0x0, sizeof(struct serial_rs485));
  813. if (mode == MODBUS_RTU_RS485) {
  814. rs485conf.flags = SER_RS485_ENABLED;
  815. if (ioctl(ctx->s, TIOCSRS485, &rs485conf) < 0) {
  816. return -1;
  817. }
  818. ctx_rtu->serial_mode = MODBUS_RTU_RS485;
  819. return 0;
  820. } else if (mode == MODBUS_RTU_RS232) {
  821. /* Turn off RS485 mode only if required */
  822. if (ctx_rtu->serial_mode == MODBUS_RTU_RS485) {
  823. /* The ioctl call is avoided because it can fail on some RS232 ports */
  824. if (ioctl(ctx->s, TIOCSRS485, &rs485conf) < 0) {
  825. return -1;
  826. }
  827. }
  828. ctx_rtu->serial_mode = MODBUS_RTU_RS232;
  829. return 0;
  830. }
  831. #else
  832. if (ctx->debug) {
  833. fprintf(stderr, "This function isn't supported on your platform\n");
  834. }
  835. errno = ENOTSUP;
  836. return -1;
  837. #endif
  838. }
  839. /* Wrong backend and invalid mode specified */
  840. errno = EINVAL;
  841. return -1;
  842. }
  843. int modbus_rtu_get_serial_mode(modbus_t *ctx)
  844. {
  845. if (ctx == NULL) {
  846. errno = EINVAL;
  847. return -1;
  848. }
  849. if (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU) {
  850. #if HAVE_DECL_TIOCSRS485
  851. modbus_rtu_t *ctx_rtu = ctx->backend_data;
  852. return ctx_rtu->serial_mode;
  853. #else
  854. if (ctx->debug) {
  855. fprintf(stderr, "This function isn't supported on your platform\n");
  856. }
  857. errno = ENOTSUP;
  858. return -1;
  859. #endif
  860. } else {
  861. errno = EINVAL;
  862. return -1;
  863. }
  864. }
  865. int modbus_rtu_set_rts(modbus_t *ctx, int mode)
  866. {
  867. if (ctx == NULL) {
  868. errno = EINVAL;
  869. return -1;
  870. }
  871. if (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU) {
  872. #if HAVE_DECL_TIOCM_RTS
  873. modbus_rtu_t *ctx_rtu = ctx->backend_data;
  874. if (mode == MODBUS_RTU_RTS_NONE || mode == MODBUS_RTU_RTS_UP ||
  875. mode == MODBUS_RTU_RTS_DOWN) {
  876. ctx_rtu->rts = mode;
  877. /* Set the RTS bit in order to not reserve the RS485 bus */
  878. ctx_rtu->set_rts(ctx, ctx_rtu->rts != MODBUS_RTU_RTS_UP);
  879. return 0;
  880. } else {
  881. errno = EINVAL;
  882. return -1;
  883. }
  884. #else
  885. if (ctx->debug) {
  886. fprintf(stderr, "This function isn't supported on your platform\n");
  887. }
  888. errno = ENOTSUP;
  889. return -1;
  890. #endif
  891. }
  892. /* Wrong backend or invalid mode specified */
  893. errno = EINVAL;
  894. return -1;
  895. }
  896. int modbus_rtu_get_rts(modbus_t *ctx)
  897. {
  898. if (ctx == NULL) {
  899. errno = EINVAL;
  900. return -1;
  901. }
  902. if (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU) {
  903. #if HAVE_DECL_TIOCM_RTS
  904. modbus_rtu_t *ctx_rtu = ctx->backend_data;
  905. return ctx_rtu->rts;
  906. #else
  907. if (ctx->debug) {
  908. fprintf(stderr, "This function isn't supported on your platform\n");
  909. }
  910. errno = ENOTSUP;
  911. return -1;
  912. #endif
  913. } else {
  914. errno = EINVAL;
  915. return -1;
  916. }
  917. }
  918. int modbus_rtu_set_custom_rts(modbus_t *ctx, void (*set_rts) (modbus_t *ctx, int on))
  919. {
  920. if (ctx == NULL) {
  921. errno = EINVAL;
  922. return -1;
  923. }
  924. if (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU) {
  925. #if HAVE_DECL_TIOCM_RTS
  926. modbus_rtu_t *ctx_rtu = ctx->backend_data;
  927. ctx_rtu->set_rts = set_rts;
  928. return 0;
  929. #else
  930. if (ctx->debug) {
  931. fprintf(stderr, "This function isn't supported on your platform\n");
  932. }
  933. errno = ENOTSUP;
  934. return -1;
  935. #endif
  936. } else {
  937. errno = EINVAL;
  938. return -1;
  939. }
  940. }
  941. static void _modbus_rtu_close(modbus_t *ctx)
  942. {
  943. /* Restore line settings and close file descriptor in RTU mode */
  944. modbus_rtu_t *ctx_rtu = ctx->backend_data;
  945. #if defined(_WIN32)
  946. /* Revert settings */
  947. if (!SetCommState(ctx_rtu->w_ser.fd, &ctx_rtu->old_dcb) && ctx->debug) {
  948. fprintf(stderr, "ERROR Couldn't revert to configuration (LastError %d)\n",
  949. (int)GetLastError());
  950. }
  951. if (!CloseHandle(ctx_rtu->w_ser.fd) && ctx->debug) {
  952. fprintf(stderr, "ERROR Error while closing handle (LastError %d)\n",
  953. (int)GetLastError());
  954. }
  955. #else
  956. if (ctx->s != -1) {
  957. tcsetattr(ctx->s, TCSANOW, &ctx_rtu->old_tios);
  958. close(ctx->s);
  959. ctx->s = -1;
  960. }
  961. #endif
  962. }
  963. static int _modbus_rtu_flush(modbus_t *ctx)
  964. {
  965. #if defined(_WIN32)
  966. modbus_rtu_t *ctx_rtu = ctx->backend_data;
  967. ctx_rtu->w_ser.n_bytes = 0;
  968. return (PurgeComm(ctx_rtu->w_ser.fd, PURGE_RXCLEAR) == FALSE);
  969. #else
  970. return tcflush(ctx->s, TCIOFLUSH);
  971. #endif
  972. }
  973. static int _modbus_rtu_select(modbus_t *ctx, fd_set *rset,
  974. struct timeval *tv, int length_to_read)
  975. {
  976. int s_rc;
  977. #if defined(_WIN32)
  978. s_rc = win32_ser_select(&((modbus_rtu_t *)ctx->backend_data)->w_ser,
  979. length_to_read, tv);
  980. if (s_rc == 0) {
  981. errno = ETIMEDOUT;
  982. return -1;
  983. }
  984. if (s_rc < 0) {
  985. return -1;
  986. }
  987. #else
  988. while ((s_rc = select(ctx->s+1, rset, NULL, NULL, tv)) == -1) {
  989. if (errno == EINTR) {
  990. if (ctx->debug) {
  991. fprintf(stderr, "A non blocked signal was caught\n");
  992. }
  993. /* Necessary after an error */
  994. FD_ZERO(rset);
  995. FD_SET(ctx->s, rset);
  996. } else {
  997. return -1;
  998. }
  999. }
  1000. if (s_rc == 0) {
  1001. /* Timeout */
  1002. errno = ETIMEDOUT;
  1003. return -1;
  1004. }
  1005. #endif
  1006. return s_rc;
  1007. }
  1008. static void _modbus_rtu_free(modbus_t *ctx) {
  1009. free(((modbus_rtu_t*)ctx->backend_data)->device);
  1010. free(ctx->backend_data);
  1011. free(ctx);
  1012. }
  1013. const modbus_backend_t _modbus_rtu_backend = {
  1014. _MODBUS_BACKEND_TYPE_RTU,
  1015. _MODBUS_RTU_HEADER_LENGTH,
  1016. _MODBUS_RTU_CHECKSUM_LENGTH,
  1017. MODBUS_RTU_MAX_ADU_LENGTH,
  1018. _modbus_set_slave,
  1019. _modbus_rtu_build_request_basis,
  1020. _modbus_rtu_build_response_basis,
  1021. _modbus_rtu_prepare_response_tid,
  1022. _modbus_rtu_send_msg_pre,
  1023. _modbus_rtu_send,
  1024. _modbus_rtu_receive,
  1025. _modbus_rtu_recv,
  1026. _modbus_rtu_check_integrity,
  1027. _modbus_rtu_pre_check_confirmation,
  1028. _modbus_rtu_connect,
  1029. _modbus_rtu_close,
  1030. _modbus_rtu_flush,
  1031. _modbus_rtu_select,
  1032. _modbus_rtu_free
  1033. };
  1034. modbus_t* modbus_new_rtu(const char *device,
  1035. int baud, char parity, int data_bit,
  1036. int stop_bit)
  1037. {
  1038. modbus_t *ctx;
  1039. modbus_rtu_t *ctx_rtu;
  1040. /* Check device argument */
  1041. if (device == NULL || *device == 0) {
  1042. fprintf(stderr, "The device string is empty\n");
  1043. errno = EINVAL;
  1044. return NULL;
  1045. }
  1046. /* Check baud argument */
  1047. if (baud == 0) {
  1048. fprintf(stderr, "The baud rate value must not be zero\n");
  1049. errno = EINVAL;
  1050. return NULL;
  1051. }
  1052. ctx = (modbus_t *)malloc(sizeof(modbus_t));
  1053. _modbus_init_common(ctx);
  1054. ctx->backend = &_modbus_rtu_backend;
  1055. ctx->backend_data = (modbus_rtu_t *)malloc(sizeof(modbus_rtu_t));
  1056. ctx_rtu = (modbus_rtu_t *)ctx->backend_data;
  1057. ctx_rtu->device = NULL;
  1058. /* Device name and \0 */
  1059. ctx_rtu->device = (char *)malloc((strlen(device) + 1) * sizeof(char));
  1060. strcpy(ctx_rtu->device, device);
  1061. ctx_rtu->baud = baud;
  1062. if (parity == 'N' || parity == 'E' || parity == 'O') {
  1063. ctx_rtu->parity = parity;
  1064. } else {
  1065. modbus_free(ctx);
  1066. errno = EINVAL;
  1067. return NULL;
  1068. }
  1069. ctx_rtu->data_bit = data_bit;
  1070. ctx_rtu->stop_bit = stop_bit;
  1071. #if HAVE_DECL_TIOCSRS485
  1072. /* The RS232 mode has been set by default */
  1073. ctx_rtu->serial_mode = MODBUS_RTU_RS232;
  1074. #endif
  1075. #if HAVE_DECL_TIOCM_RTS
  1076. /* The RTS use has been set by default */
  1077. ctx_rtu->rts = MODBUS_RTU_RTS_NONE;
  1078. /* Calculate estimated time in micro second to send one byte */
  1079. ctx_rtu->onebyte_time = (1000 * 1000) * (1 + data_bit + (parity == 'N' ? 0 : 1) + stop_bit) / baud;
  1080. ctx_rtu->set_rts = _modbus_rtu_ioctl_rts;
  1081. #endif
  1082. ctx_rtu->confirmation_to_ignore = FALSE;
  1083. return ctx;
  1084. }