modbus-rtu.c 26 KB

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