modbus-rtu.c 27 KB

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