modbus.c 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034
  1. /*
  2. * Copyright © Stéphane Raimbault <stephane.raimbault@gmail.com>
  3. *
  4. * SPDX-License-Identifier: LGPL-2.1-or-later
  5. *
  6. * This library implements the Modbus protocol.
  7. * http://libmodbus.org/
  8. */
  9. #include <errno.h>
  10. #include <limits.h>
  11. #include <stdarg.h>
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <string.h>
  15. #include <time.h>
  16. #include <syslog.h>
  17. #ifndef _MSC_VER
  18. #include <unistd.h>
  19. #endif
  20. #include <config.h>
  21. #include "modbus-private.h"
  22. #include "modbus.h"
  23. /* Internal use */
  24. #define MSG_LENGTH_UNDEFINED -1
  25. /* Exported version */
  26. const unsigned int libmodbus_version_major = LIBMODBUS_VERSION_MAJOR;
  27. const unsigned int libmodbus_version_minor = LIBMODBUS_VERSION_MINOR;
  28. const unsigned int libmodbus_version_micro = LIBMODBUS_VERSION_MICRO;
  29. /* Max between RTU and TCP max adu length (so TCP) */
  30. #define MAX_MESSAGE_LENGTH 260
  31. /* 3 steps are used to parse the query */
  32. typedef enum {
  33. _STEP_FUNCTION,
  34. _STEP_META,
  35. _STEP_DATA
  36. } _step_t;
  37. const char *modbus_strerror(int errnum)
  38. {
  39. switch (errnum) {
  40. case EMBXILFUN:
  41. return "Illegal function";
  42. case EMBXILADD:
  43. return "Illegal data address";
  44. case EMBXILVAL:
  45. return "Illegal data value";
  46. case EMBXSFAIL:
  47. return "Slave device or server failure";
  48. case EMBXACK:
  49. return "Acknowledge";
  50. case EMBXSBUSY:
  51. return "Slave device or server is busy";
  52. case EMBXNACK:
  53. return "Negative acknowledge";
  54. case EMBXMEMPAR:
  55. return "Memory parity error";
  56. case EMBXGPATH:
  57. return "Gateway path unavailable";
  58. case EMBXGTAR:
  59. return "Target device failed to respond";
  60. case EMBBADCRC:
  61. return "Invalid CRC";
  62. case EMBBADDATA:
  63. return "Invalid data";
  64. case EMBBADEXC:
  65. return "Invalid exception code";
  66. case EMBMDATA:
  67. return "Too many data";
  68. case EMBBADSLAVE:
  69. return "Response not from requested slave";
  70. default:
  71. return strerror(errnum);
  72. }
  73. }
  74. void _error_print(modbus_t *ctx, const char *context)
  75. {
  76. if (ctx->debug) {
  77. fprintf(stderr, "ERROR %s", modbus_strerror(errno));
  78. if (context != NULL) {
  79. fprintf(stderr, ": %s\n", context);
  80. } else {
  81. fprintf(stderr, "\n");
  82. }
  83. }
  84. }
  85. static void _sleep_response_timeout(modbus_t *ctx)
  86. {
  87. /* Response timeout is always positive */
  88. /* usleep source code */
  89. struct timespec request, remaining;
  90. request.tv_sec = ctx->response_timeout.tv_sec;
  91. request.tv_nsec = ((long int) ctx->response_timeout.tv_usec) * 1000;
  92. while (nanosleep(&request, &remaining) == -1 && errno == EINTR) {
  93. request = remaining;
  94. }
  95. }
  96. int modbus_flush(modbus_t *ctx)
  97. {
  98. int rc;
  99. if (ctx == NULL) {
  100. errno = EINVAL;
  101. return -1;
  102. }
  103. rc = ctx->backend->flush(ctx);
  104. if (rc != -1 && ctx->debug) {
  105. /* Not all backends are able to return the number of bytes flushed */
  106. printf("Bytes flushed (%d)\n", rc);
  107. }
  108. return rc;
  109. }
  110. /* Computes the length of the expected response */
  111. static unsigned int compute_response_length_from_request(modbus_t *ctx, uint8_t *req)
  112. {
  113. int length;
  114. const int offset = ctx->backend->header_length;
  115. switch (req[offset]) {
  116. case MODBUS_FC_READ_COILS:
  117. case MODBUS_FC_READ_DISCRETE_INPUTS: {
  118. /* Header + nb values (code from write_bits) */
  119. int nb = (req[offset + 3] << 8) | req[offset + 4];
  120. length = 2 + (nb / 8) + ((nb % 8) ? 1 : 0);
  121. } break;
  122. case MODBUS_FC_WRITE_AND_READ_REGISTERS:
  123. case MODBUS_FC_READ_HOLDING_REGISTERS:
  124. case MODBUS_FC_READ_INPUT_REGISTERS:
  125. /* Header + 2 * nb values */
  126. length = 2 + 2 * (req[offset + 3] << 8 | req[offset + 4]);
  127. break;
  128. case MODBUS_FC_READ_EXCEPTION_STATUS:
  129. length = 3;
  130. break;
  131. case MODBUS_FC_REPORT_SLAVE_ID:
  132. /* The response is device specific (the header provides the
  133. length) */
  134. return MSG_LENGTH_UNDEFINED;
  135. case MODBUS_FC_MASK_WRITE_REGISTER:
  136. length = 7;
  137. break;
  138. default:
  139. length = 5;
  140. }
  141. return offset + length + ctx->backend->checksum_length;
  142. }
  143. /* Sends a request/response */
  144. static int send_msg(modbus_t *ctx, uint8_t *msg, int msg_length)
  145. {
  146. int rc;
  147. int i;
  148. msg_length = ctx->backend->send_msg_pre(msg, msg_length);
  149. if (ctx->debug) {
  150. for (i = 0; i < msg_length; i++)
  151. printf("[%.2X]", msg[i]);
  152. printf("\n");
  153. }
  154. /* In recovery mode, the write command will be issued until to be
  155. successful! Disabled by default. */
  156. do {
  157. rc = ctx->backend->send(ctx, msg, msg_length);
  158. if (rc == -1) {
  159. _error_print(ctx, NULL);
  160. if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_LINK) {
  161. int saved_errno = errno;
  162. if ((errno == EBADF || errno == ECONNRESET || errno == EPIPE)) {
  163. modbus_close(ctx);
  164. _sleep_response_timeout(ctx);
  165. modbus_connect(ctx);
  166. } else {
  167. _sleep_response_timeout(ctx);
  168. modbus_flush(ctx);
  169. }
  170. errno = saved_errno;
  171. }
  172. }
  173. } while ((ctx->error_recovery & MODBUS_ERROR_RECOVERY_LINK) && rc == -1);
  174. if (rc > 0 && rc != msg_length) {
  175. errno = EMBBADDATA;
  176. return -1;
  177. }
  178. return rc;
  179. }
  180. int modbus_send_raw_request(modbus_t *ctx, const uint8_t *raw_req, int raw_req_length)
  181. {
  182. sft_t sft;
  183. uint8_t req[MAX_MESSAGE_LENGTH];
  184. int req_length;
  185. if (ctx == NULL) {
  186. errno = EINVAL;
  187. return -1;
  188. }
  189. if (raw_req_length < 2 || raw_req_length > (MODBUS_MAX_PDU_LENGTH + 1)) {
  190. /* The raw request must contain function and slave at least and
  191. must not be longer than the maximum pdu length plus the slave
  192. address. */
  193. errno = EINVAL;
  194. return -1;
  195. }
  196. sft.slave = raw_req[0];
  197. sft.function = raw_req[1];
  198. /* The t_id is left to zero */
  199. sft.t_id = 0;
  200. /* This response function only set the header so it's convenient here */
  201. req_length = ctx->backend->build_response_basis(&sft, req);
  202. if (raw_req_length > 2) {
  203. /* Copy data after function code */
  204. memcpy(req + req_length, raw_req + 2, raw_req_length - 2);
  205. req_length += raw_req_length - 2;
  206. }
  207. return send_msg(ctx, req, req_length);
  208. }
  209. /*
  210. * ---------- Request Indication ----------
  211. * | Client | ---------------------->| Server |
  212. * ---------- Confirmation Response ----------
  213. */
  214. /* Computes the length to read after the function received */
  215. static uint8_t compute_meta_length_after_function(int function, msg_type_t msg_type)
  216. {
  217. int length;
  218. if (msg_type == MSG_INDICATION) {
  219. if (function <= MODBUS_FC_WRITE_SINGLE_REGISTER) {
  220. length = 4;
  221. } else if (function == MODBUS_FC_WRITE_MULTIPLE_COILS ||
  222. function == MODBUS_FC_WRITE_MULTIPLE_REGISTERS) {
  223. length = 5;
  224. } else if (function == MODBUS_FC_MASK_WRITE_REGISTER) {
  225. length = 6;
  226. } else if (function == MODBUS_FC_WRITE_AND_READ_REGISTERS) {
  227. length = 9;
  228. } else {
  229. /* MODBUS_FC_READ_EXCEPTION_STATUS, MODBUS_FC_REPORT_SLAVE_ID */
  230. length = 0;
  231. }
  232. } else {
  233. /* MSG_CONFIRMATION */
  234. switch (function) {
  235. case MODBUS_FC_WRITE_SINGLE_COIL:
  236. case MODBUS_FC_WRITE_SINGLE_REGISTER:
  237. case MODBUS_FC_WRITE_MULTIPLE_COILS:
  238. case MODBUS_FC_WRITE_MULTIPLE_REGISTERS:
  239. length = 4;
  240. break;
  241. case MODBUS_FC_MASK_WRITE_REGISTER:
  242. length = 6;
  243. break;
  244. default:
  245. length = 1;
  246. }
  247. }
  248. return length;
  249. }
  250. /* Computes the length to read after the meta information (address, count, etc) */
  251. static int
  252. compute_data_length_after_meta(modbus_t *ctx, uint8_t *msg, msg_type_t msg_type)
  253. {
  254. int function = msg[ctx->backend->header_length];
  255. int length;
  256. if (msg_type == MSG_INDICATION) {
  257. switch (function) {
  258. case MODBUS_FC_WRITE_MULTIPLE_COILS:
  259. case MODBUS_FC_WRITE_MULTIPLE_REGISTERS:
  260. length = msg[ctx->backend->header_length + 5];
  261. break;
  262. case MODBUS_FC_WRITE_AND_READ_REGISTERS:
  263. length = msg[ctx->backend->header_length + 9];
  264. break;
  265. default:
  266. length = 0;
  267. }
  268. } else {
  269. /* MSG_CONFIRMATION */
  270. if (function <= MODBUS_FC_READ_INPUT_REGISTERS ||
  271. function == MODBUS_FC_REPORT_SLAVE_ID ||
  272. function == MODBUS_FC_WRITE_AND_READ_REGISTERS) {
  273. length = msg[ctx->backend->header_length + 1];
  274. } else {
  275. length = 0;
  276. }
  277. }
  278. length += ctx->backend->checksum_length;
  279. return length;
  280. }
  281. /* Waits a response from a modbus server or a request from a modbus client.
  282. This function blocks if there is no replies (3 timeouts).
  283. The function shall return the number of received characters and the received
  284. message in an array of uint8_t if successful. Otherwise it shall return -1
  285. and errno is set to one of the values defined below:
  286. - ECONNRESET
  287. - EMBBADDATA
  288. - ETIMEDOUT
  289. - read() or recv() error codes
  290. */
  291. int _modbus_receive_msg(modbus_t *ctx, uint8_t *msg, msg_type_t msg_type)
  292. {
  293. int rc;
  294. fd_set rset;
  295. struct timeval tv;
  296. struct timeval *p_tv;
  297. unsigned int length_to_read;
  298. int msg_length = 0;
  299. _step_t step;
  300. if (ctx->debug) {
  301. if (msg_type == MSG_INDICATION) {
  302. printf("Waiting for an indication...\n");
  303. } else {
  304. printf("Waiting for a confirmation...\n");
  305. }
  306. }
  307. if (!ctx->backend->is_connected(ctx)) {
  308. if (ctx->debug) {
  309. fprintf(stderr, "ERROR The connection is not established.\n");
  310. }
  311. return -1;
  312. }
  313. /* Add a file descriptor to the set */
  314. FD_ZERO(&rset);
  315. FD_SET(ctx->s, &rset);
  316. /* We need to analyse the message step by step. At the first step, we want
  317. * to reach the function code because all packets contain this
  318. * information. */
  319. step = _STEP_FUNCTION;
  320. length_to_read = ctx->backend->header_length + 1;
  321. if (msg_type == MSG_INDICATION) {
  322. /* Wait for a message, we don't know when the message will be
  323. * received */
  324. if (ctx->indication_timeout.tv_sec == 0 && ctx->indication_timeout.tv_usec == 0) {
  325. /* By default, the indication timeout isn't set */
  326. p_tv = NULL;
  327. } else {
  328. /* Wait for an indication (name of a received request by a server, see schema)
  329. */
  330. tv.tv_sec = ctx->indication_timeout.tv_sec;
  331. tv.tv_usec = ctx->indication_timeout.tv_usec;
  332. p_tv = &tv;
  333. }
  334. } else {
  335. tv.tv_sec = ctx->response_timeout.tv_sec;
  336. tv.tv_usec = ctx->response_timeout.tv_usec;
  337. p_tv = &tv;
  338. }
  339. while (length_to_read != 0) {
  340. rc = ctx->backend->select(ctx, &rset, p_tv, length_to_read);
  341. if (rc == -1) {
  342. _error_print(ctx, "select");
  343. if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_LINK) {
  344. int saved_errno = errno;
  345. if (errno == ETIMEDOUT) {
  346. _sleep_response_timeout(ctx);
  347. modbus_flush(ctx);
  348. } else if (errno == EBADF) {
  349. modbus_close(ctx);
  350. modbus_connect(ctx);
  351. }
  352. errno = saved_errno;
  353. }
  354. return -1;
  355. }
  356. rc = ctx->backend->recv(ctx, msg + msg_length, length_to_read);
  357. if (rc == 0) {
  358. errno = ECONNRESET;
  359. rc = -1;
  360. }
  361. if (rc == -1) {
  362. _error_print(ctx, "read");
  363. if ((ctx->error_recovery & MODBUS_ERROR_RECOVERY_LINK) &&
  364. (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_TCP) &&
  365. (errno == ECONNRESET || errno == ECONNREFUSED || errno == EBADF)) {
  366. int saved_errno = errno;
  367. modbus_close(ctx);
  368. modbus_connect(ctx);
  369. /* Could be removed by previous calls */
  370. errno = saved_errno;
  371. }
  372. return -1;
  373. }
  374. /* Display the hex code of each character received */
  375. if (ctx->debug) {
  376. int i;
  377. for (i = 0; i < rc; i++)
  378. printf("<%.2X>", msg[msg_length + i]);
  379. }
  380. /* Sums bytes received */
  381. msg_length += rc;
  382. /* Computes remaining bytes */
  383. length_to_read -= rc;
  384. if (length_to_read == 0) {
  385. switch (step) {
  386. case _STEP_FUNCTION:
  387. /* Function code position */
  388. length_to_read = compute_meta_length_after_function(
  389. msg[ctx->backend->header_length], msg_type);
  390. if (length_to_read != 0) {
  391. step = _STEP_META;
  392. break;
  393. } /* else switches straight to the next step */
  394. case _STEP_META:
  395. length_to_read = compute_data_length_after_meta(ctx, msg, msg_type);
  396. if ((msg_length + length_to_read) > ctx->backend->max_adu_length) {
  397. errno = EMBBADDATA;
  398. _error_print(ctx, "too many data");
  399. return -1;
  400. }
  401. step = _STEP_DATA;
  402. break;
  403. default:
  404. break;
  405. }
  406. }
  407. if (length_to_read > 0 &&
  408. (ctx->byte_timeout.tv_sec > 0 || ctx->byte_timeout.tv_usec > 0)) {
  409. /* If there is no character in the buffer, the allowed timeout
  410. interval between two consecutive bytes is defined by
  411. byte_timeout */
  412. tv.tv_sec = ctx->byte_timeout.tv_sec;
  413. tv.tv_usec = ctx->byte_timeout.tv_usec;
  414. p_tv = &tv;
  415. }
  416. /* else timeout isn't set again, the full response must be read before
  417. expiration of response timeout (for CONFIRMATION only) */
  418. }
  419. if (ctx->debug)
  420. printf("\n");
  421. return ctx->backend->check_integrity(ctx, msg, msg_length);
  422. }
  423. /* Receive the request from a modbus master */
  424. int modbus_receive(modbus_t *ctx, uint8_t *req)
  425. {
  426. if (ctx == NULL) {
  427. errno = EINVAL;
  428. return -1;
  429. }
  430. return ctx->backend->receive(ctx, req);
  431. }
  432. /* Receives the confirmation.
  433. The function shall store the read response in rsp and return the number of
  434. values (bits or words). Otherwise, its shall return -1 and errno is set.
  435. The function doesn't check the confirmation is the expected response to the
  436. initial request.
  437. */
  438. int modbus_receive_confirmation(modbus_t *ctx, uint8_t *rsp)
  439. {
  440. if (ctx == NULL) {
  441. errno = EINVAL;
  442. return -1;
  443. }
  444. return _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
  445. }
  446. static int check_confirmation(modbus_t *ctx, uint8_t *req, uint8_t *rsp, int rsp_length)
  447. {
  448. int rc;
  449. int rsp_length_computed;
  450. const unsigned int offset = ctx->backend->header_length;
  451. const int function = rsp[offset];
  452. if (ctx->backend->pre_check_confirmation) {
  453. rc = ctx->backend->pre_check_confirmation(ctx, req, rsp, rsp_length);
  454. if (rc == -1) {
  455. if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) {
  456. _sleep_response_timeout(ctx);
  457. modbus_flush(ctx);
  458. }
  459. return -1;
  460. }
  461. }
  462. rsp_length_computed = compute_response_length_from_request(ctx, req);
  463. /* Exception code */
  464. if (function >= 0x80) {
  465. if (rsp_length == (int) (offset + 2 + ctx->backend->checksum_length) &&
  466. req[offset] == (rsp[offset] - 0x80)) {
  467. /* Valid exception code received */
  468. int exception_code = rsp[offset + 1];
  469. if (exception_code < MODBUS_EXCEPTION_MAX) {
  470. errno = MODBUS_ENOBASE + exception_code;
  471. } else {
  472. errno = EMBBADEXC;
  473. }
  474. _error_print(ctx, NULL);
  475. return -1;
  476. } else {
  477. errno = EMBBADEXC;
  478. _error_print(ctx, NULL);
  479. return -1;
  480. }
  481. }
  482. /* Check length */
  483. if ((rsp_length == rsp_length_computed ||
  484. rsp_length_computed == MSG_LENGTH_UNDEFINED) &&
  485. function < 0x80) {
  486. int req_nb_value;
  487. int rsp_nb_value;
  488. int resp_addr_ok = TRUE;
  489. int resp_data_ok = TRUE;
  490. /* Check function code */
  491. if (function != req[offset]) {
  492. if (ctx->debug) {
  493. fprintf(
  494. stderr,
  495. "Received function not corresponding to the request (0x%X != 0x%X)\n",
  496. function,
  497. req[offset]);
  498. }
  499. if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) {
  500. _sleep_response_timeout(ctx);
  501. modbus_flush(ctx);
  502. }
  503. errno = EMBBADDATA;
  504. return -1;
  505. }
  506. /* Check the number of values is corresponding to the request */
  507. switch (function) {
  508. case MODBUS_FC_READ_COILS:
  509. case MODBUS_FC_READ_DISCRETE_INPUTS:
  510. /* Read functions, 8 values in a byte (nb
  511. * of values in the request and byte count in
  512. * the response. */
  513. req_nb_value = (req[offset + 3] << 8) + req[offset + 4];
  514. req_nb_value = (req_nb_value / 8) + ((req_nb_value % 8) ? 1 : 0);
  515. rsp_nb_value = rsp[offset + 1];
  516. break;
  517. case MODBUS_FC_WRITE_AND_READ_REGISTERS:
  518. case MODBUS_FC_READ_HOLDING_REGISTERS:
  519. case MODBUS_FC_READ_INPUT_REGISTERS:
  520. /* Read functions 1 value = 2 bytes */
  521. req_nb_value = (req[offset + 3] << 8) + req[offset + 4];
  522. rsp_nb_value = (rsp[offset + 1] / 2);
  523. break;
  524. case MODBUS_FC_WRITE_MULTIPLE_COILS:
  525. case MODBUS_FC_WRITE_MULTIPLE_REGISTERS:
  526. /* address in request and response must be equal */
  527. if ((req[offset + 1] != rsp[offset + 1]) ||
  528. (req[offset + 2] != rsp[offset + 2])) {
  529. resp_addr_ok = FALSE;
  530. }
  531. /* N Write functions */
  532. req_nb_value = (req[offset + 3] << 8) + req[offset + 4];
  533. rsp_nb_value = (rsp[offset + 3] << 8) | rsp[offset + 4];
  534. break;
  535. case MODBUS_FC_REPORT_SLAVE_ID:
  536. /* Report slave ID (bytes received) */
  537. req_nb_value = rsp_nb_value = rsp[offset + 1];
  538. break;
  539. case MODBUS_FC_WRITE_SINGLE_COIL:
  540. case MODBUS_FC_WRITE_SINGLE_REGISTER:
  541. /* address in request and response must be equal */
  542. if ((req[offset + 1] != rsp[offset + 1]) ||
  543. (req[offset + 2] != rsp[offset + 2])) {
  544. resp_addr_ok = FALSE;
  545. }
  546. /* data in request and response must be equal */
  547. if ((req[offset + 3] != rsp[offset + 3]) ||
  548. (req[offset + 4] != rsp[offset + 4])) {
  549. resp_data_ok = FALSE;
  550. }
  551. /* 1 Write functions & others */
  552. req_nb_value = rsp_nb_value = 1;
  553. break;
  554. default:
  555. /* 1 Write functions & others */
  556. req_nb_value = rsp_nb_value = 1;
  557. break;
  558. }
  559. if ((req_nb_value == rsp_nb_value) && (resp_addr_ok == TRUE) &&
  560. (resp_data_ok == TRUE)) {
  561. rc = rsp_nb_value;
  562. } else {
  563. if (ctx->debug) {
  564. fprintf(stderr,
  565. "Received data not corresponding to the request (%d != %d)\n",
  566. rsp_nb_value,
  567. req_nb_value);
  568. }
  569. if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) {
  570. _sleep_response_timeout(ctx);
  571. modbus_flush(ctx);
  572. }
  573. errno = EMBBADDATA;
  574. rc = -1;
  575. }
  576. } else {
  577. if (ctx->debug) {
  578. fprintf(
  579. stderr,
  580. "Message length not corresponding to the computed length (%d != %d)\n",
  581. rsp_length,
  582. rsp_length_computed);
  583. }
  584. if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) {
  585. _sleep_response_timeout(ctx);
  586. modbus_flush(ctx);
  587. }
  588. errno = EMBBADDATA;
  589. rc = -1;
  590. }
  591. return rc;
  592. }
  593. static int
  594. response_io_status(uint8_t *tab_io_status, int address, int nb, uint8_t *rsp, int offset)
  595. {
  596. int shift = 0;
  597. /* Instead of byte (not allowed in Win32) */
  598. int one_byte = 0;
  599. int i;
  600. for (i = address; i < address + nb; i++) {
  601. one_byte |= tab_io_status[i] << shift;
  602. if (shift == 7) {
  603. /* Byte is full */
  604. rsp[offset++] = one_byte;
  605. one_byte = shift = 0;
  606. } else {
  607. shift++;
  608. }
  609. }
  610. if (shift != 0)
  611. rsp[offset++] = one_byte;
  612. return offset;
  613. }
  614. /* Build the exception response */
  615. static int response_exception(modbus_t *ctx,
  616. sft_t *sft,
  617. int exception_code,
  618. uint8_t *rsp,
  619. unsigned int to_flush,
  620. const char *template,
  621. ...)
  622. {
  623. int rsp_length;
  624. /* Print debug message */
  625. if (ctx->debug) {
  626. va_list ap;
  627. va_start(ap, template);
  628. vfprintf(stderr, template, ap);
  629. va_end(ap);
  630. }
  631. /* Flush if required */
  632. if (to_flush) {
  633. _sleep_response_timeout(ctx);
  634. modbus_flush(ctx);
  635. }
  636. /* Build exception response */
  637. sft->function = sft->function + 0x80;
  638. rsp_length = ctx->backend->build_response_basis(sft, rsp);
  639. rsp[rsp_length++] = exception_code;
  640. return rsp_length;
  641. }
  642. /* Send a response to the received request.
  643. Analyses the request and constructs a response.
  644. If an error occurs, this function construct the response
  645. accordingly.
  646. */
  647. int modbus_reply(modbus_t *ctx,
  648. const uint8_t *req,
  649. int req_length,
  650. modbus_mapping_t *mb_mapping)
  651. {
  652. unsigned int offset;
  653. int slave;
  654. int function;
  655. uint16_t address;
  656. uint8_t rsp[MAX_MESSAGE_LENGTH];
  657. int rsp_length = 0;
  658. sft_t sft;
  659. if (ctx == NULL) {
  660. errno = EINVAL;
  661. return -1;
  662. }
  663. offset = ctx->backend->header_length;
  664. slave = req[offset - 1];
  665. function = req[offset];
  666. address = (req[offset + 1] << 8) + req[offset + 2];
  667. sft.slave = slave;
  668. sft.function = function;
  669. sft.t_id = ctx->backend->prepare_response_tid(req, &req_length);
  670. /* Data are flushed on illegal number of values errors. */
  671. switch (function) {
  672. case MODBUS_FC_READ_COILS:
  673. case MODBUS_FC_READ_DISCRETE_INPUTS: {
  674. unsigned int is_input = (function == MODBUS_FC_READ_DISCRETE_INPUTS);
  675. int start_bits = is_input ? mb_mapping->start_input_bits : mb_mapping->start_bits;
  676. int nb_bits = is_input ? mb_mapping->nb_input_bits : mb_mapping->nb_bits;
  677. uint8_t *tab_bits = is_input ? mb_mapping->tab_input_bits : mb_mapping->tab_bits;
  678. const char *const name = is_input ? "read_input_bits" : "read_bits";
  679. int nb = (req[offset + 3] << 8) + req[offset + 4];
  680. /* The mapping can be shifted to reduce memory consumption and it
  681. doesn't always start at address zero. */
  682. int mapping_address = address - start_bits;
  683. if (nb < 1 || MODBUS_MAX_READ_BITS < nb) {
  684. rsp_length = response_exception(ctx,
  685. &sft,
  686. MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE,
  687. rsp,
  688. TRUE,
  689. "Illegal nb of values %d in %s (max %d)\n",
  690. nb,
  691. name,
  692. MODBUS_MAX_READ_BITS);
  693. } else if (mapping_address < 0 || (mapping_address + nb) > nb_bits) {
  694. rsp_length = response_exception(ctx,
  695. &sft,
  696. MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS,
  697. rsp,
  698. FALSE,
  699. "Illegal data address 0x%0X in %s\n",
  700. mapping_address < 0 ? address : address + nb,
  701. name);
  702. } else {
  703. rsp_length = ctx->backend->build_response_basis(&sft, rsp);
  704. rsp[rsp_length++] = (nb / 8) + ((nb % 8) ? 1 : 0);
  705. rsp_length =
  706. response_io_status(tab_bits, mapping_address, nb, rsp, rsp_length);
  707. }
  708. } break;
  709. case MODBUS_FC_READ_HOLDING_REGISTERS:
  710. case MODBUS_FC_READ_INPUT_REGISTERS: {
  711. unsigned int is_input = (function == MODBUS_FC_READ_INPUT_REGISTERS);
  712. int start_registers =
  713. is_input ? mb_mapping->start_input_registers : mb_mapping->start_registers;
  714. int nb_registers =
  715. is_input ? mb_mapping->nb_input_registers : mb_mapping->nb_registers;
  716. uint16_t *tab_registers =
  717. is_input ? mb_mapping->tab_input_registers : mb_mapping->tab_registers;
  718. const char *const name = is_input ? "read_input_registers" : "read_registers";
  719. int nb = (req[offset + 3] << 8) + req[offset + 4];
  720. /* The mapping can be shifted to reduce memory consumption and it
  721. doesn't always start at address zero. */
  722. int mapping_address = address - start_registers;
  723. if (nb < 1 || MODBUS_MAX_READ_REGISTERS < nb) {
  724. rsp_length = response_exception(ctx,
  725. &sft,
  726. MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE,
  727. rsp,
  728. TRUE,
  729. "Illegal nb of values %d in %s (max %d)\n",
  730. nb,
  731. name,
  732. MODBUS_MAX_READ_REGISTERS);
  733. } else if (mapping_address < 0 || (mapping_address + nb) > nb_registers) {
  734. rsp_length = response_exception(ctx,
  735. &sft,
  736. MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS,
  737. rsp,
  738. FALSE,
  739. "Illegal data address 0x%0X in %s\n",
  740. mapping_address < 0 ? address : address + nb,
  741. name);
  742. } else {
  743. int i;
  744. rsp_length = ctx->backend->build_response_basis(&sft, rsp);
  745. rsp[rsp_length++] = nb << 1;
  746. for (i = mapping_address; i < mapping_address + nb; i++) {
  747. rsp[rsp_length++] = tab_registers[i] >> 8;
  748. rsp[rsp_length++] = tab_registers[i] & 0xFF;
  749. }
  750. }
  751. } break;
  752. case MODBUS_FC_WRITE_SINGLE_COIL: {
  753. int mapping_address = address - mb_mapping->start_bits;
  754. if (mapping_address < 0 || mapping_address >= mb_mapping->nb_bits) {
  755. rsp_length = response_exception(ctx,
  756. &sft,
  757. MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS,
  758. rsp,
  759. FALSE,
  760. "Illegal data address 0x%0X in write_bit\n",
  761. address);
  762. } else {
  763. int data = (req[offset + 3] << 8) + req[offset + 4];
  764. if (data == 0xFF00 || data == 0x0) {
  765. mb_mapping->tab_bits[mapping_address] = data ? ON : OFF;
  766. memcpy(rsp, req, req_length);
  767. rsp_length = req_length;
  768. } else {
  769. rsp_length = response_exception(
  770. ctx,
  771. &sft,
  772. MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE,
  773. rsp,
  774. FALSE,
  775. "Illegal data value 0x%0X in write_bit request at address %0X\n",
  776. data,
  777. address);
  778. }
  779. }
  780. } break;
  781. case MODBUS_FC_WRITE_SINGLE_REGISTER: {
  782. int mapping_address = address - mb_mapping->start_registers;
  783. if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) {
  784. rsp_length =
  785. response_exception(ctx,
  786. &sft,
  787. MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS,
  788. rsp,
  789. FALSE,
  790. "Illegal data address 0x%0X in write_register\n",
  791. address);
  792. } else {
  793. int data = (req[offset + 3] << 8) + req[offset + 4];
  794. mb_mapping->tab_registers[mapping_address] = data;
  795. memcpy(rsp, req, req_length);
  796. rsp_length = req_length;
  797. }
  798. } break;
  799. case MODBUS_FC_WRITE_MULTIPLE_COILS: {
  800. int nb = (req[offset + 3] << 8) + req[offset + 4];
  801. int nb_bits = req[offset + 5];
  802. int mapping_address = address - mb_mapping->start_bits;
  803. if (nb < 1 || MODBUS_MAX_WRITE_BITS < nb || nb_bits * 8 < nb) {
  804. /* May be the indication has been truncated on reading because of
  805. * invalid address (eg. nb is 0 but the request contains values to
  806. * write) so it's necessary to flush. */
  807. rsp_length =
  808. response_exception(ctx,
  809. &sft,
  810. MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE,
  811. rsp,
  812. TRUE,
  813. "Illegal number of values %d in write_bits (max %d)\n",
  814. nb,
  815. MODBUS_MAX_WRITE_BITS);
  816. } else if (mapping_address < 0 || (mapping_address + nb) > mb_mapping->nb_bits) {
  817. rsp_length = response_exception(ctx,
  818. &sft,
  819. MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS,
  820. rsp,
  821. FALSE,
  822. "Illegal data address 0x%0X in write_bits\n",
  823. mapping_address < 0 ? address : address + nb);
  824. } else {
  825. /* 6 = byte count */
  826. modbus_set_bits_from_bytes(
  827. mb_mapping->tab_bits, mapping_address, nb, &req[offset + 6]);
  828. rsp_length = ctx->backend->build_response_basis(&sft, rsp);
  829. /* 4 to copy the bit address (2) and the quantity of bits */
  830. memcpy(rsp + rsp_length, req + rsp_length, 4);
  831. rsp_length += 4;
  832. }
  833. } break;
  834. case MODBUS_FC_WRITE_MULTIPLE_REGISTERS: {
  835. int nb = (req[offset + 3] << 8) + req[offset + 4];
  836. int nb_bytes = req[offset + 5];
  837. int mapping_address = address - mb_mapping->start_registers;
  838. if (nb < 1 || MODBUS_MAX_WRITE_REGISTERS < nb || nb_bytes != nb * 2) {
  839. rsp_length = response_exception(
  840. ctx,
  841. &sft,
  842. MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE,
  843. rsp,
  844. TRUE,
  845. "Illegal number of values %d in write_registers (max %d)\n",
  846. nb,
  847. MODBUS_MAX_WRITE_REGISTERS);
  848. } else if (mapping_address < 0 ||
  849. (mapping_address + nb) > mb_mapping->nb_registers) {
  850. rsp_length =
  851. response_exception(ctx,
  852. &sft,
  853. MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS,
  854. rsp,
  855. FALSE,
  856. "Illegal data address 0x%0X in write_registers\n",
  857. mapping_address < 0 ? address : address + nb);
  858. } else {
  859. int i, j;
  860. for (i = mapping_address, j = 6; i < mapping_address + nb; i++, j += 2) {
  861. /* 6 and 7 = first value */
  862. mb_mapping->tab_registers[i] =
  863. (req[offset + j] << 8) + req[offset + j + 1];
  864. }
  865. rsp_length = ctx->backend->build_response_basis(&sft, rsp);
  866. /* 4 to copy the address (2) and the no. of registers */
  867. memcpy(rsp + rsp_length, req + rsp_length, 4);
  868. rsp_length += 4;
  869. }
  870. } break;
  871. case MODBUS_FC_REPORT_SLAVE_ID: {
  872. int str_len;
  873. int byte_count_pos;
  874. rsp_length = ctx->backend->build_response_basis(&sft, rsp);
  875. /* Skip byte count for now */
  876. byte_count_pos = rsp_length++;
  877. rsp[rsp_length++] = _REPORT_SLAVE_ID;
  878. /* Run indicator status to ON */
  879. rsp[rsp_length++] = 0xFF;
  880. /* LMB + length of LIBMODBUS_VERSION_STRING */
  881. str_len = 3 + strlen(LIBMODBUS_VERSION_STRING);
  882. memcpy(rsp + rsp_length, "LMB" LIBMODBUS_VERSION_STRING, str_len);
  883. rsp_length += str_len;
  884. rsp[byte_count_pos] = rsp_length - byte_count_pos - 1;
  885. } break;
  886. case MODBUS_FC_READ_EXCEPTION_STATUS:
  887. if (ctx->debug) {
  888. fprintf(stderr, "FIXME Not implemented\n");
  889. }
  890. errno = ENOPROTOOPT;
  891. return -1;
  892. break;
  893. case MODBUS_FC_MASK_WRITE_REGISTER: {
  894. int mapping_address = address - mb_mapping->start_registers;
  895. if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) {
  896. rsp_length =
  897. response_exception(ctx,
  898. &sft,
  899. MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS,
  900. rsp,
  901. FALSE,
  902. "Illegal data address 0x%0X in write_register\n",
  903. address);
  904. } else {
  905. uint16_t data = mb_mapping->tab_registers[mapping_address];
  906. uint16_t and = (req[offset + 3] << 8) + req[offset + 4];
  907. uint16_t or = (req[offset + 5] << 8) + req[offset + 6];
  908. data = (data & and) | (or &(~and));
  909. mb_mapping->tab_registers[mapping_address] = data;
  910. memcpy(rsp, req, req_length);
  911. rsp_length = req_length;
  912. }
  913. } break;
  914. case MODBUS_FC_WRITE_AND_READ_REGISTERS: {
  915. int nb = (req[offset + 3] << 8) + req[offset + 4];
  916. uint16_t address_write = (req[offset + 5] << 8) + req[offset + 6];
  917. int nb_write = (req[offset + 7] << 8) + req[offset + 8];
  918. int nb_write_bytes = req[offset + 9];
  919. int mapping_address = address - mb_mapping->start_registers;
  920. int mapping_address_write = address_write - mb_mapping->start_registers;
  921. if (nb_write < 1 || MODBUS_MAX_WR_WRITE_REGISTERS < nb_write || nb < 1 ||
  922. MODBUS_MAX_WR_READ_REGISTERS < nb || nb_write_bytes != nb_write * 2) {
  923. rsp_length = response_exception(
  924. ctx,
  925. &sft,
  926. MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE,
  927. rsp,
  928. TRUE,
  929. "Illegal nb of values (W%d, R%d) in write_and_read_registers (max W%d, "
  930. "R%d)\n",
  931. nb_write,
  932. nb,
  933. MODBUS_MAX_WR_WRITE_REGISTERS,
  934. MODBUS_MAX_WR_READ_REGISTERS);
  935. } else if (mapping_address < 0 ||
  936. (mapping_address + nb) > mb_mapping->nb_registers ||
  937. mapping_address_write < 0 ||
  938. (mapping_address_write + nb_write) > mb_mapping->nb_registers) {
  939. rsp_length = response_exception(
  940. ctx,
  941. &sft,
  942. MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS,
  943. rsp,
  944. FALSE,
  945. "Illegal data read address 0x%0X or write address 0x%0X "
  946. "write_and_read_registers\n",
  947. mapping_address < 0 ? address : address + nb,
  948. mapping_address_write < 0 ? address_write : address_write + nb_write);
  949. } else {
  950. int i, j;
  951. rsp_length = ctx->backend->build_response_basis(&sft, rsp);
  952. rsp[rsp_length++] = nb << 1;
  953. /* Write first.
  954. 10 and 11 are the offset of the first values to write */
  955. for (i = mapping_address_write, j = 10; i < mapping_address_write + nb_write;
  956. i++, j += 2) {
  957. mb_mapping->tab_registers[i] =
  958. (req[offset + j] << 8) + req[offset + j + 1];
  959. }
  960. /* and read the data for the response */
  961. for (i = mapping_address; i < mapping_address + nb; i++) {
  962. rsp[rsp_length++] = mb_mapping->tab_registers[i] >> 8;
  963. rsp[rsp_length++] = mb_mapping->tab_registers[i] & 0xFF;
  964. }
  965. }
  966. } break;
  967. default:
  968. rsp_length = response_exception(ctx,
  969. &sft,
  970. MODBUS_EXCEPTION_ILLEGAL_FUNCTION,
  971. rsp,
  972. TRUE,
  973. "Unknown Modbus function code: 0x%0X\n",
  974. function);
  975. break;
  976. }
  977. /* Suppress any responses in RTU when the request was a broadcast, excepted when quirk
  978. * is enabled. */
  979. if (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU &&
  980. slave == MODBUS_BROADCAST_ADDRESS &&
  981. !(ctx->quirks & MODBUS_QUIRK_REPLY_TO_BROADCAST)) {
  982. return 0;
  983. }
  984. return send_msg(ctx, rsp, rsp_length);
  985. }
  986. int modbus_reply_exception(modbus_t *ctx, const uint8_t *req, unsigned int exception_code)
  987. {
  988. unsigned int offset;
  989. int slave;
  990. int function;
  991. uint8_t rsp[MAX_MESSAGE_LENGTH];
  992. int rsp_length;
  993. int dummy_length = 99;
  994. sft_t sft;
  995. if (ctx == NULL) {
  996. errno = EINVAL;
  997. return -1;
  998. }
  999. offset = ctx->backend->header_length;
  1000. slave = req[offset - 1];
  1001. function = req[offset];
  1002. sft.slave = slave;
  1003. sft.function = function + 0x80;
  1004. sft.t_id = ctx->backend->prepare_response_tid(req, &dummy_length);
  1005. rsp_length = ctx->backend->build_response_basis(&sft, rsp);
  1006. /* Positive exception code */
  1007. if (exception_code < MODBUS_EXCEPTION_MAX) {
  1008. rsp[rsp_length++] = exception_code;
  1009. return send_msg(ctx, rsp, rsp_length);
  1010. } else {
  1011. errno = EINVAL;
  1012. return -1;
  1013. }
  1014. }
  1015. /* Reads IO status */
  1016. static int read_io_status(modbus_t *ctx, int function, int addr, int nb, uint8_t *dest)
  1017. {
  1018. int rc;
  1019. int req_length;
  1020. uint8_t req[_MIN_REQ_LENGTH];
  1021. uint8_t rsp[MAX_MESSAGE_LENGTH];
  1022. req_length = ctx->backend->build_request_basis(ctx, function, addr, nb, req);
  1023. rc = send_msg(ctx, req, req_length);
  1024. if (rc > 0) {
  1025. int temp, bit;
  1026. int pos = 0;
  1027. unsigned int offset;
  1028. unsigned int offset_end;
  1029. rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
  1030. if (rc == -1)
  1031. return -1;
  1032. rc = check_confirmation(ctx, req, rsp, rc);
  1033. if (rc == -1)
  1034. return -1;
  1035. offset = ctx->backend->header_length + 2;
  1036. offset_end = offset + rc;
  1037. for (unsigned int i = offset; i < offset_end; i++) {
  1038. /* Shift reg hi_byte to temp */
  1039. temp = rsp[i];
  1040. for (bit = 0x01; (bit & 0xff) && (pos < nb);) {
  1041. dest[pos++] = (temp & bit) ? TRUE : FALSE;
  1042. bit = bit << 1;
  1043. }
  1044. }
  1045. }
  1046. return rc;
  1047. }
  1048. /* Reads the boolean status of bits and sets the array elements
  1049. in the destination to TRUE or FALSE (single bits). */
  1050. int modbus_read_bits(modbus_t *ctx, int addr, int nb, uint8_t *dest)
  1051. {
  1052. int rc;
  1053. if (ctx == NULL) {
  1054. errno = EINVAL;
  1055. return -1;
  1056. }
  1057. if (nb > MODBUS_MAX_READ_BITS) {
  1058. if (ctx->debug) {
  1059. fprintf(stderr,
  1060. "ERROR Too many bits requested (%d > %d)\n",
  1061. nb,
  1062. MODBUS_MAX_READ_BITS);
  1063. }
  1064. errno = EMBMDATA;
  1065. return -1;
  1066. }
  1067. rc = read_io_status(ctx, MODBUS_FC_READ_COILS, addr, nb, dest);
  1068. if (rc == -1)
  1069. return -1;
  1070. else
  1071. return nb;
  1072. }
  1073. /* Same as modbus_read_bits but reads the remote device input table */
  1074. int modbus_read_input_bits(modbus_t *ctx, int addr, int nb, uint8_t *dest)
  1075. {
  1076. int rc;
  1077. if (ctx == NULL) {
  1078. errno = EINVAL;
  1079. return -1;
  1080. }
  1081. if (nb > MODBUS_MAX_READ_BITS) {
  1082. if (ctx->debug) {
  1083. fprintf(stderr,
  1084. "ERROR Too many discrete inputs requested (%d > %d)\n",
  1085. nb,
  1086. MODBUS_MAX_READ_BITS);
  1087. }
  1088. errno = EMBMDATA;
  1089. return -1;
  1090. }
  1091. rc = read_io_status(ctx, MODBUS_FC_READ_DISCRETE_INPUTS, addr, nb, dest);
  1092. if (rc == -1)
  1093. return -1;
  1094. else
  1095. return nb;
  1096. }
  1097. /* Reads the data from a remote device and put that data into an array */
  1098. static int read_registers(modbus_t *ctx, int function, int addr, int nb, uint16_t *dest)
  1099. {
  1100. int rc;
  1101. int req_length;
  1102. uint8_t req[_MIN_REQ_LENGTH];
  1103. uint8_t rsp[MAX_MESSAGE_LENGTH];
  1104. if (nb > MODBUS_MAX_READ_REGISTERS) {
  1105. if (ctx->debug) {
  1106. fprintf(stderr,
  1107. "ERROR Too many registers requested (%d > %d)\n",
  1108. nb,
  1109. MODBUS_MAX_READ_REGISTERS);
  1110. }
  1111. errno = EMBMDATA;
  1112. return -1;
  1113. }
  1114. req_length = ctx->backend->build_request_basis(ctx, function, addr, nb, req);
  1115. rc = send_msg(ctx, req, req_length);
  1116. if (rc > 0) {
  1117. unsigned int offset;
  1118. int i;
  1119. rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
  1120. if (rc == -1){
  1121. //syslog(LOG_INFO, "%s %d _modbus_receive_msg fail:%d",__func__, ctx->s ,rc);
  1122. return -1;
  1123. }
  1124. rc = check_confirmation(ctx, req, rsp, rc);
  1125. if (rc == -1){
  1126. //syslog(LOG_INFO, "%s %d check_confirmation fail:%d",__func__, ctx->s, rc);
  1127. return -1;
  1128. }
  1129. offset = ctx->backend->header_length;
  1130. for (i = 0; i < rc; i++) {
  1131. /* shift reg hi_byte to temp OR with lo_byte */
  1132. dest[i] = (rsp[offset + 2 + (i << 1)] << 8) | rsp[offset + 3 + (i << 1)];
  1133. }
  1134. }else{
  1135. //syslog(LOG_INFO, "%s %d send_msg fail:%d",__func__, ctx->s, rc);
  1136. }
  1137. return rc;
  1138. }
  1139. /* Reads the holding registers of remote device and put the data into an
  1140. array */
  1141. int modbus_read_registers(modbus_t *ctx, int addr, int nb, uint16_t *dest)
  1142. {
  1143. int status;
  1144. if (ctx == NULL) {
  1145. errno = EINVAL;
  1146. return -1;
  1147. }
  1148. if (nb > MODBUS_MAX_READ_REGISTERS) {
  1149. if (ctx->debug) {
  1150. fprintf(stderr,
  1151. "ERROR Too many registers requested (%d > %d)\n",
  1152. nb,
  1153. MODBUS_MAX_READ_REGISTERS);
  1154. }
  1155. errno = EMBMDATA;
  1156. return -1;
  1157. }
  1158. status = read_registers(ctx, MODBUS_FC_READ_HOLDING_REGISTERS, addr, nb, dest);
  1159. return status;
  1160. }
  1161. /* Reads the input registers of remote device and put the data into an array */
  1162. int modbus_read_input_registers(modbus_t *ctx, int addr, int nb, uint16_t *dest)
  1163. {
  1164. int status;
  1165. if (ctx == NULL) {
  1166. errno = EINVAL;
  1167. return -1;
  1168. }
  1169. if (nb > MODBUS_MAX_READ_REGISTERS) {
  1170. fprintf(stderr,
  1171. "ERROR Too many input registers requested (%d > %d)\n",
  1172. nb,
  1173. MODBUS_MAX_READ_REGISTERS);
  1174. errno = EMBMDATA;
  1175. return -1;
  1176. }
  1177. status = read_registers(ctx, MODBUS_FC_READ_INPUT_REGISTERS, addr, nb, dest);
  1178. return status;
  1179. }
  1180. /* Write a value to the specified register of the remote device.
  1181. Used by write_bit and write_register */
  1182. static int write_single(modbus_t *ctx, int function, int addr, const uint16_t value)
  1183. {
  1184. int rc;
  1185. int req_length;
  1186. uint8_t req[_MIN_REQ_LENGTH];
  1187. if (ctx == NULL) {
  1188. errno = EINVAL;
  1189. return -1;
  1190. }
  1191. req_length = ctx->backend->build_request_basis(ctx, function, addr, (int) value, req);
  1192. rc = send_msg(ctx, req, req_length);
  1193. if (rc > 0) {
  1194. /* Used by write_bit and write_register */
  1195. uint8_t rsp[MAX_MESSAGE_LENGTH];
  1196. rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
  1197. if (rc == -1)
  1198. return -1;
  1199. rc = check_confirmation(ctx, req, rsp, rc);
  1200. }
  1201. return rc;
  1202. }
  1203. /* Turns ON or OFF a single bit of the remote device */
  1204. int modbus_write_bit(modbus_t *ctx, int addr, int status)
  1205. {
  1206. if (ctx == NULL) {
  1207. errno = EINVAL;
  1208. return -1;
  1209. }
  1210. return write_single(ctx, MODBUS_FC_WRITE_SINGLE_COIL, addr, status ? 0xFF00 : 0);
  1211. }
  1212. /* Writes a value in one register of the remote device */
  1213. int modbus_write_register(modbus_t *ctx, int addr, const uint16_t value)
  1214. {
  1215. if (ctx == NULL) {
  1216. errno = EINVAL;
  1217. return -1;
  1218. }
  1219. return write_single(ctx, MODBUS_FC_WRITE_SINGLE_REGISTER, addr, value);
  1220. }
  1221. /* Write the bits of the array in the remote device */
  1222. int modbus_write_bits(modbus_t *ctx, int addr, int nb, const uint8_t *src)
  1223. {
  1224. int rc;
  1225. int i;
  1226. int byte_count;
  1227. int req_length;
  1228. int bit_check = 0;
  1229. int pos = 0;
  1230. uint8_t req[MAX_MESSAGE_LENGTH];
  1231. if (ctx == NULL) {
  1232. errno = EINVAL;
  1233. return -1;
  1234. }
  1235. if (nb > MODBUS_MAX_WRITE_BITS) {
  1236. if (ctx->debug) {
  1237. fprintf(stderr,
  1238. "ERROR Writing too many bits (%d > %d)\n",
  1239. nb,
  1240. MODBUS_MAX_WRITE_BITS);
  1241. }
  1242. errno = EMBMDATA;
  1243. return -1;
  1244. }
  1245. req_length = ctx->backend->build_request_basis(
  1246. ctx, MODBUS_FC_WRITE_MULTIPLE_COILS, addr, nb, req);
  1247. byte_count = (nb / 8) + ((nb % 8) ? 1 : 0);
  1248. req[req_length++] = byte_count;
  1249. for (i = 0; i < byte_count; i++) {
  1250. int bit;
  1251. bit = 0x01;
  1252. req[req_length] = 0;
  1253. while ((bit & 0xFF) && (bit_check++ < nb)) {
  1254. if (src[pos++])
  1255. req[req_length] |= bit;
  1256. else
  1257. req[req_length] &= ~bit;
  1258. bit = bit << 1;
  1259. }
  1260. req_length++;
  1261. }
  1262. rc = send_msg(ctx, req, req_length);
  1263. if (rc > 0) {
  1264. uint8_t rsp[MAX_MESSAGE_LENGTH];
  1265. rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
  1266. if (rc == -1)
  1267. return -1;
  1268. rc = check_confirmation(ctx, req, rsp, rc);
  1269. }
  1270. return rc;
  1271. }
  1272. /* Write the values from the array to the registers of the remote device */
  1273. int modbus_write_registers(modbus_t *ctx, int addr, int nb, const uint16_t *src)
  1274. {
  1275. int rc;
  1276. int i;
  1277. int req_length;
  1278. int byte_count;
  1279. uint8_t req[MAX_MESSAGE_LENGTH];
  1280. if (ctx == NULL) {
  1281. errno = EINVAL;
  1282. return -1;
  1283. }
  1284. if (nb > MODBUS_MAX_WRITE_REGISTERS) {
  1285. if (ctx->debug) {
  1286. fprintf(stderr,
  1287. "ERROR Trying to write to too many registers (%d > %d)\n",
  1288. nb,
  1289. MODBUS_MAX_WRITE_REGISTERS);
  1290. }
  1291. errno = EMBMDATA;
  1292. return -1;
  1293. }
  1294. req_length = ctx->backend->build_request_basis(
  1295. ctx, MODBUS_FC_WRITE_MULTIPLE_REGISTERS, addr, nb, req);
  1296. byte_count = nb * 2;
  1297. req[req_length++] = byte_count;
  1298. for (i = 0; i < nb; i++) {
  1299. req[req_length++] = src[i] >> 8;
  1300. req[req_length++] = src[i] & 0x00FF;
  1301. }
  1302. rc = send_msg(ctx, req, req_length);
  1303. if (rc > 0) {
  1304. uint8_t rsp[MAX_MESSAGE_LENGTH];
  1305. rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
  1306. if (rc == -1)
  1307. return -1;
  1308. rc = check_confirmation(ctx, req, rsp, rc);
  1309. }
  1310. return rc;
  1311. }
  1312. int modbus_mask_write_register(modbus_t *ctx,
  1313. int addr,
  1314. uint16_t and_mask,
  1315. uint16_t or_mask)
  1316. {
  1317. int rc;
  1318. int req_length;
  1319. /* The request length can not exceed _MIN_REQ_LENGTH - 2 and 4 bytes to
  1320. * store the masks. The ugly substraction is there to remove the 'nb' value
  1321. * (2 bytes) which is not used. */
  1322. uint8_t req[_MIN_REQ_LENGTH + 2];
  1323. req_length = ctx->backend->build_request_basis(
  1324. ctx, MODBUS_FC_MASK_WRITE_REGISTER, addr, 0, req);
  1325. /* HACKISH, count is not used */
  1326. req_length -= 2;
  1327. req[req_length++] = and_mask >> 8;
  1328. req[req_length++] = and_mask & 0x00ff;
  1329. req[req_length++] = or_mask >> 8;
  1330. req[req_length++] = or_mask & 0x00ff;
  1331. rc = send_msg(ctx, req, req_length);
  1332. if (rc > 0) {
  1333. /* Used by write_bit and write_register */
  1334. uint8_t rsp[MAX_MESSAGE_LENGTH];
  1335. rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
  1336. if (rc == -1)
  1337. return -1;
  1338. rc = check_confirmation(ctx, req, rsp, rc);
  1339. }
  1340. return rc;
  1341. }
  1342. /* Write multiple registers from src array to remote device and read multiple
  1343. registers from remote device to dest array. */
  1344. int modbus_write_and_read_registers(modbus_t *ctx,
  1345. int write_addr,
  1346. int write_nb,
  1347. const uint16_t *src,
  1348. int read_addr,
  1349. int read_nb,
  1350. uint16_t *dest)
  1351. {
  1352. int rc;
  1353. int req_length;
  1354. int i;
  1355. int byte_count;
  1356. uint8_t req[MAX_MESSAGE_LENGTH];
  1357. uint8_t rsp[MAX_MESSAGE_LENGTH];
  1358. if (ctx == NULL) {
  1359. errno = EINVAL;
  1360. return -1;
  1361. }
  1362. if (write_nb > MODBUS_MAX_WR_WRITE_REGISTERS) {
  1363. if (ctx->debug) {
  1364. fprintf(stderr,
  1365. "ERROR Too many registers to write (%d > %d)\n",
  1366. write_nb,
  1367. MODBUS_MAX_WR_WRITE_REGISTERS);
  1368. }
  1369. errno = EMBMDATA;
  1370. return -1;
  1371. }
  1372. if (read_nb > MODBUS_MAX_WR_READ_REGISTERS) {
  1373. if (ctx->debug) {
  1374. fprintf(stderr,
  1375. "ERROR Too many registers requested (%d > %d)\n",
  1376. read_nb,
  1377. MODBUS_MAX_WR_READ_REGISTERS);
  1378. }
  1379. errno = EMBMDATA;
  1380. return -1;
  1381. }
  1382. req_length = ctx->backend->build_request_basis(
  1383. ctx, MODBUS_FC_WRITE_AND_READ_REGISTERS, read_addr, read_nb, req);
  1384. req[req_length++] = write_addr >> 8;
  1385. req[req_length++] = write_addr & 0x00ff;
  1386. req[req_length++] = write_nb >> 8;
  1387. req[req_length++] = write_nb & 0x00ff;
  1388. byte_count = write_nb * 2;
  1389. req[req_length++] = byte_count;
  1390. for (i = 0; i < write_nb; i++) {
  1391. req[req_length++] = src[i] >> 8;
  1392. req[req_length++] = src[i] & 0x00FF;
  1393. }
  1394. rc = send_msg(ctx, req, req_length);
  1395. if (rc > 0) {
  1396. unsigned int offset;
  1397. rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
  1398. if (rc == -1)
  1399. return -1;
  1400. rc = check_confirmation(ctx, req, rsp, rc);
  1401. if (rc == -1)
  1402. return -1;
  1403. offset = ctx->backend->header_length;
  1404. for (i = 0; i < rc; i++) {
  1405. /* shift reg hi_byte to temp OR with lo_byte */
  1406. dest[i] = (rsp[offset + 2 + (i << 1)] << 8) | rsp[offset + 3 + (i << 1)];
  1407. }
  1408. }
  1409. return rc;
  1410. }
  1411. /* Send a request to get the slave ID of the device (only available in serial
  1412. communication). */
  1413. int modbus_report_slave_id(modbus_t *ctx, int max_dest, uint8_t *dest)
  1414. {
  1415. int rc;
  1416. int req_length;
  1417. uint8_t req[_MIN_REQ_LENGTH];
  1418. if (ctx == NULL || max_dest <= 0) {
  1419. errno = EINVAL;
  1420. return -1;
  1421. }
  1422. req_length =
  1423. ctx->backend->build_request_basis(ctx, MODBUS_FC_REPORT_SLAVE_ID, 0, 0, req);
  1424. /* HACKISH, addr and count are not used */
  1425. req_length -= 4;
  1426. rc = send_msg(ctx, req, req_length);
  1427. if (rc > 0) {
  1428. int i;
  1429. unsigned int offset;
  1430. uint8_t rsp[MAX_MESSAGE_LENGTH];
  1431. rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION);
  1432. if (rc == -1)
  1433. return -1;
  1434. rc = check_confirmation(ctx, req, rsp, rc);
  1435. if (rc == -1)
  1436. return -1;
  1437. offset = ctx->backend->header_length + 2;
  1438. /* Byte count, slave id, run indicator status and
  1439. additional data. Truncate copy to max_dest. */
  1440. for (i = 0; i < rc && i < max_dest; i++) {
  1441. dest[i] = rsp[offset + i];
  1442. }
  1443. }
  1444. return rc;
  1445. }
  1446. void _modbus_init_common(modbus_t *ctx)
  1447. {
  1448. /* Slave and socket are initialized to -1 */
  1449. ctx->slave = -1;
  1450. ctx->s = -1;
  1451. ctx->debug = FALSE;
  1452. ctx->error_recovery = MODBUS_ERROR_RECOVERY_NONE;
  1453. ctx->quirks = MODBUS_QUIRK_NONE;
  1454. ctx->response_timeout.tv_sec = 0;
  1455. ctx->response_timeout.tv_usec = _RESPONSE_TIMEOUT;
  1456. ctx->byte_timeout.tv_sec = 0;
  1457. ctx->byte_timeout.tv_usec = _BYTE_TIMEOUT;
  1458. ctx->indication_timeout.tv_sec = 0;
  1459. ctx->indication_timeout.tv_usec = 0;
  1460. }
  1461. /* Define the slave number */
  1462. int modbus_set_slave(modbus_t *ctx, int slave)
  1463. {
  1464. if (ctx == NULL) {
  1465. errno = EINVAL;
  1466. return -1;
  1467. }
  1468. return ctx->backend->set_slave(ctx, slave);
  1469. }
  1470. int modbus_get_slave(modbus_t *ctx)
  1471. {
  1472. if (ctx == NULL) {
  1473. errno = EINVAL;
  1474. return -1;
  1475. }
  1476. return ctx->slave;
  1477. }
  1478. int modbus_set_error_recovery(modbus_t *ctx, modbus_error_recovery_mode error_recovery)
  1479. {
  1480. if (ctx == NULL) {
  1481. errno = EINVAL;
  1482. return -1;
  1483. }
  1484. /* The type of modbus_error_recovery_mode is unsigned enum */
  1485. ctx->error_recovery = (uint8_t) error_recovery;
  1486. return 0;
  1487. }
  1488. // FIXME Doesn't work under Windows RTU
  1489. int modbus_set_socket(modbus_t *ctx, int s)
  1490. {
  1491. if (ctx == NULL) {
  1492. errno = EINVAL;
  1493. return -1;
  1494. }
  1495. ctx->s = s;
  1496. return 0;
  1497. }
  1498. int modbus_get_socket(modbus_t *ctx)
  1499. {
  1500. if (ctx == NULL) {
  1501. errno = EINVAL;
  1502. return -1;
  1503. }
  1504. return ctx->s;
  1505. }
  1506. /* Get the timeout interval used to wait for a response */
  1507. int modbus_get_response_timeout(modbus_t *ctx, uint32_t *to_sec, uint32_t *to_usec)
  1508. {
  1509. if (ctx == NULL) {
  1510. errno = EINVAL;
  1511. return -1;
  1512. }
  1513. *to_sec = ctx->response_timeout.tv_sec;
  1514. *to_usec = ctx->response_timeout.tv_usec;
  1515. return 0;
  1516. }
  1517. int modbus_set_response_timeout(modbus_t *ctx, uint32_t to_sec, uint32_t to_usec)
  1518. {
  1519. if (ctx == NULL || (to_sec == 0 && to_usec == 0) || to_usec > 999999) {
  1520. errno = EINVAL;
  1521. return -1;
  1522. }
  1523. ctx->response_timeout.tv_sec = to_sec;
  1524. ctx->response_timeout.tv_usec = to_usec;
  1525. return 0;
  1526. }
  1527. /* Get the timeout interval between two consecutive bytes of a message */
  1528. int modbus_get_byte_timeout(modbus_t *ctx, uint32_t *to_sec, uint32_t *to_usec)
  1529. {
  1530. if (ctx == NULL) {
  1531. errno = EINVAL;
  1532. return -1;
  1533. }
  1534. *to_sec = ctx->byte_timeout.tv_sec;
  1535. *to_usec = ctx->byte_timeout.tv_usec;
  1536. return 0;
  1537. }
  1538. int modbus_set_byte_timeout(modbus_t *ctx, uint32_t to_sec, uint32_t to_usec)
  1539. {
  1540. /* Byte timeout can be disabled when both values are zero */
  1541. if (ctx == NULL || to_usec > 999999) {
  1542. errno = EINVAL;
  1543. return -1;
  1544. }
  1545. ctx->byte_timeout.tv_sec = to_sec;
  1546. ctx->byte_timeout.tv_usec = to_usec;
  1547. return 0;
  1548. }
  1549. /* Get the timeout interval used by the server to wait for an indication from a client */
  1550. int modbus_get_indication_timeout(modbus_t *ctx, uint32_t *to_sec, uint32_t *to_usec)
  1551. {
  1552. if (ctx == NULL) {
  1553. errno = EINVAL;
  1554. return -1;
  1555. }
  1556. *to_sec = ctx->indication_timeout.tv_sec;
  1557. *to_usec = ctx->indication_timeout.tv_usec;
  1558. return 0;
  1559. }
  1560. int modbus_set_indication_timeout(modbus_t *ctx, uint32_t to_sec, uint32_t to_usec)
  1561. {
  1562. /* Indication timeout can be disabled when both values are zero */
  1563. if (ctx == NULL || to_usec > 999999) {
  1564. errno = EINVAL;
  1565. return -1;
  1566. }
  1567. ctx->indication_timeout.tv_sec = to_sec;
  1568. ctx->indication_timeout.tv_usec = to_usec;
  1569. return 0;
  1570. }
  1571. int modbus_get_header_length(modbus_t *ctx)
  1572. {
  1573. if (ctx == NULL) {
  1574. errno = EINVAL;
  1575. return -1;
  1576. }
  1577. return ctx->backend->header_length;
  1578. }
  1579. int modbus_enable_quirks(modbus_t *ctx, unsigned int quirks_mask)
  1580. {
  1581. if (ctx == NULL) {
  1582. errno = EINVAL;
  1583. return -1;
  1584. }
  1585. /* Enable quirks that have a true value at their index in the mask */
  1586. ctx->quirks |= quirks_mask;
  1587. return 0;
  1588. }
  1589. int modbus_disable_quirks(modbus_t *ctx, unsigned int quirks_mask)
  1590. {
  1591. if (ctx == NULL) {
  1592. errno = EINVAL;
  1593. return -1;
  1594. }
  1595. /* Disable quirks that have a true value at ther index in the mask */
  1596. ctx->quirks &= ~quirks_mask;
  1597. return 0;
  1598. }
  1599. int modbus_connect(modbus_t *ctx)
  1600. {
  1601. if (ctx == NULL) {
  1602. errno = EINVAL;
  1603. return -1;
  1604. }
  1605. return ctx->backend->connect(ctx);
  1606. }
  1607. void modbus_close(modbus_t *ctx)
  1608. {
  1609. if (ctx == NULL)
  1610. return;
  1611. ctx->backend->close(ctx);
  1612. }
  1613. void modbus_free(modbus_t *ctx)
  1614. {
  1615. if (ctx == NULL)
  1616. return;
  1617. ctx->backend->free(ctx);
  1618. }
  1619. int modbus_set_debug(modbus_t *ctx, int flag)
  1620. {
  1621. if (ctx == NULL) {
  1622. errno = EINVAL;
  1623. return -1;
  1624. }
  1625. ctx->debug = flag;
  1626. return 0;
  1627. }
  1628. /* Allocates 4 arrays to store bits, input bits, registers and inputs
  1629. registers. The pointers are stored in modbus_mapping structure.
  1630. The modbus_mapping_new_start_address() function shall return the new allocated
  1631. structure if successful. Otherwise it shall return NULL and set errno to
  1632. ENOMEM. */
  1633. modbus_mapping_t *modbus_mapping_new_start_address(unsigned int start_bits,
  1634. unsigned int nb_bits,
  1635. unsigned int start_input_bits,
  1636. unsigned int nb_input_bits,
  1637. unsigned int start_registers,
  1638. unsigned int nb_registers,
  1639. unsigned int start_input_registers,
  1640. unsigned int nb_input_registers)
  1641. {
  1642. modbus_mapping_t *mb_mapping;
  1643. mb_mapping = (modbus_mapping_t *) malloc(sizeof(modbus_mapping_t));
  1644. if (mb_mapping == NULL) {
  1645. return NULL;
  1646. }
  1647. /* 0X */
  1648. mb_mapping->nb_bits = nb_bits;
  1649. mb_mapping->start_bits = start_bits;
  1650. if (nb_bits == 0) {
  1651. mb_mapping->tab_bits = NULL;
  1652. } else {
  1653. /* Negative number raises a POSIX error */
  1654. mb_mapping->tab_bits = (uint8_t *) malloc(nb_bits * sizeof(uint8_t));
  1655. if (mb_mapping->tab_bits == NULL) {
  1656. free(mb_mapping);
  1657. return NULL;
  1658. }
  1659. memset(mb_mapping->tab_bits, 0, nb_bits * sizeof(uint8_t));
  1660. }
  1661. /* 1X */
  1662. mb_mapping->nb_input_bits = nb_input_bits;
  1663. mb_mapping->start_input_bits = start_input_bits;
  1664. if (nb_input_bits == 0) {
  1665. mb_mapping->tab_input_bits = NULL;
  1666. } else {
  1667. mb_mapping->tab_input_bits = (uint8_t *) malloc(nb_input_bits * sizeof(uint8_t));
  1668. if (mb_mapping->tab_input_bits == NULL) {
  1669. free(mb_mapping->tab_bits);
  1670. free(mb_mapping);
  1671. return NULL;
  1672. }
  1673. memset(mb_mapping->tab_input_bits, 0, nb_input_bits * sizeof(uint8_t));
  1674. }
  1675. /* 4X */
  1676. mb_mapping->nb_registers = nb_registers;
  1677. mb_mapping->start_registers = start_registers;
  1678. if (nb_registers == 0) {
  1679. mb_mapping->tab_registers = NULL;
  1680. } else {
  1681. mb_mapping->tab_registers = (uint16_t *) malloc(nb_registers * sizeof(uint16_t));
  1682. if (mb_mapping->tab_registers == NULL) {
  1683. free(mb_mapping->tab_input_bits);
  1684. free(mb_mapping->tab_bits);
  1685. free(mb_mapping);
  1686. return NULL;
  1687. }
  1688. memset(mb_mapping->tab_registers, 0, nb_registers * sizeof(uint16_t));
  1689. }
  1690. /* 3X */
  1691. mb_mapping->nb_input_registers = nb_input_registers;
  1692. mb_mapping->start_input_registers = start_input_registers;
  1693. if (nb_input_registers == 0) {
  1694. mb_mapping->tab_input_registers = NULL;
  1695. } else {
  1696. mb_mapping->tab_input_registers =
  1697. (uint16_t *) malloc(nb_input_registers * sizeof(uint16_t));
  1698. if (mb_mapping->tab_input_registers == NULL) {
  1699. free(mb_mapping->tab_registers);
  1700. free(mb_mapping->tab_input_bits);
  1701. free(mb_mapping->tab_bits);
  1702. free(mb_mapping);
  1703. return NULL;
  1704. }
  1705. memset(mb_mapping->tab_input_registers, 0, nb_input_registers * sizeof(uint16_t));
  1706. }
  1707. return mb_mapping;
  1708. }
  1709. modbus_mapping_t *modbus_mapping_new(int nb_bits,
  1710. int nb_input_bits,
  1711. int nb_registers,
  1712. int nb_input_registers)
  1713. {
  1714. return modbus_mapping_new_start_address(
  1715. 0, nb_bits, 0, nb_input_bits, 0, nb_registers, 0, nb_input_registers);
  1716. }
  1717. /* Frees the 4 arrays */
  1718. void modbus_mapping_free(modbus_mapping_t *mb_mapping)
  1719. {
  1720. if (mb_mapping == NULL) {
  1721. return;
  1722. }
  1723. free(mb_mapping->tab_input_registers);
  1724. free(mb_mapping->tab_registers);
  1725. free(mb_mapping->tab_input_bits);
  1726. free(mb_mapping->tab_bits);
  1727. free(mb_mapping);
  1728. }
  1729. #ifndef HAVE_STRLCPY
  1730. /*
  1731. * Function strlcpy was originally developed by
  1732. * Todd C. Miller <Todd.Miller@courtesan.com> to simplify writing secure code.
  1733. * See ftp://ftp.openbsd.org/pub/OpenBSD/src/lib/libc/string/strlcpy.3
  1734. * for more information.
  1735. *
  1736. * Thank you Ulrich Drepper... not!
  1737. *
  1738. * Copy src to string dest of size dest_size. At most dest_size-1 characters
  1739. * will be copied. Always NUL terminates (unless dest_size == 0). Returns
  1740. * strlen(src); if retval >= dest_size, truncation occurred.
  1741. */
  1742. size_t strlcpy(char *dest, const char *src, size_t dest_size)
  1743. {
  1744. register char *d = dest;
  1745. register const char *s = src;
  1746. register size_t n = dest_size;
  1747. /* Copy as many bytes as will fit */
  1748. if (n != 0 && --n != 0) {
  1749. do {
  1750. if ((*d++ = *s++) == 0)
  1751. break;
  1752. } while (--n != 0);
  1753. }
  1754. /* Not enough room in dest, add NUL and traverse rest of src */
  1755. if (n == 0) {
  1756. if (dest_size != 0)
  1757. *d = '\0'; /* NUL-terminate dest */
  1758. while (*s++)
  1759. ;
  1760. }
  1761. return (s - src - 1); /* count does not include NUL */
  1762. }
  1763. #endif