modbus.c 56 KB

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