modbus-rtu.c 26 KB

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