modbus-rtu.c 27 KB

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