modbus-rtu.c 32 KB

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