modbus.c 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599
  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. *
  19. * This library implements the Modbus protocol.
  20. * http://libmodbus.org/
  21. */
  22. #include <stdio.h>
  23. #include <string.h>
  24. #include <stdlib.h>
  25. #include <errno.h>
  26. #include <limits.h>
  27. #include <time.h>
  28. #include <config.h>
  29. #include "modbus.h"
  30. #include "modbus-private.h"
  31. /* Internal use */
  32. #define MSG_LENGTH_UNDEFINED -1
  33. /* Exported version */
  34. const unsigned int libmodbus_version_major = LIBMODBUS_VERSION_MAJOR;
  35. const unsigned int libmodbus_version_minor = LIBMODBUS_VERSION_MINOR;
  36. const unsigned int libmodbus_version_micro = LIBMODBUS_VERSION_MICRO;
  37. /* Max between RTU and TCP max adu length (so TCP) */
  38. #define MAX_MESSAGE_LENGTH 260
  39. /* 3 steps are used to parse the query */
  40. typedef enum {
  41. _STEP_FUNCTION,
  42. _STEP_META,
  43. _STEP_DATA
  44. } _step_t;
  45. const char *modbus_strerror(int errnum) {
  46. switch (errnum) {
  47. case EMBXILFUN:
  48. return "Illegal function";
  49. case EMBXILADD:
  50. return "Illegal data address";
  51. case EMBXILVAL:
  52. return "Illegal data value";
  53. case EMBXSFAIL:
  54. return "Slave device or server failure";
  55. case EMBXACK:
  56. return "Acknowledge";
  57. case EMBXSBUSY:
  58. return "Slave device or server is busy";
  59. case EMBXNACK:
  60. return "Negative acknowledge";
  61. case EMBXMEMPAR:
  62. return "Memory parity error";
  63. case EMBXGPATH:
  64. return "Gateway path unavailable";
  65. case EMBXGTAR:
  66. return "Target device failed to respond";
  67. case EMBBADCRC:
  68. return "Invalid CRC";
  69. case EMBBADDATA:
  70. return "Invalid data";
  71. case EMBBADEXC:
  72. return "Invalid exception code";
  73. case EMBMDATA:
  74. return "Too many data";
  75. default:
  76. return strerror(errnum);
  77. }
  78. }
  79. void _error_print(modbus_t *ctx, const char *context)
  80. {
  81. if (ctx->debug) {
  82. fprintf(stderr, "ERROR %s", modbus_strerror(errno));
  83. if (context != NULL) {
  84. fprintf(stderr, ": %s\n", context);
  85. } else {
  86. fprintf(stderr, "\n");
  87. }
  88. }
  89. }
  90. int _sleep_and_flush(modbus_t *ctx)
  91. {
  92. #ifdef _WIN32
  93. /* usleep doesn't exist on Windows */
  94. Sleep((ctx->response_timeout.tv_sec * 1000) +
  95. (ctx->response_timeout.tv_usec / 1000));
  96. #else
  97. /* usleep source code */
  98. struct timespec request, remaining;
  99. request.tv_sec = ctx->response_timeout.tv_sec;
  100. request.tv_nsec = ((long int)ctx->response_timeout.tv_usec % 1000000)
  101. * 1000;
  102. while (nanosleep(&request, &remaining) == -1 && errno == EINTR)
  103. request = remaining;
  104. #endif
  105. return modbus_flush(ctx);
  106. }
  107. int modbus_flush(modbus_t *ctx)
  108. {
  109. int rc = ctx->backend->flush(ctx);
  110. if (rc != -1 && ctx->debug) {
  111. printf("%d bytes flushed\n", rc);
  112. }
  113. return rc;
  114. }
  115. /* Computes the length of the expected response */
  116. static unsigned int compute_response_length_from_request(modbus_t *ctx, uint8_t *req)
  117. {
  118. int length;
  119. const int offset = ctx->backend->header_length;
  120. switch (req[offset]) {
  121. case _FC_READ_COILS:
  122. case _FC_READ_DISCRETE_INPUTS: {
  123. /* Header + nb values (code from write_bits) */
  124. int nb = (req[offset + 3] << 8) | req[offset + 4];
  125. length = 2 + (nb / 8) + ((nb % 8) ? 1 : 0);
  126. }
  127. break;
  128. case _FC_READ_AND_WRITE_REGISTERS:
  129. case _FC_READ_HOLDING_REGISTERS:
  130. case _FC_READ_INPUT_REGISTERS:
  131. /* Header + 2 * nb values */
  132. length = 2 + 2 * (req[offset + 3] << 8 | req[offset + 4]);
  133. break;
  134. case _FC_READ_EXCEPTION_STATUS:
  135. length = 3;
  136. break;
  137. case _FC_REPORT_SLAVE_ID:
  138. /* The response is device specific (the header provides the
  139. length) */
  140. return MSG_LENGTH_UNDEFINED;
  141. default:
  142. length = 5;
  143. }
  144. return offset + length + ctx->backend->checksum_length;
  145. }
  146. /* Sends a request/response */
  147. static int send_msg(modbus_t *ctx, uint8_t *msg, int msg_length)
  148. {
  149. int rc;
  150. int i;
  151. msg_length = ctx->backend->send_msg_pre(msg, msg_length);
  152. if (ctx->debug) {
  153. for (i = 0; i < msg_length; i++)
  154. printf("[%.2X]", msg[i]);
  155. printf("\n");
  156. }
  157. /* In recovery mode, the write command will be issued until to be
  158. successful! Disabled by default. */
  159. do {
  160. rc = ctx->backend->send(ctx, msg, msg_length);
  161. if (rc == -1) {
  162. _error_print(ctx, NULL);
  163. if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_LINK) {
  164. int saved_errno = errno;
  165. if ((errno == EBADF || errno == ECONNRESET || errno == EPIPE)) {
  166. modbus_close(ctx);
  167. modbus_connect(ctx);
  168. } else {
  169. _sleep_and_flush(ctx);
  170. }
  171. errno = saved_errno;
  172. }
  173. }
  174. } while ((ctx->error_recovery & MODBUS_ERROR_RECOVERY_LINK) &&
  175. rc == -1);
  176. if (rc > 0 && rc != msg_length) {
  177. errno = EMBBADDATA;
  178. return -1;
  179. }
  180. return rc;
  181. }
  182. int modbus_send_raw_request(modbus_t *ctx, uint8_t *raw_req, int raw_req_length)
  183. {
  184. sft_t sft;
  185. uint8_t req[MAX_MESSAGE_LENGTH];
  186. int req_length;
  187. if (raw_req_length < 2) {
  188. /* The raw request must contain function and slave at least */
  189. errno = EINVAL;
  190. return -1;
  191. }
  192. sft.slave = raw_req[0];
  193. sft.function = raw_req[1];
  194. /* The t_id is left to zero */
  195. sft.t_id = 0;
  196. /* This response function only set the header so it's convenient here */
  197. req_length = ctx->backend->build_response_basis(&sft, req);
  198. if (raw_req_length > 2) {
  199. /* Copy data after function code */
  200. memcpy(req + req_length, raw_req + 2, raw_req_length - 2);
  201. req_length += raw_req_length - 2;
  202. }
  203. return send_msg(ctx, req, req_length);
  204. }
  205. /*
  206. ---------- Request Indication ----------
  207. | Client | ---------------------->| Server |
  208. ---------- Confirmation Response ----------
  209. */
  210. typedef enum {
  211. /* Request message on the server side */
  212. MSG_INDICATION,
  213. /* Request message on the client side */
  214. MSG_CONFIRMATION
  215. } msg_type_t;
  216. /* Computes the length to read after the function received */
  217. static uint8_t compute_meta_length_after_function(int function,
  218. msg_type_t msg_type)
  219. {
  220. int length;
  221. if (msg_type == MSG_INDICATION) {
  222. if (function <= _FC_WRITE_SINGLE_REGISTER) {
  223. length = 4;
  224. } else if (function == _FC_WRITE_MULTIPLE_COILS ||
  225. function == _FC_WRITE_MULTIPLE_REGISTERS) {
  226. length = 5;
  227. } else if (function == _FC_READ_AND_WRITE_REGISTERS) {
  228. length = 9;
  229. } else {
  230. /* _FC_READ_EXCEPTION_STATUS, _FC_REPORT_SLAVE_ID */
  231. length = 0;
  232. }
  233. } else {
  234. /* MSG_CONFIRMATION */
  235. switch (function) {
  236. case _FC_WRITE_SINGLE_COIL:
  237. case _FC_WRITE_SINGLE_REGISTER:
  238. case _FC_WRITE_MULTIPLE_COILS:
  239. case _FC_WRITE_MULTIPLE_REGISTERS:
  240. length = 4;
  241. break;
  242. default:
  243. length = 1;
  244. }
  245. }
  246. return length;
  247. }
  248. /* Computes the length to read after the meta information (address, count, etc) */
  249. static int compute_data_length_after_meta(modbus_t *ctx, uint8_t *msg,
  250. msg_type_t msg_type)
  251. {
  252. int function = msg[ctx->backend->header_length];
  253. int length;
  254. if (msg_type == MSG_INDICATION) {
  255. switch (function) {
  256. case _FC_WRITE_MULTIPLE_COILS:
  257. case _FC_WRITE_MULTIPLE_REGISTERS:
  258. length = msg[ctx->backend->header_length + 5];
  259. break;
  260. case _FC_READ_AND_WRITE_REGISTERS:
  261. length = msg[ctx->backend->header_length + 9];
  262. break;
  263. default:
  264. length = 0;
  265. }
  266. } else {
  267. /* MSG_CONFIRMATION */
  268. if (function <= _FC_READ_INPUT_REGISTERS ||
  269. function == _FC_REPORT_SLAVE_ID ||
  270. function == _FC_READ_AND_WRITE_REGISTERS) {
  271. length = msg[ctx->backend->header_length + 1];
  272. } else {
  273. length = 0;
  274. }
  275. }
  276. length += ctx->backend->checksum_length;
  277. return length;
  278. }
  279. /* Waits a response from a modbus server or a request from a modbus client.
  280. This function blocks if there is no replies (3 timeouts).
  281. The function shall return the number of received characters and the received
  282. message in an array of uint8_t if successful. Otherwise it shall return -1
  283. and errno is set to one of the values defined below:
  284. - ECONNRESET
  285. - EMBBADDATA
  286. - EMBUNKEXC
  287. - ETIMEDOUT
  288. - read() or recv() error codes
  289. */
  290. static int receive_msg(modbus_t *ctx, uint8_t *msg, msg_type_t msg_type)
  291. {
  292. int rc;
  293. fd_set rfds;
  294. struct timeval tv;
  295. struct timeval *p_tv;
  296. int length_to_read;
  297. int msg_length = 0;
  298. _step_t step;
  299. if (ctx->debug) {
  300. if (msg_type == MSG_INDICATION) {
  301. printf("Waiting for a indication...\n");
  302. } else {
  303. printf("Waiting for a confirmation...\n");
  304. }
  305. }
  306. /* Add a file descriptor to the set */
  307. FD_ZERO(&rfds);
  308. FD_SET(ctx->s, &rfds);
  309. /* We need to analyse the message step by step. At the first step, we want
  310. * to reach the function code because all packets contain this
  311. * information. */
  312. step = _STEP_FUNCTION;
  313. length_to_read = ctx->backend->header_length + 1;
  314. if (msg_type == MSG_INDICATION) {
  315. /* Wait for a message, we don't know when the message will be
  316. * received */
  317. p_tv = NULL;
  318. } else {
  319. tv.tv_sec = ctx->response_timeout.tv_sec;
  320. tv.tv_usec = ctx->response_timeout.tv_usec;
  321. p_tv = &tv;
  322. }
  323. while (length_to_read != 0) {
  324. rc = ctx->backend->select(ctx, &rfds, p_tv, length_to_read);
  325. if (rc == -1) {
  326. _error_print(ctx, "select");
  327. if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_LINK) {
  328. int saved_errno = errno;
  329. if (errno == ETIMEDOUT) {
  330. _sleep_and_flush(ctx);
  331. } else if (errno == EBADF) {
  332. modbus_close(ctx);
  333. modbus_connect(ctx);
  334. }
  335. errno = saved_errno;
  336. }
  337. return -1;
  338. }
  339. rc = ctx->backend->recv(ctx, msg + msg_length, length_to_read);
  340. if (rc == 0) {
  341. errno = ECONNRESET;
  342. rc = -1;
  343. }
  344. if (rc == -1) {
  345. _error_print(ctx, "read");
  346. if ((ctx->error_recovery & MODBUS_ERROR_RECOVERY_LINK) &&
  347. (errno == ECONNRESET || errno == ECONNREFUSED ||
  348. errno == EBADF)) {
  349. int saved_errno = errno;
  350. modbus_close(ctx);
  351. modbus_connect(ctx);
  352. /* Could be removed by previous calls */
  353. errno = saved_errno;
  354. }
  355. return -1;
  356. }
  357. /* Display the hex code of each character received */
  358. if (ctx->debug) {
  359. int i;
  360. for (i=0; i < rc; i++)
  361. printf("<%.2X>", msg[msg_length + i]);
  362. }
  363. /* Sums bytes received */
  364. msg_length += rc;
  365. /* Computes remaining bytes */
  366. length_to_read -= rc;
  367. if (length_to_read == 0) {
  368. switch (step) {
  369. case _STEP_FUNCTION:
  370. /* Function code position */
  371. length_to_read = compute_meta_length_after_function(
  372. msg[ctx->backend->header_length],
  373. msg_type);
  374. if (length_to_read != 0) {
  375. step = _STEP_META;
  376. break;
  377. } /* else switches straight to the next step */
  378. case _STEP_META:
  379. length_to_read = compute_data_length_after_meta(
  380. ctx, msg, msg_type);
  381. if ((msg_length + length_to_read) > ctx->backend->max_adu_length) {
  382. errno = EMBBADDATA;
  383. _error_print(ctx, "too many data");
  384. return -1;
  385. }
  386. step = _STEP_DATA;
  387. break;
  388. default:
  389. break;
  390. }
  391. }
  392. if (length_to_read > 0) {
  393. /* If there is no character in the buffer, the allowed timeout
  394. interval between two consecutive bytes is defined by
  395. byte_timeout */
  396. tv.tv_sec = ctx->byte_timeout.tv_sec;
  397. tv.tv_usec = ctx->byte_timeout.tv_usec;
  398. p_tv = &tv;
  399. }
  400. }
  401. if (ctx->debug)
  402. printf("\n");
  403. return ctx->backend->check_integrity(ctx, msg, msg_length);
  404. }
  405. /* Receive the request from a modbus master */
  406. int modbus_receive(modbus_t *ctx, uint8_t *req)
  407. {
  408. return receive_msg(ctx, req, MSG_INDICATION);
  409. }
  410. /* Receives the confirmation.
  411. The function shall store the read response in rsp and return the number of
  412. values (bits or words). Otherwise, its shall return -1 and errno is set.
  413. The function doesn't check the confirmation is the expected response to the
  414. initial request.
  415. */
  416. int modbus_receive_confirmation(modbus_t *ctx, uint8_t *rsp)
  417. {
  418. return receive_msg(ctx, rsp, MSG_CONFIRMATION);
  419. }
  420. static int check_confirmation(modbus_t *ctx, uint8_t *req,
  421. uint8_t *rsp, int rsp_length)
  422. {
  423. int rc;
  424. int rsp_length_computed;
  425. const int offset = ctx->backend->header_length;
  426. if (ctx->backend->pre_check_confirmation) {
  427. rc = ctx->backend->pre_check_confirmation(ctx, req, rsp, rsp_length);
  428. if (rc == -1) {
  429. if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) {
  430. _sleep_and_flush(ctx);
  431. }
  432. return -1;
  433. }
  434. }
  435. rsp_length_computed = compute_response_length_from_request(ctx, req);
  436. /* Check length */
  437. if (rsp_length == rsp_length_computed ||
  438. rsp_length_computed == MSG_LENGTH_UNDEFINED) {
  439. int req_nb_value;
  440. int rsp_nb_value;
  441. const int function = rsp[offset];
  442. /* Check function code */
  443. if (function != req[offset]) {
  444. if (ctx->debug) {
  445. fprintf(stderr,
  446. "Received function not corresponding to the request (%d != %d)\n",
  447. function, req[offset]);
  448. }
  449. if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) {
  450. _sleep_and_flush(ctx);
  451. }
  452. errno = EMBBADDATA;
  453. return -1;
  454. }
  455. /* Check the number of values is corresponding to the request */
  456. switch (function) {
  457. case _FC_READ_COILS:
  458. case _FC_READ_DISCRETE_INPUTS:
  459. /* Read functions, 8 values in a byte (nb
  460. * of values in the request and byte count in
  461. * the response. */
  462. req_nb_value = (req[offset + 3] << 8) + req[offset + 4];
  463. req_nb_value = (req_nb_value / 8) + ((req_nb_value % 8) ? 1 : 0);
  464. rsp_nb_value = rsp[offset + 1];
  465. break;
  466. case _FC_READ_AND_WRITE_REGISTERS:
  467. case _FC_READ_HOLDING_REGISTERS:
  468. case _FC_READ_INPUT_REGISTERS:
  469. /* Read functions 1 value = 2 bytes */
  470. req_nb_value = (req[offset + 3] << 8) + req[offset + 4];
  471. rsp_nb_value = (rsp[offset + 1] / 2);
  472. break;
  473. case _FC_WRITE_MULTIPLE_COILS:
  474. case _FC_WRITE_MULTIPLE_REGISTERS:
  475. /* N Write functions */
  476. req_nb_value = (req[offset + 3] << 8) + req[offset + 4];
  477. rsp_nb_value = (rsp[offset + 3] << 8) | rsp[offset + 4];
  478. break;
  479. case _FC_REPORT_SLAVE_ID:
  480. /* Report slave ID (bytes received) */
  481. req_nb_value = rsp_nb_value = rsp[offset + 1];
  482. break;
  483. default:
  484. /* 1 Write functions & others */
  485. req_nb_value = rsp_nb_value = 1;
  486. }
  487. if (req_nb_value == rsp_nb_value) {
  488. rc = rsp_nb_value;
  489. } else {
  490. if (ctx->debug) {
  491. fprintf(stderr,
  492. "Quantity not corresponding to the request (%d != %d)\n",
  493. rsp_nb_value, req_nb_value);
  494. }
  495. if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) {
  496. _sleep_and_flush(ctx);
  497. }
  498. errno = EMBBADDATA;
  499. rc = -1;
  500. }
  501. } else if (rsp_length == (offset + 2 + ctx->backend->checksum_length) &&
  502. req[offset] == (rsp[offset] - 0x80)) {
  503. /* EXCEPTION CODE RECEIVED */
  504. int exception_code = rsp[offset + 1];
  505. if (exception_code < MODBUS_EXCEPTION_MAX) {
  506. errno = MODBUS_ENOBASE + exception_code;
  507. } else {
  508. errno = EMBBADEXC;
  509. }
  510. _error_print(ctx, NULL);
  511. rc = -1;
  512. } else {
  513. if (ctx->debug) {
  514. fprintf(stderr,
  515. "Message length not corresponding to the computed length (%d != %d)\n",
  516. rsp_length, rsp_length_computed);
  517. }
  518. if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) {
  519. _sleep_and_flush(ctx);
  520. }
  521. errno = EMBBADDATA;
  522. rc = -1;
  523. }
  524. return rc;
  525. }
  526. static int response_io_status(int address, int nb,
  527. uint8_t *tab_io_status,
  528. uint8_t *rsp, int offset)
  529. {
  530. int shift = 0;
  531. int byte = 0;
  532. int i;
  533. for (i = address; i < address+nb; i++) {
  534. byte |= tab_io_status[i] << shift;
  535. if (shift == 7) {
  536. /* Byte is full */
  537. rsp[offset++] = byte;
  538. byte = shift = 0;
  539. } else {
  540. shift++;
  541. }
  542. }
  543. if (shift != 0)
  544. rsp[offset++] = byte;
  545. return offset;
  546. }
  547. /* Build the exception response */
  548. static int response_exception(modbus_t *ctx, sft_t *sft,
  549. int exception_code, uint8_t *rsp)
  550. {
  551. int rsp_length;
  552. sft->function = sft->function + 0x80;
  553. rsp_length = ctx->backend->build_response_basis(sft, rsp);
  554. /* Positive exception code */
  555. rsp[rsp_length++] = exception_code;
  556. return rsp_length;
  557. }
  558. /* Send a response to the receive request.
  559. Analyses the request and constructs a response.
  560. If an error occurs, this function construct the response
  561. accordingly.
  562. */
  563. int modbus_reply(modbus_t *ctx, const uint8_t *req,
  564. int req_length, modbus_mapping_t *mb_mapping)
  565. {
  566. int offset = ctx->backend->header_length;
  567. int slave = req[offset - 1];
  568. int function = req[offset];
  569. uint16_t address = (req[offset + 1] << 8) + req[offset + 2];
  570. uint8_t rsp[MAX_MESSAGE_LENGTH];
  571. int rsp_length = 0;
  572. sft_t sft;
  573. if (ctx->backend->filter_request(ctx, slave) == 1) {
  574. /* Filtered */
  575. return 0;
  576. }
  577. sft.slave = slave;
  578. sft.function = function;
  579. sft.t_id = ctx->backend->prepare_response_tid(req, &req_length);
  580. switch (function) {
  581. case _FC_READ_COILS: {
  582. int nb = (req[offset + 3] << 8) + req[offset + 4];
  583. if ((address + nb) > mb_mapping->nb_bits) {
  584. if (ctx->debug) {
  585. fprintf(stderr, "Illegal data address %0X in read_bits\n",
  586. address + nb);
  587. }
  588. rsp_length = response_exception(
  589. ctx, &sft,
  590. MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp);
  591. } else {
  592. rsp_length = ctx->backend->build_response_basis(&sft, rsp);
  593. rsp[rsp_length++] = (nb / 8) + ((nb % 8) ? 1 : 0);
  594. rsp_length = response_io_status(address, nb,
  595. mb_mapping->tab_bits,
  596. rsp, rsp_length);
  597. }
  598. }
  599. break;
  600. case _FC_READ_DISCRETE_INPUTS: {
  601. /* Similar to coil status (but too many arguments to use a
  602. * function) */
  603. int nb = (req[offset + 3] << 8) + req[offset + 4];
  604. if ((address + nb) > mb_mapping->nb_input_bits) {
  605. if (ctx->debug) {
  606. fprintf(stderr, "Illegal data address %0X in read_input_bits\n",
  607. address + nb);
  608. }
  609. rsp_length = response_exception(
  610. ctx, &sft,
  611. MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp);
  612. } else {
  613. rsp_length = ctx->backend->build_response_basis(&sft, rsp);
  614. rsp[rsp_length++] = (nb / 8) + ((nb % 8) ? 1 : 0);
  615. rsp_length = response_io_status(address, nb,
  616. mb_mapping->tab_input_bits,
  617. rsp, rsp_length);
  618. }
  619. }
  620. break;
  621. case _FC_READ_HOLDING_REGISTERS: {
  622. int nb = (req[offset + 3] << 8) + req[offset + 4];
  623. if ((address + nb) > mb_mapping->nb_registers) {
  624. if (ctx->debug) {
  625. fprintf(stderr, "Illegal data address %0X in read_registers\n",
  626. address + nb);
  627. }
  628. rsp_length = response_exception(
  629. ctx, &sft,
  630. MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp);
  631. } else {
  632. int i;
  633. rsp_length = ctx->backend->build_response_basis(&sft, rsp);
  634. rsp[rsp_length++] = nb << 1;
  635. for (i = address; i < address + nb; i++) {
  636. rsp[rsp_length++] = mb_mapping->tab_registers[i] >> 8;
  637. rsp[rsp_length++] = mb_mapping->tab_registers[i] & 0xFF;
  638. }
  639. }
  640. }
  641. break;
  642. case _FC_READ_INPUT_REGISTERS: {
  643. /* Similar to holding registers (but too many arguments to use a
  644. * function) */
  645. int nb = (req[offset + 3] << 8) + req[offset + 4];
  646. if ((address + nb) > mb_mapping->nb_input_registers) {
  647. if (ctx->debug) {
  648. fprintf(stderr, "Illegal data address %0X in read_input_registers\n",
  649. address + nb);
  650. }
  651. rsp_length = response_exception(
  652. ctx, &sft,
  653. MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp);
  654. } else {
  655. int i;
  656. rsp_length = ctx->backend->build_response_basis(&sft, rsp);
  657. rsp[rsp_length++] = nb << 1;
  658. for (i = address; i < address + nb; i++) {
  659. rsp[rsp_length++] = mb_mapping->tab_input_registers[i] >> 8;
  660. rsp[rsp_length++] = mb_mapping->tab_input_registers[i] & 0xFF;
  661. }
  662. }
  663. }
  664. break;
  665. case _FC_WRITE_SINGLE_COIL:
  666. if (address >= mb_mapping->nb_bits) {
  667. if (ctx->debug) {
  668. fprintf(stderr, "Illegal data address %0X in write_bit\n",
  669. address);
  670. }
  671. rsp_length = response_exception(
  672. ctx, &sft,
  673. MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp);
  674. } else {
  675. int data = (req[offset + 3] << 8) + req[offset + 4];
  676. if (data == 0xFF00 || data == 0x0) {
  677. mb_mapping->tab_bits[address] = (data) ? ON : OFF;
  678. memcpy(rsp, req, req_length);
  679. rsp_length = req_length;
  680. } else {
  681. if (ctx->debug) {
  682. fprintf(stderr,
  683. "Illegal data value %0X in write_bit request at address %0X\n",
  684. data, address);
  685. }
  686. rsp_length = response_exception(
  687. ctx, &sft,
  688. MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp);
  689. }
  690. }
  691. break;
  692. case _FC_WRITE_SINGLE_REGISTER:
  693. if (address >= mb_mapping->nb_registers) {
  694. if (ctx->debug) {
  695. fprintf(stderr, "Illegal data address %0X in write_register\n",
  696. address);
  697. }
  698. rsp_length = response_exception(
  699. ctx, &sft,
  700. MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp);
  701. } else {
  702. int data = (req[offset + 3] << 8) + req[offset + 4];
  703. mb_mapping->tab_registers[address] = data;
  704. memcpy(rsp, req, req_length);
  705. rsp_length = req_length;
  706. }
  707. break;
  708. case _FC_WRITE_MULTIPLE_COILS: {
  709. int nb = (req[offset + 3] << 8) + req[offset + 4];
  710. if ((address + nb) > mb_mapping->nb_bits) {
  711. if (ctx->debug) {
  712. fprintf(stderr, "Illegal data address %0X in write_bits\n",
  713. address + nb);
  714. }
  715. rsp_length = response_exception(
  716. ctx, &sft,
  717. MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp);
  718. } else {
  719. /* 6 = byte count */
  720. modbus_set_bits_from_bytes(mb_mapping->tab_bits, address, nb, &req[offset + 6]);
  721. rsp_length = ctx->backend->build_response_basis(&sft, rsp);
  722. /* 4 to copy the bit address (2) and the quantity of bits */
  723. memcpy(rsp + rsp_length, req + rsp_length, 4);
  724. rsp_length += 4;
  725. }
  726. }
  727. break;
  728. case _FC_WRITE_MULTIPLE_REGISTERS: {
  729. int nb = (req[offset + 3] << 8) + req[offset + 4];
  730. if ((address + nb) > mb_mapping->nb_registers) {
  731. if (ctx->debug) {
  732. fprintf(stderr, "Illegal data address %0X in write_registers\n",
  733. address + nb);
  734. }
  735. rsp_length = response_exception(
  736. ctx, &sft,
  737. MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp);
  738. } else {
  739. int i, j;
  740. for (i = address, j = 6; i < address + nb; i++, j += 2) {
  741. /* 6 and 7 = first value */
  742. mb_mapping->tab_registers[i] =
  743. (req[offset + j] << 8) + req[offset + j + 1];
  744. }
  745. rsp_length = ctx->backend->build_response_basis(&sft, rsp);
  746. /* 4 to copy the address (2) and the no. of registers */
  747. memcpy(rsp + rsp_length, req + rsp_length, 4);
  748. rsp_length += 4;
  749. }
  750. }
  751. break;
  752. case _FC_REPORT_SLAVE_ID:
  753. rsp_length = ctx->backend->build_response_basis(&sft, rsp);
  754. /* 2 bytes */
  755. rsp[rsp_length++] = 2;
  756. rsp[rsp_length++] = ctx->slave;
  757. /* Slave is ON */
  758. rsp[rsp_length++] = 0xFF;
  759. break;
  760. case _FC_READ_EXCEPTION_STATUS:
  761. if (ctx->debug) {
  762. fprintf(stderr, "FIXME Not implemented\n");
  763. }
  764. errno = ENOPROTOOPT;
  765. return -1;
  766. break;
  767. case _FC_READ_AND_WRITE_REGISTERS: {
  768. int nb = (req[offset + 3] << 8) + req[offset + 4];
  769. uint16_t address_write = (req[offset + 5] << 8) + req[offset + 6];
  770. int nb_write = (req[offset + 7] << 8) + req[offset + 8];
  771. if ((address + nb) > mb_mapping->nb_registers ||
  772. (address_write + nb_write) > mb_mapping->nb_registers) {
  773. if (ctx->debug) {
  774. fprintf(stderr,
  775. "Illegal data read address %0X or write address %0X in read_and_write_registers\n",
  776. address + nb, address_write + nb_write);
  777. }
  778. rsp_length = response_exception(ctx, &sft,
  779. MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp);
  780. } else {
  781. int i, j;
  782. rsp_length = ctx->backend->build_response_basis(&sft, rsp);
  783. rsp[rsp_length++] = nb << 1;
  784. /* Write first.
  785. 10 and 11 are the offset of the first values to write */
  786. for (i = address_write, j = 10; i < address_write + nb_write; i++, j += 2) {
  787. mb_mapping->tab_registers[i] =
  788. (req[offset + j] << 8) + req[offset + j + 1];
  789. }
  790. /* and read the data for the response */
  791. for (i = address; i < address + nb; i++) {
  792. rsp[rsp_length++] = mb_mapping->tab_registers[i] >> 8;
  793. rsp[rsp_length++] = mb_mapping->tab_registers[i] & 0xFF;
  794. }
  795. }
  796. }
  797. break;
  798. default:
  799. rsp_length = response_exception(ctx, &sft,
  800. MODBUS_EXCEPTION_ILLEGAL_FUNCTION,
  801. rsp);
  802. break;
  803. }
  804. return send_msg(ctx, rsp, rsp_length);
  805. }
  806. int modbus_reply_exception(modbus_t *ctx, const uint8_t *req,
  807. unsigned int exception_code)
  808. {
  809. int offset = ctx->backend->header_length;
  810. int slave = req[offset - 1];
  811. int function = req[offset];
  812. uint8_t rsp[MAX_MESSAGE_LENGTH];
  813. int rsp_length;
  814. int dummy_length = 99;
  815. sft_t sft;
  816. if (ctx->backend->filter_request(ctx, slave) == 1) {
  817. /* Filtered */
  818. return 0;
  819. }
  820. sft.slave = slave;
  821. sft.function = function + 0x80;;
  822. sft.t_id = ctx->backend->prepare_response_tid(req, &dummy_length);
  823. rsp_length = ctx->backend->build_response_basis(&sft, rsp);
  824. /* Positive exception code */
  825. if (exception_code < MODBUS_EXCEPTION_MAX) {
  826. rsp[rsp_length++] = exception_code;
  827. return send_msg(ctx, rsp, rsp_length);
  828. } else {
  829. errno = EINVAL;
  830. return -1;
  831. }
  832. }
  833. /* Reads IO status */
  834. static int read_io_status(modbus_t *ctx, int function,
  835. int addr, int nb, uint8_t *dest)
  836. {
  837. int rc;
  838. int req_length;
  839. uint8_t req[_MIN_REQ_LENGTH];
  840. uint8_t rsp[MAX_MESSAGE_LENGTH];
  841. req_length = ctx->backend->build_request_basis(ctx, function, addr, nb, req);
  842. rc = send_msg(ctx, req, req_length);
  843. if (rc > 0) {
  844. int i, temp, bit;
  845. int pos = 0;
  846. int offset;
  847. int offset_end;
  848. rc = receive_msg(ctx, rsp, MSG_CONFIRMATION);
  849. if (rc == -1)
  850. return -1;
  851. rc = check_confirmation(ctx, req, rsp, rc);
  852. if (rc == -1)
  853. return -1;
  854. offset = ctx->backend->header_length + 2;
  855. offset_end = offset + rc;
  856. for (i = offset; i < offset_end; i++) {
  857. /* Shift reg hi_byte to temp */
  858. temp = rsp[i];
  859. for (bit = 0x01; (bit & 0xff) && (pos < nb);) {
  860. dest[pos++] = (temp & bit) ? TRUE : FALSE;
  861. bit = bit << 1;
  862. }
  863. }
  864. }
  865. return rc;
  866. }
  867. /* Reads the boolean status of bits and sets the array elements
  868. in the destination to TRUE or FALSE (single bits). */
  869. int modbus_read_bits(modbus_t *ctx, int addr, int nb, uint8_t *dest)
  870. {
  871. int rc;
  872. if (nb > MODBUS_MAX_READ_BITS) {
  873. if (ctx->debug) {
  874. fprintf(stderr,
  875. "ERROR Too many bits requested (%d > %d)\n",
  876. nb, MODBUS_MAX_READ_BITS);
  877. }
  878. errno = EMBMDATA;
  879. return -1;
  880. }
  881. rc = read_io_status(ctx, _FC_READ_COILS, addr, nb, dest);
  882. if (rc == -1)
  883. return -1;
  884. else
  885. return nb;
  886. }
  887. /* Same as modbus_read_bits but reads the remote device input table */
  888. int modbus_read_input_bits(modbus_t *ctx, int addr, int nb, uint8_t *dest)
  889. {
  890. int rc;
  891. if (nb > MODBUS_MAX_READ_BITS) {
  892. if (ctx->debug) {
  893. fprintf(stderr,
  894. "ERROR Too many discrete inputs requested (%d > %d)\n",
  895. nb, MODBUS_MAX_READ_BITS);
  896. }
  897. errno = EMBMDATA;
  898. return -1;
  899. }
  900. rc = read_io_status(ctx, _FC_READ_DISCRETE_INPUTS, addr, nb, dest);
  901. if (rc == -1)
  902. return -1;
  903. else
  904. return nb;
  905. }
  906. /* Reads the data from a remove device and put that data into an array */
  907. static int read_registers(modbus_t *ctx, int function, int addr, int nb,
  908. uint16_t *dest)
  909. {
  910. int rc;
  911. int req_length;
  912. uint8_t req[_MIN_REQ_LENGTH];
  913. uint8_t rsp[MAX_MESSAGE_LENGTH];
  914. if (nb > MODBUS_MAX_READ_REGISTERS) {
  915. if (ctx->debug) {
  916. fprintf(stderr,
  917. "ERROR Too many registers requested (%d > %d)\n",
  918. nb, MODBUS_MAX_READ_REGISTERS);
  919. }
  920. errno = EMBMDATA;
  921. return -1;
  922. }
  923. req_length = ctx->backend->build_request_basis(ctx, function, addr, nb, req);
  924. rc = send_msg(ctx, req, req_length);
  925. if (rc > 0) {
  926. int offset;
  927. int i;
  928. rc = receive_msg(ctx, rsp, MSG_CONFIRMATION);
  929. if (rc == -1)
  930. return -1;
  931. rc = check_confirmation(ctx, req, rsp, rc);
  932. if (rc == -1)
  933. return -1;
  934. offset = ctx->backend->header_length;
  935. for (i = 0; i < rc; i++) {
  936. /* shift reg hi_byte to temp OR with lo_byte */
  937. dest[i] = (rsp[offset + 2 + (i << 1)] << 8) |
  938. rsp[offset + 3 + (i << 1)];
  939. }
  940. }
  941. return rc;
  942. }
  943. /* Reads the holding registers of remote device and put the data into an
  944. array */
  945. int modbus_read_registers(modbus_t *ctx, int addr, int nb, uint16_t *dest)
  946. {
  947. int status;
  948. if (nb > MODBUS_MAX_READ_REGISTERS) {
  949. if (ctx->debug) {
  950. fprintf(stderr,
  951. "ERROR Too many registers requested (%d > %d)\n",
  952. nb, MODBUS_MAX_READ_REGISTERS);
  953. }
  954. errno = EMBMDATA;
  955. return -1;
  956. }
  957. status = read_registers(ctx, _FC_READ_HOLDING_REGISTERS,
  958. addr, nb, dest);
  959. return status;
  960. }
  961. /* Reads the input registers of remote device and put the data into an array */
  962. int modbus_read_input_registers(modbus_t *ctx, int addr, int nb,
  963. uint16_t *dest)
  964. {
  965. int status;
  966. if (nb > MODBUS_MAX_READ_REGISTERS) {
  967. fprintf(stderr,
  968. "ERROR Too many input registers requested (%d > %d)\n",
  969. nb, MODBUS_MAX_READ_REGISTERS);
  970. errno = EMBMDATA;
  971. return -1;
  972. }
  973. status = read_registers(ctx, _FC_READ_INPUT_REGISTERS,
  974. addr, nb, dest);
  975. return status;
  976. }
  977. /* Write a value to the specified register of the remote device.
  978. Used by write_bit and write_register */
  979. static int write_single(modbus_t *ctx, int function, int addr, int value)
  980. {
  981. int rc;
  982. int req_length;
  983. uint8_t req[_MIN_REQ_LENGTH];
  984. req_length = ctx->backend->build_request_basis(ctx, function, addr, value, req);
  985. rc = send_msg(ctx, req, req_length);
  986. if (rc > 0) {
  987. /* Used by write_bit and write_register */
  988. uint8_t rsp[_MIN_REQ_LENGTH];
  989. rc = receive_msg(ctx, rsp, MSG_CONFIRMATION);
  990. if (rc == -1)
  991. return -1;
  992. rc = check_confirmation(ctx, req, rsp, rc);
  993. }
  994. return rc;
  995. }
  996. /* Turns ON or OFF a single bit of the remote device */
  997. int modbus_write_bit(modbus_t *ctx, int addr, int status)
  998. {
  999. return write_single(ctx, _FC_WRITE_SINGLE_COIL, addr,
  1000. status ? 0xFF00 : 0);
  1001. }
  1002. /* Writes a value in one register of the remote device */
  1003. int modbus_write_register(modbus_t *ctx, int addr, int value)
  1004. {
  1005. return write_single(ctx, _FC_WRITE_SINGLE_REGISTER, addr, value);
  1006. }
  1007. /* Write the bits of the array in the remote device */
  1008. int modbus_write_bits(modbus_t *ctx, int addr, int nb, const uint8_t *src)
  1009. {
  1010. int rc;
  1011. int i;
  1012. int byte_count;
  1013. int req_length;
  1014. int bit_check = 0;
  1015. int pos = 0;
  1016. uint8_t req[MAX_MESSAGE_LENGTH];
  1017. if (nb > MODBUS_MAX_WRITE_BITS) {
  1018. if (ctx->debug) {
  1019. fprintf(stderr, "ERROR Writing too many bits (%d > %d)\n",
  1020. nb, MODBUS_MAX_WRITE_BITS);
  1021. }
  1022. errno = EMBMDATA;
  1023. return -1;
  1024. }
  1025. req_length = ctx->backend->build_request_basis(ctx,
  1026. _FC_WRITE_MULTIPLE_COILS,
  1027. addr, nb, req);
  1028. byte_count = (nb / 8) + ((nb % 8) ? 1 : 0);
  1029. req[req_length++] = byte_count;
  1030. for (i = 0; i < byte_count; i++) {
  1031. int bit;
  1032. bit = 0x01;
  1033. req[req_length] = 0;
  1034. while ((bit & 0xFF) && (bit_check++ < nb)) {
  1035. if (src[pos++])
  1036. req[req_length] |= bit;
  1037. else
  1038. req[req_length] &=~ bit;
  1039. bit = bit << 1;
  1040. }
  1041. req_length++;
  1042. }
  1043. rc = send_msg(ctx, req, req_length);
  1044. if (rc > 0) {
  1045. uint8_t rsp[MAX_MESSAGE_LENGTH];
  1046. rc = receive_msg(ctx, rsp, MSG_CONFIRMATION);
  1047. if (rc == -1)
  1048. return -1;
  1049. rc = check_confirmation(ctx, req, rsp, rc);
  1050. }
  1051. return rc;
  1052. }
  1053. /* Write the values from the array to the registers of the remote device */
  1054. int modbus_write_registers(modbus_t *ctx, int addr, int nb, const uint16_t *src)
  1055. {
  1056. int rc;
  1057. int i;
  1058. int req_length;
  1059. int byte_count;
  1060. uint8_t req[MAX_MESSAGE_LENGTH];
  1061. if (nb > MODBUS_MAX_WRITE_REGISTERS) {
  1062. if (ctx->debug) {
  1063. fprintf(stderr,
  1064. "ERROR Trying to write to too many registers (%d > %d)\n",
  1065. nb, MODBUS_MAX_WRITE_REGISTERS);
  1066. }
  1067. errno = EMBMDATA;
  1068. return -1;
  1069. }
  1070. req_length = ctx->backend->build_request_basis(ctx,
  1071. _FC_WRITE_MULTIPLE_REGISTERS,
  1072. addr, nb, req);
  1073. byte_count = nb * 2;
  1074. req[req_length++] = byte_count;
  1075. for (i = 0; i < nb; i++) {
  1076. req[req_length++] = src[i] >> 8;
  1077. req[req_length++] = src[i] & 0x00FF;
  1078. }
  1079. rc = send_msg(ctx, req, req_length);
  1080. if (rc > 0) {
  1081. uint8_t rsp[MAX_MESSAGE_LENGTH];
  1082. rc = receive_msg(ctx, rsp, MSG_CONFIRMATION);
  1083. if (rc == -1)
  1084. return -1;
  1085. rc = check_confirmation(ctx, req, rsp, rc);
  1086. }
  1087. return rc;
  1088. }
  1089. /* Read multiple registers from remote device to dest array and write multiple
  1090. registers to remote device from data array. */
  1091. int modbus_read_and_write_registers(modbus_t *ctx,
  1092. int read_addr, int read_nb, uint16_t *dest,
  1093. int write_addr, int write_nb, const uint16_t *data)
  1094. {
  1095. int rc;
  1096. int req_length;
  1097. int i;
  1098. int byte_count;
  1099. uint8_t req[MAX_MESSAGE_LENGTH];
  1100. uint8_t rsp[MAX_MESSAGE_LENGTH];
  1101. if (read_nb > MODBUS_MAX_READ_REGISTERS) {
  1102. if (ctx->debug) {
  1103. fprintf(stderr,
  1104. "ERROR Too many registers requested (%d > %d)\n",
  1105. read_nb, MODBUS_MAX_READ_REGISTERS);
  1106. }
  1107. errno = EMBMDATA;
  1108. return -1;
  1109. }
  1110. if (write_nb > MODBUS_MAX_RW_WRITE_REGISTERS) {
  1111. if (ctx->debug) {
  1112. fprintf(stderr,
  1113. "ERROR Too many registers to write (%d > %d)\n",
  1114. write_nb, MODBUS_MAX_RW_WRITE_REGISTERS);
  1115. }
  1116. errno = EMBMDATA;
  1117. return -1;
  1118. }
  1119. req_length = ctx->backend->build_request_basis(ctx,
  1120. _FC_READ_AND_WRITE_REGISTERS,
  1121. read_addr, read_nb, req);
  1122. req[req_length++] = write_addr >> 8;
  1123. req[req_length++] = write_addr & 0x00ff;
  1124. req[req_length++] = write_nb >> 8;
  1125. req[req_length++] = write_nb & 0x00ff;
  1126. byte_count = write_nb * 2;
  1127. req[req_length++] = byte_count;
  1128. for (i = 0; i < write_nb; i++) {
  1129. req[req_length++] = data[i] >> 8;
  1130. req[req_length++] = data[i] & 0x00FF;
  1131. }
  1132. rc = send_msg(ctx, req, req_length);
  1133. if (rc > 0) {
  1134. int offset;
  1135. rc = receive_msg(ctx, rsp, MSG_CONFIRMATION);
  1136. if (rc == -1)
  1137. return -1;
  1138. rc = check_confirmation(ctx, req, rsp, rc);
  1139. if (rc == -1)
  1140. return -1;
  1141. offset = ctx->backend->header_length;
  1142. /* If rc is negative, the loop is jumped ! */
  1143. for (i = 0; i < rc; i++) {
  1144. /* shift reg hi_byte to temp OR with lo_byte */
  1145. dest[i] = (rsp[offset + 2 + (i << 1)] << 8) |
  1146. rsp[offset + 3 + (i << 1)];
  1147. }
  1148. }
  1149. return rc;
  1150. }
  1151. /* Send a request to get the slave ID of the device (only available in serial
  1152. communication). */
  1153. int modbus_report_slave_id(modbus_t *ctx, uint8_t *dest)
  1154. {
  1155. int rc;
  1156. int req_length;
  1157. uint8_t req[_MIN_REQ_LENGTH];
  1158. req_length = ctx->backend->build_request_basis(ctx, _FC_REPORT_SLAVE_ID,
  1159. 0, 0, req);
  1160. /* HACKISH, addr and count are not used */
  1161. req_length -= 4;
  1162. rc = send_msg(ctx, req, req_length);
  1163. if (rc > 0) {
  1164. int i;
  1165. int offset;
  1166. uint8_t rsp[MAX_MESSAGE_LENGTH];
  1167. rc = receive_msg(ctx, rsp, MSG_CONFIRMATION);
  1168. if (rc == -1)
  1169. return -1;
  1170. rc = check_confirmation(ctx, req, rsp, rc);
  1171. if (rc == -1)
  1172. return -1;
  1173. offset = ctx->backend->header_length + 2;
  1174. /* Byte count, slave id, run indicator status,
  1175. additional data */
  1176. for (i=0; i < rc; i++) {
  1177. dest[i] = rsp[offset + i];
  1178. }
  1179. }
  1180. return rc;
  1181. }
  1182. void _modbus_init_common(modbus_t *ctx)
  1183. {
  1184. /* Slave and socket are initialized to -1 */
  1185. ctx->slave = -1;
  1186. ctx->s = -1;
  1187. ctx->debug = FALSE;
  1188. ctx->error_recovery = MODBUS_ERROR_RECOVERY_NONE;
  1189. ctx->response_timeout.tv_sec = 0;
  1190. ctx->response_timeout.tv_usec = _RESPONSE_TIMEOUT;
  1191. ctx->byte_timeout.tv_sec = 0;
  1192. ctx->byte_timeout.tv_usec = _BYTE_TIMEOUT;
  1193. }
  1194. /* Define the slave number */
  1195. int modbus_set_slave(modbus_t *ctx, int slave)
  1196. {
  1197. return ctx->backend->set_slave(ctx, slave);
  1198. }
  1199. int modbus_set_error_recovery(modbus_t *ctx,
  1200. modbus_error_recovery_mode error_recovery)
  1201. {
  1202. if (error_recovery >= 0) {
  1203. ctx->error_recovery = (uint8_t) error_recovery;
  1204. } else {
  1205. errno = EINVAL;
  1206. return -1;
  1207. }
  1208. return 0;
  1209. }
  1210. void modbus_set_socket(modbus_t *ctx, int socket)
  1211. {
  1212. ctx->s = socket;
  1213. }
  1214. int modbus_get_socket(modbus_t *ctx)
  1215. {
  1216. return ctx->s;
  1217. }
  1218. /* Get the timeout interval used to wait for a response */
  1219. void modbus_get_response_timeout(modbus_t *ctx, struct timeval *timeout)
  1220. {
  1221. *timeout = ctx->response_timeout;
  1222. }
  1223. void modbus_set_response_timeout(modbus_t *ctx, const struct timeval *timeout)
  1224. {
  1225. ctx->response_timeout = *timeout;
  1226. }
  1227. /* Get the timeout interval between two consecutive bytes of a message */
  1228. void modbus_get_byte_timeout(modbus_t *ctx, struct timeval *timeout)
  1229. {
  1230. *timeout = ctx->byte_timeout;
  1231. }
  1232. void modbus_set_byte_timeout(modbus_t *ctx, const struct timeval *timeout)
  1233. {
  1234. ctx->byte_timeout = *timeout;
  1235. }
  1236. int modbus_get_header_length(modbus_t *ctx)
  1237. {
  1238. return ctx->backend->header_length;
  1239. }
  1240. int modbus_connect(modbus_t *ctx)
  1241. {
  1242. return ctx->backend->connect(ctx);
  1243. }
  1244. void modbus_close(modbus_t *ctx)
  1245. {
  1246. if (ctx == NULL)
  1247. return;
  1248. ctx->backend->close(ctx);
  1249. }
  1250. void modbus_free(modbus_t *ctx)
  1251. {
  1252. if (ctx == NULL)
  1253. return;
  1254. free(ctx->backend_data);
  1255. free(ctx);
  1256. }
  1257. void modbus_set_debug(modbus_t *ctx, int boolean)
  1258. {
  1259. ctx->debug = boolean;
  1260. }
  1261. /* Allocates 4 arrays to store bits, input bits, registers and inputs
  1262. registers. The pointers are stored in modbus_mapping structure.
  1263. The modbus_mapping_new() function shall return the new allocated structure if
  1264. successful. Otherwise it shall return NULL and set errno to ENOMEM. */
  1265. modbus_mapping_t* modbus_mapping_new(int nb_bits, int nb_input_bits,
  1266. int nb_registers, int nb_input_registers)
  1267. {
  1268. modbus_mapping_t *mb_mapping;
  1269. mb_mapping = (modbus_mapping_t *)malloc(sizeof(modbus_mapping_t));
  1270. if (mb_mapping == NULL) {
  1271. return NULL;
  1272. }
  1273. /* 0X */
  1274. mb_mapping->nb_bits = nb_bits;
  1275. if (nb_bits == 0) {
  1276. mb_mapping->tab_bits = NULL;
  1277. } else {
  1278. /* Negative number raises a POSIX error */
  1279. mb_mapping->tab_bits =
  1280. (uint8_t *) malloc(nb_bits * sizeof(uint8_t));
  1281. if (mb_mapping->tab_bits == NULL) {
  1282. free(mb_mapping);
  1283. return NULL;
  1284. }
  1285. memset(mb_mapping->tab_bits, 0, nb_bits * sizeof(uint8_t));
  1286. }
  1287. /* 1X */
  1288. mb_mapping->nb_input_bits = nb_input_bits;
  1289. if (nb_input_bits == 0) {
  1290. mb_mapping->tab_input_bits = NULL;
  1291. } else {
  1292. mb_mapping->tab_input_bits =
  1293. (uint8_t *) malloc(nb_input_bits * sizeof(uint8_t));
  1294. if (mb_mapping->tab_input_bits == NULL) {
  1295. free(mb_mapping->tab_bits);
  1296. free(mb_mapping);
  1297. return NULL;
  1298. }
  1299. memset(mb_mapping->tab_input_bits, 0, nb_input_bits * sizeof(uint8_t));
  1300. }
  1301. /* 4X */
  1302. mb_mapping->nb_registers = nb_registers;
  1303. if (nb_registers == 0) {
  1304. mb_mapping->tab_registers = NULL;
  1305. } else {
  1306. mb_mapping->tab_registers =
  1307. (uint16_t *) malloc(nb_registers * sizeof(uint16_t));
  1308. if (mb_mapping->tab_registers == NULL) {
  1309. free(mb_mapping->tab_input_bits);
  1310. free(mb_mapping->tab_bits);
  1311. free(mb_mapping);
  1312. return NULL;
  1313. }
  1314. memset(mb_mapping->tab_registers, 0, nb_registers * sizeof(uint16_t));
  1315. }
  1316. /* 3X */
  1317. mb_mapping->nb_input_registers = nb_input_registers;
  1318. if (nb_input_registers == 0) {
  1319. mb_mapping->tab_input_registers = NULL;
  1320. } else {
  1321. mb_mapping->tab_input_registers =
  1322. (uint16_t *) malloc(nb_input_registers * sizeof(uint16_t));
  1323. if (mb_mapping->tab_input_registers == NULL) {
  1324. free(mb_mapping->tab_registers);
  1325. free(mb_mapping->tab_input_bits);
  1326. free(mb_mapping->tab_bits);
  1327. free(mb_mapping);
  1328. return NULL;
  1329. }
  1330. memset(mb_mapping->tab_input_registers, 0,
  1331. nb_input_registers * sizeof(uint16_t));
  1332. }
  1333. return mb_mapping;
  1334. }
  1335. /* Frees the 4 arrays */
  1336. void modbus_mapping_free(modbus_mapping_t *mb_mapping)
  1337. {
  1338. free(mb_mapping->tab_input_registers);
  1339. free(mb_mapping->tab_registers);
  1340. free(mb_mapping->tab_input_bits);
  1341. free(mb_mapping->tab_bits);
  1342. free(mb_mapping);
  1343. }
  1344. #ifndef HAVE_STRLCPY
  1345. /*
  1346. * Function strlcpy was originally developed by
  1347. * Todd C. Miller <Todd.Miller@courtesan.com> to simplify writing secure code.
  1348. * See ftp://ftp.openbsd.org/pub/OpenBSD/src/lib/libc/string/strlcpy.3
  1349. * for more information.
  1350. *
  1351. * Thank you Ulrich Drepper... not!
  1352. *
  1353. * Copy src to string dest of size dest_size. At most dest_size-1 characters
  1354. * will be copied. Always NUL terminates (unless dest_size == 0). Returns
  1355. * strlen(src); if retval >= dest_size, truncation occurred.
  1356. */
  1357. size_t strlcpy(char *dest, const char *src, size_t dest_size)
  1358. {
  1359. register char *d = dest;
  1360. register const char *s = src;
  1361. register size_t n = dest_size;
  1362. /* Copy as many bytes as will fit */
  1363. if (n != 0 && --n != 0) {
  1364. do {
  1365. if ((*d++ = *s++) == 0)
  1366. break;
  1367. } while (--n != 0);
  1368. }
  1369. /* Not enough room in dest, add NUL and traverse rest of src */
  1370. if (n == 0) {
  1371. if (dest_size != 0)
  1372. *d = '\0'; /* NUL-terminate dest */
  1373. while (*s++)
  1374. ;
  1375. }
  1376. return (s - src - 1); /* count does not include NUL */
  1377. }
  1378. #endif