modbus.c 44 KB

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