modbus.c 43 KB

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