modbus.c 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959
  1. /*
  2. * Copyright © 2001-2008 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. The library is designed to send and receive data from a device that
  19. communicate via the Modbus protocol.
  20. The function names used are inspired by the Modicon Modbus Protocol
  21. Reference Guide which can be obtained from Schneider at
  22. www.schneiderautomation.com.
  23. Documentation:
  24. http://www.easysw.com/~mike/serial/serial.html
  25. http://copyleft.free.fr/wordpress/index.php/libmodbus/
  26. */
  27. #include <config.h>
  28. #include <stdio.h>
  29. #include <string.h>
  30. #include <stdlib.h>
  31. #include <stdint.h>
  32. #include <termios.h>
  33. #include <sys/time.h>
  34. #include <unistd.h>
  35. #include <errno.h>
  36. #include <limits.h>
  37. #include <fcntl.h>
  38. /* TCP */
  39. #include <sys/types.h>
  40. #include <sys/socket.h>
  41. #include <sys/ioctl.h>
  42. #include <netinet/in.h>
  43. #include <netinet/ip.h>
  44. #include <netinet/tcp.h>
  45. #include <arpa/inet.h>
  46. #include "modbus.h"
  47. #define UNKNOWN_ERROR_MSG "Not defined in modbus specification"
  48. /* This structure reduces the number of params in functions and so
  49. * optimizes the speed of execution (~ 37%). */
  50. typedef struct {
  51. int slave;
  52. int function;
  53. int t_id;
  54. } sft_t;
  55. static const uint8_t NB_TAB_ERROR_MSG = 12;
  56. static const char *TAB_ERROR_MSG[] = {
  57. /* 0x00 */ UNKNOWN_ERROR_MSG,
  58. /* 0x01 */ "Illegal function code",
  59. /* 0x02 */ "Illegal data address",
  60. /* 0x03 */ "Illegal data value",
  61. /* 0x04 */ "Slave device or server failure",
  62. /* 0x05 */ "Acknowledge",
  63. /* 0x06 */ "Slave device or server busy",
  64. /* 0x07 */ "Negative acknowledge",
  65. /* 0x08 */ "Memory parity error",
  66. /* 0x09 */ UNKNOWN_ERROR_MSG,
  67. /* 0x0A */ "Gateway path unavailable",
  68. /* 0x0B */ "Target device failed to respond"
  69. };
  70. /* Table of CRC values for high-order byte */
  71. static uint8_t table_crc_hi[] = {
  72. 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
  73. 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
  74. 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
  75. 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
  76. 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
  77. 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
  78. 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
  79. 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
  80. 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
  81. 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
  82. 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
  83. 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
  84. 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
  85. 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
  86. 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
  87. 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
  88. 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
  89. 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
  90. 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
  91. 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
  92. 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
  93. 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
  94. 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
  95. 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
  96. 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
  97. 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
  98. };
  99. /* Table of CRC values for low-order byte */
  100. static uint8_t table_crc_lo[] = {
  101. 0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06,
  102. 0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD,
  103. 0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
  104. 0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A,
  105. 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4,
  106. 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
  107. 0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3,
  108. 0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4,
  109. 0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
  110. 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29,
  111. 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED,
  112. 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
  113. 0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60,
  114. 0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67,
  115. 0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
  116. 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68,
  117. 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E,
  118. 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
  119. 0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71,
  120. 0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92,
  121. 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
  122. 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B,
  123. 0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B,
  124. 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
  125. 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42,
  126. 0x43, 0x83, 0x41, 0x81, 0x80, 0x40
  127. };
  128. static const int TAB_HEADER_LENGTH[2] = {
  129. HEADER_LENGTH_RTU,
  130. HEADER_LENGTH_TCP
  131. };
  132. static const int TAB_CHECKSUM_LENGTH[2] = {
  133. CHECKSUM_LENGTH_RTU,
  134. CHECKSUM_LENGTH_TCP
  135. };
  136. static const int TAB_MAX_ADU_LENGTH[2] = {
  137. MAX_ADU_LENGTH_RTU,
  138. MAX_ADU_LENGTH_TCP,
  139. };
  140. /* Treats errors and flush or close connection if necessary */
  141. static void error_treat(modbus_param_t *mb_param, int code, const char *string)
  142. {
  143. printf("\nERROR %s (%0X)\n", string, -code);
  144. if (mb_param->error_handling == FLUSH_OR_CONNECT_ON_ERROR) {
  145. switch (code) {
  146. case INVALID_DATA:
  147. case INVALID_CRC:
  148. case INVALID_EXCEPTION_CODE:
  149. modbus_flush(mb_param);
  150. break;
  151. case SELECT_FAILURE:
  152. case SOCKET_FAILURE:
  153. case CONNECTION_CLOSED:
  154. modbus_close(mb_param);
  155. modbus_connect(mb_param);
  156. break;
  157. default:
  158. /* NOP */
  159. break;
  160. }
  161. }
  162. }
  163. void modbus_flush(modbus_param_t *mb_param)
  164. {
  165. if (mb_param->type_com == RTU) {
  166. tcflush(mb_param->fd, TCIOFLUSH);
  167. } else {
  168. int ret;
  169. do {
  170. /* Extract the garbage from the socket */
  171. char devnull[MAX_ADU_LENGTH_TCP];
  172. #if (!HAVE_DECL___CYGWIN__)
  173. ret = recv(mb_param->fd, devnull, MAX_ADU_LENGTH_TCP, MSG_DONTWAIT);
  174. #else
  175. /* On Cygwin, it's a bit more complicated to not wait */
  176. fd_set rfds;
  177. struct timeval tv;
  178. tv.tv_sec = 0;
  179. tv.tv_usec = 0;
  180. FD_ZERO(&rfds);
  181. FD_SET(mb_param->fd, &rfds);
  182. ret = select(mb_param->fd+1, &rfds, NULL, NULL, &tv);
  183. if (ret > 0) {
  184. ret = recv(mb_param->fd, devnull, MAX_ADU_LENGTH_TCP, 0);
  185. } else if (ret == -1) {
  186. /* error_treat() doesn't call modbus_flush() in
  187. this case (avoid infinite loop) */
  188. error_treat(mb_param, SELECT_FAILURE, "Select failure");
  189. }
  190. #endif
  191. if (mb_param->debug && ret > 0) {
  192. printf("%d bytes flushed\n", ret);
  193. }
  194. } while (ret > 0);
  195. }
  196. }
  197. /* Computes the length of the expected response */
  198. static unsigned int compute_response_length(modbus_param_t *mb_param,
  199. uint8_t *query)
  200. {
  201. int length;
  202. int offset;
  203. offset = TAB_HEADER_LENGTH[mb_param->type_com];
  204. switch (query[offset]) {
  205. case FC_READ_COIL_STATUS:
  206. case FC_READ_INPUT_STATUS: {
  207. /* Header + nb values (code from force_multiple_coils) */
  208. int nb = (query[offset + 3] << 8) | query[offset + 4];
  209. length = 2 + (nb / 8) + ((nb % 8) ? 1 : 0);
  210. }
  211. break;
  212. case FC_READ_HOLDING_REGISTERS:
  213. case FC_READ_INPUT_REGISTERS:
  214. /* Header + 2 * nb values */
  215. length = 2 + 2 * (query[offset + 3] << 8 |
  216. query[offset + 4]);
  217. break;
  218. case FC_READ_EXCEPTION_STATUS:
  219. length = 3;
  220. break;
  221. default:
  222. length = 5;
  223. }
  224. return length + offset + TAB_CHECKSUM_LENGTH[mb_param->type_com];
  225. }
  226. /* Builds a RTU query header */
  227. static int build_query_basis_rtu(int slave, int function,
  228. int start_addr, int nb,
  229. uint8_t *query)
  230. {
  231. query[0] = slave;
  232. query[1] = function;
  233. query[2] = start_addr >> 8;
  234. query[3] = start_addr & 0x00ff;
  235. query[4] = nb >> 8;
  236. query[5] = nb & 0x00ff;
  237. return PRESET_QUERY_LENGTH_RTU;
  238. }
  239. /* Builds a TCP query header */
  240. static int build_query_basis_tcp(int slave, int function,
  241. int start_addr, int nb,
  242. uint8_t *query)
  243. {
  244. /* Extract from MODBUS Messaging on TCP/IP Implementation
  245. Guide V1.0b (page 23/46):
  246. The transaction identifier is used to associate the future
  247. response with the request. So, at a time, on a TCP
  248. connection, this identifier must be unique.
  249. */
  250. static uint16_t t_id = 0;
  251. /* Transaction ID */
  252. if (t_id < UINT16_MAX)
  253. t_id++;
  254. else
  255. t_id = 0;
  256. query[0] = t_id >> 8;
  257. query[1] = t_id & 0x00ff;
  258. /* Protocol Modbus */
  259. query[2] = 0;
  260. query[3] = 0;
  261. /* Length will be defined later by set_query_length_tcp at offsets 4
  262. * and 5 */
  263. query[6] = slave;
  264. query[7] = function;
  265. query[8] = start_addr >> 8;
  266. query[9] = start_addr & 0x00ff;
  267. query[10] = nb >> 8;
  268. query[11] = nb & 0x00ff;
  269. return PRESET_QUERY_LENGTH_TCP;
  270. }
  271. static int build_query_basis(modbus_param_t *mb_param,
  272. int function, int start_addr,
  273. int nb, uint8_t *query)
  274. {
  275. if (mb_param->type_com == RTU)
  276. return build_query_basis_rtu(mb_param->slave, function,
  277. start_addr, nb, query);
  278. else
  279. return build_query_basis_tcp(mb_param->slave, function,
  280. start_addr, nb, query);
  281. }
  282. /* Builds a RTU response header */
  283. static int build_response_basis_rtu(sft_t *sft, uint8_t *response)
  284. {
  285. response[0] = sft->slave;
  286. response[1] = sft->function;
  287. return PRESET_RESPONSE_LENGTH_RTU;
  288. }
  289. /* Builds a TCP response header */
  290. static int build_response_basis_tcp(sft_t *sft, uint8_t *response)
  291. {
  292. /* Extract from MODBUS Messaging on TCP/IP Implementation
  293. Guide V1.0b (page 23/46):
  294. The transaction identifier is used to associate the future
  295. response with the request. */
  296. response[0] = sft->t_id >> 8;
  297. response[1] = sft->t_id & 0x00ff;
  298. /* Protocol Modbus */
  299. response[2] = 0;
  300. response[3] = 0;
  301. /* Length to fix later with set_message_length_tcp (4 and 5) */
  302. response[6] = sft->slave;
  303. response[7] = sft->function;
  304. return PRESET_RESPONSE_LENGTH_TCP;
  305. }
  306. static int build_response_basis(modbus_param_t *mb_param, sft_t *sft,
  307. uint8_t *response)
  308. {
  309. if (mb_param->type_com == RTU)
  310. return build_response_basis_rtu(sft, response);
  311. else
  312. return build_response_basis_tcp(sft, response);
  313. }
  314. /* Sets the length of TCP message in the message (query and response) */
  315. void set_message_length_tcp(uint8_t *msg, int msg_length)
  316. {
  317. /* Substract the header length to the message length */
  318. int mbap_length = msg_length - 6;
  319. msg[4] = mbap_length >> 8;
  320. msg[5] = mbap_length & 0x00FF;
  321. }
  322. /* Fast CRC */
  323. static uint16_t crc16(uint8_t *buffer, uint16_t buffer_length)
  324. {
  325. uint8_t crc_hi = 0xFF; /* high CRC byte initialized */
  326. uint8_t crc_lo = 0xFF; /* low CRC byte initialized */
  327. unsigned int i; /* will index into CRC lookup */
  328. /* pass through message buffer */
  329. while (buffer_length--) {
  330. i = crc_hi ^ *buffer++; /* calculate the CRC */
  331. crc_hi = crc_lo ^ table_crc_hi[i];
  332. crc_lo = table_crc_lo[i];
  333. }
  334. return (crc_hi << 8 | crc_lo);
  335. }
  336. /* If CRC is correct returns 0 else returns INVALID_CRC */
  337. static int check_crc16(modbus_param_t *mb_param,
  338. uint8_t *msg,
  339. const int msg_length)
  340. {
  341. int ret;
  342. uint16_t crc_calc;
  343. uint16_t crc_received;
  344. crc_calc = crc16(msg, msg_length - 2);
  345. crc_received = (msg[msg_length - 2] << 8) | msg[msg_length - 1];
  346. /* Check CRC of msg */
  347. if (crc_calc == crc_received) {
  348. ret = 0;
  349. } else {
  350. char s_error[64];
  351. sprintf(s_error,
  352. "invalid crc received %0X - crc_calc %0X",
  353. crc_received, crc_calc);
  354. ret = INVALID_CRC;
  355. error_treat(mb_param, ret, s_error);
  356. }
  357. return ret;
  358. }
  359. /* Sends a query/response over a serial or a TCP communication */
  360. static int modbus_send(modbus_param_t *mb_param, uint8_t *query,
  361. int query_length)
  362. {
  363. int ret;
  364. uint16_t s_crc;
  365. int i;
  366. if (mb_param->type_com == RTU) {
  367. s_crc = crc16(query, query_length);
  368. query[query_length++] = s_crc >> 8;
  369. query[query_length++] = s_crc & 0x00FF;
  370. } else {
  371. set_message_length_tcp(query, query_length);
  372. }
  373. if (mb_param->debug) {
  374. for (i = 0; i < query_length; i++)
  375. printf("[%.2X]", query[i]);
  376. printf("\n");
  377. }
  378. if (mb_param->type_com == RTU)
  379. ret = write(mb_param->fd, query, query_length);
  380. else
  381. ret = send(mb_param->fd, query, query_length, 0);
  382. /* Return the number of bytes written (0 to n)
  383. or SOCKET_FAILURE on error */
  384. if ((ret == -1) || (ret != query_length)) {
  385. ret = SOCKET_FAILURE;
  386. error_treat(mb_param, ret, "Write socket failure");
  387. }
  388. return ret;
  389. }
  390. /* Computes the length of the header following the function code */
  391. static uint8_t compute_query_length_header(int function)
  392. {
  393. int length;
  394. if (function <= FC_FORCE_SINGLE_COIL ||
  395. function == FC_PRESET_SINGLE_REGISTER)
  396. /* Read and single write */
  397. length = 4;
  398. else if (function == FC_FORCE_MULTIPLE_COILS ||
  399. function == FC_PRESET_MULTIPLE_REGISTERS)
  400. /* Multiple write */
  401. length = 5;
  402. else
  403. length = 0;
  404. return length;
  405. }
  406. /* Computes the length of the data to write in the query */
  407. static int compute_query_length_data(modbus_param_t *mb_param, uint8_t *msg)
  408. {
  409. int function = msg[TAB_HEADER_LENGTH[mb_param->type_com]];
  410. int length;
  411. if (function == FC_FORCE_MULTIPLE_COILS ||
  412. function == FC_PRESET_MULTIPLE_REGISTERS)
  413. length = msg[TAB_HEADER_LENGTH[mb_param->type_com] + 5];
  414. else
  415. length = 0;
  416. length += TAB_CHECKSUM_LENGTH[mb_param->type_com];
  417. return length;
  418. }
  419. #define WAIT_DATA() \
  420. { \
  421. while ((select_ret = select(mb_param->fd+1, &rfds, NULL, NULL, &tv)) == -1) { \
  422. if (errno == EINTR) { \
  423. printf("A non blocked signal was caught\n"); \
  424. /* Necessary after an error */ \
  425. FD_ZERO(&rfds); \
  426. FD_SET(mb_param->fd, &rfds); \
  427. } else { \
  428. error_treat(mb_param, SELECT_FAILURE, "Select failure"); \
  429. return SELECT_FAILURE; \
  430. } \
  431. } \
  432. \
  433. if (select_ret == 0) { \
  434. /* Call to error_treat is done later to manage exceptions */ \
  435. return SELECT_TIMEOUT; \
  436. } \
  437. }
  438. /* Waits a reply from a modbus slave or a query from a modbus master.
  439. This function blocks for timeout seconds if there is no reply.
  440. In
  441. - msg_length_computed must be set to MSG_LENGTH_UNDEFINED if undefined
  442. Out
  443. - msg is an array of uint8_t to receive the message
  444. - p_msg_length, the variable is assigned to the number of
  445. characters received. This value won't be greater than
  446. msg_length_computed.
  447. Returns 0 in success or a negative value if an error occured.
  448. */
  449. static int receive_msg(modbus_param_t *mb_param,
  450. int msg_length_computed,
  451. uint8_t *msg, int *p_msg_length)
  452. {
  453. int select_ret;
  454. int read_ret;
  455. fd_set rfds;
  456. struct timeval tv;
  457. int length_to_read;
  458. uint8_t *p_msg;
  459. enum { FUNCTION, BYTE, COMPLETE };
  460. int state;
  461. if (mb_param->debug) {
  462. if (msg_length_computed == MSG_LENGTH_UNDEFINED)
  463. printf("Waiting for a message...\n");
  464. else
  465. printf("Waiting for a message (%d bytes)...\n",
  466. msg_length_computed);
  467. }
  468. /* Add a file descriptor to the set */
  469. FD_ZERO(&rfds);
  470. FD_SET(mb_param->fd, &rfds);
  471. if (msg_length_computed == MSG_LENGTH_UNDEFINED) {
  472. /* Wait for a message */
  473. tv.tv_sec = 60;
  474. tv.tv_usec = 0;
  475. /* The message length is undefined (query receiving) so
  476. * we need to analyse the message step by step.
  477. * At the first step, we want to reach the function
  478. * code because all packets have that information. */
  479. state = FUNCTION;
  480. msg_length_computed = TAB_HEADER_LENGTH[mb_param->type_com] + 1;
  481. } else {
  482. tv.tv_sec = 0;
  483. tv.tv_usec = TIME_OUT_BEGIN_OF_TRAME;
  484. state = COMPLETE;
  485. }
  486. length_to_read = msg_length_computed;
  487. select_ret = 0;
  488. WAIT_DATA();
  489. /* Initialize the readin the message */
  490. (*p_msg_length) = 0;
  491. p_msg = msg;
  492. while (select_ret) {
  493. if (mb_param->type_com == RTU)
  494. read_ret = read(mb_param->fd, p_msg, length_to_read);
  495. else
  496. read_ret = recv(mb_param->fd, p_msg, length_to_read, 0);
  497. if (read_ret == 0) {
  498. return CONNECTION_CLOSED;
  499. } else if (read_ret < 0) {
  500. /* The only negative possible value is -1 */
  501. error_treat(mb_param, SOCKET_FAILURE,
  502. "Read socket failure");
  503. return SOCKET_FAILURE;
  504. }
  505. /* Sums bytes received */
  506. (*p_msg_length) += read_ret;
  507. /* Display the hex code of each character received */
  508. if (mb_param->debug) {
  509. int i;
  510. for (i=0; i < read_ret; i++)
  511. printf("<%.2X>", p_msg[i]);
  512. }
  513. if ((*p_msg_length) < msg_length_computed) {
  514. /* Message incomplete */
  515. length_to_read = msg_length_computed - (*p_msg_length);
  516. } else {
  517. switch (state) {
  518. case FUNCTION:
  519. /* Function code position */
  520. length_to_read = compute_query_length_header(
  521. msg[TAB_HEADER_LENGTH[mb_param->type_com]]);
  522. msg_length_computed += length_to_read;
  523. /* It's useless to check
  524. p_msg_length_computed value in this
  525. case (only defined values are used). */
  526. state = BYTE;
  527. break;
  528. case BYTE:
  529. length_to_read = compute_query_length_data(mb_param, msg);
  530. msg_length_computed += length_to_read;
  531. if (msg_length_computed > TAB_MAX_ADU_LENGTH[mb_param->type_com]) {
  532. error_treat(mb_param, INVALID_DATA, "Too many data");
  533. return INVALID_DATA;
  534. }
  535. state = COMPLETE;
  536. break;
  537. case COMPLETE:
  538. length_to_read = 0;
  539. break;
  540. }
  541. }
  542. /* Moves the pointer to receive other data */
  543. p_msg = &(p_msg[read_ret]);
  544. if (length_to_read > 0) {
  545. /* If no character at the buffer wait
  546. TIME_OUT_END_OF_TRAME before to generate an error. */
  547. tv.tv_sec = 0;
  548. tv.tv_usec = TIME_OUT_END_OF_TRAME;
  549. WAIT_DATA();
  550. } else {
  551. /* All chars are received */
  552. select_ret = FALSE;
  553. }
  554. }
  555. if (mb_param->debug)
  556. printf("\n");
  557. if (mb_param->type_com == RTU) {
  558. return check_crc16(mb_param, msg, (*p_msg_length));
  559. } else {
  560. /* OK */
  561. return 0;
  562. }
  563. }
  564. /* Listens for any query from a modbus master in TCP, requires the socket file
  565. descriptor etablished with the master device in argument or -1 to use the
  566. internal one of modbus_param_t.
  567. Returns:
  568. - 0 on success, or a negative error number if the request fails
  569. - query, message received
  570. - query_length, length in bytes of the message */
  571. int modbus_slave_receive(modbus_param_t *mb_param, int sockfd,
  572. uint8_t *query, int *query_length)
  573. {
  574. int ret;
  575. if (sockfd != -1) {
  576. mb_param->fd = sockfd;
  577. }
  578. /* The length of the query to receive isn't known. */
  579. ret = receive_msg(mb_param, MSG_LENGTH_UNDEFINED, query, query_length);
  580. return ret;
  581. }
  582. /* Receives the response and checks values (and checksum in RTU).
  583. Returns:
  584. - the number of values (bits or word) if success or the response
  585. length if no value is returned
  586. - less than 0 for exception errors
  587. Note: all functions used to send or receive data with modbus return
  588. these values. */
  589. static int modbus_receive(modbus_param_t *mb_param,
  590. uint8_t *query,
  591. uint8_t *response)
  592. {
  593. int ret;
  594. int response_length;
  595. int response_length_computed;
  596. int offset = TAB_HEADER_LENGTH[mb_param->type_com];
  597. response_length_computed = compute_response_length(mb_param, query);
  598. ret = receive_msg(mb_param, response_length_computed,
  599. response, &response_length);
  600. if (ret == 0) {
  601. /* GOOD RESPONSE */
  602. int query_nb_value;
  603. int response_nb_value;
  604. /* The number of values is returned if it's corresponding
  605. * to the query */
  606. switch (response[offset]) {
  607. case FC_READ_COIL_STATUS:
  608. case FC_READ_INPUT_STATUS:
  609. /* Read functions, 8 values in a byte (nb
  610. * of values in the query and byte count in
  611. * the response. */
  612. query_nb_value = (query[offset + 3] << 8) + query[offset + 4];
  613. query_nb_value = (query_nb_value / 8) + ((query_nb_value % 8) ? 1 : 0);
  614. response_nb_value = response[offset + 1];
  615. break;
  616. case FC_READ_HOLDING_REGISTERS:
  617. case FC_READ_INPUT_REGISTERS:
  618. /* Read functions 1 value = 2 bytes */
  619. query_nb_value = (query[offset + 3] << 8) + query[offset + 4];
  620. response_nb_value = (response[offset + 1] / 2);
  621. break;
  622. case FC_FORCE_MULTIPLE_COILS:
  623. case FC_PRESET_MULTIPLE_REGISTERS:
  624. /* N Write functions */
  625. query_nb_value = (query[offset + 3] << 8) + query[offset + 4];
  626. response_nb_value = (response[offset + 3] << 8) | response[offset + 4];
  627. break;
  628. case FC_REPORT_SLAVE_ID:
  629. /* Report slave ID (bytes received) */
  630. query_nb_value = response_nb_value = response_length;
  631. break;
  632. default:
  633. /* 1 Write functions & others */
  634. query_nb_value = response_nb_value = 1;
  635. }
  636. if (query_nb_value == response_nb_value) {
  637. ret = response_nb_value;
  638. } else {
  639. char *s_error = malloc(64 * sizeof(char));
  640. sprintf(s_error, "Quantity not corresponding to the query (%d != %d)",
  641. response_nb_value, query_nb_value);
  642. ret = INVALID_DATA;
  643. error_treat(mb_param, ret, s_error);
  644. free(s_error);
  645. }
  646. } else if (ret == SELECT_TIMEOUT) {
  647. if (response_length == (offset + 2 + TAB_CHECKSUM_LENGTH[mb_param->type_com])) {
  648. /* EXCEPTION CODE RECEIVED */
  649. /* Optimization allowed because exception response is
  650. the smallest trame in modbus protocol (3) so always
  651. raise a timeout error */
  652. /* CRC must be checked here (not done in receive_msg) */
  653. if (mb_param->type_com == RTU) {
  654. ret = check_crc16(mb_param, response, response_length);
  655. if (ret != 0)
  656. return ret;
  657. }
  658. /* Check for exception response.
  659. 0x80 + function is stored in the exception
  660. response. */
  661. if (0x80 + query[offset] == response[offset]) {
  662. int exception_code = response[offset + 1];
  663. // FIXME check test
  664. if (exception_code < NB_TAB_ERROR_MSG) {
  665. error_treat(mb_param, -exception_code,
  666. TAB_ERROR_MSG[response[offset + 1]]);
  667. /* RETURN THE EXCEPTION CODE */
  668. /* Modbus error code is negative */
  669. return -exception_code;
  670. } else {
  671. /* The chances are low to hit this
  672. case but it can avoid a vicious
  673. segfault */
  674. char *s_error = malloc(64 * sizeof(char));
  675. sprintf(s_error,
  676. "Invalid exception code %d",
  677. response[offset + 1]);
  678. error_treat(mb_param, INVALID_EXCEPTION_CODE,
  679. s_error);
  680. free(s_error);
  681. return INVALID_EXCEPTION_CODE;
  682. }
  683. }
  684. /* If doesn't return previously, return as
  685. TIME OUT here */
  686. }
  687. error_treat(mb_param, ret, "Select timeout");
  688. return ret;
  689. }
  690. return ret;
  691. }
  692. static int response_io_status(int address, int nb,
  693. uint8_t *tab_io_status,
  694. uint8_t *response, int offset)
  695. {
  696. int shift = 0;
  697. int byte = 0;
  698. int i;
  699. for (i = address; i < address+nb; i++) {
  700. byte |= tab_io_status[i] << shift;
  701. if (shift == 7) {
  702. /* Byte is full */
  703. response[offset++] = byte;
  704. byte = shift = 0;
  705. } else {
  706. shift++;
  707. }
  708. }
  709. if (shift != 0)
  710. response[offset++] = byte;
  711. return offset;
  712. }
  713. /* Build the exception response */
  714. static int response_exception(modbus_param_t *mb_param, sft_t *sft,
  715. int exception_code, uint8_t *response)
  716. {
  717. int response_length;
  718. sft->function = sft->function + 0x80;
  719. response_length = build_response_basis(mb_param, sft, response);
  720. /* Positive exception code */
  721. response[response_length++] = -exception_code;
  722. return response_length;
  723. }
  724. /* Manages the received query.
  725. Analyses the query and constructs a response.
  726. If an error occurs, this function construct the response
  727. accordingly.
  728. */
  729. void modbus_slave_manage(modbus_param_t *mb_param, const uint8_t *query,
  730. int query_length, modbus_mapping_t *mb_mapping)
  731. {
  732. int offset = TAB_HEADER_LENGTH[mb_param->type_com];
  733. int slave = query[offset - 1];
  734. int function = query[offset];
  735. uint16_t address = (query[offset + 1] << 8) + query[offset + 2];
  736. uint8_t response[MAX_MESSAGE_LENGTH];
  737. int resp_length = 0;
  738. sft_t sft;
  739. if (slave != mb_param->slave && slave != MODBUS_BROADCAST_ADDRESS) {
  740. // Ignores the query (not for me)
  741. if (mb_param->debug) {
  742. printf("Request for slave %d ignored (not %d)\n",
  743. slave, mb_param->slave);
  744. }
  745. return;
  746. }
  747. sft.slave = slave;
  748. sft.function = function;
  749. if (mb_param->type_com == TCP) {
  750. sft.t_id = (query[0] << 8) + query[1];
  751. } else {
  752. sft.t_id = 0;
  753. query_length -= CHECKSUM_LENGTH_RTU;
  754. }
  755. switch (function) {
  756. case FC_READ_COIL_STATUS: {
  757. int nb = (query[offset + 3] << 8) + query[offset + 4];
  758. if ((address + nb) > mb_mapping->nb_coil_status) {
  759. printf("Illegal data address %0X in read_coil_status\n",
  760. address + nb);
  761. resp_length = response_exception(mb_param, &sft,
  762. ILLEGAL_DATA_ADDRESS, response);
  763. } else {
  764. resp_length = build_response_basis(mb_param, &sft, response);
  765. response[resp_length++] = (nb / 8) + ((nb % 8) ? 1 : 0);
  766. resp_length = response_io_status(address, nb,
  767. mb_mapping->tab_coil_status,
  768. response, resp_length);
  769. }
  770. }
  771. break;
  772. case FC_READ_INPUT_STATUS: {
  773. /* Similar to coil status (but too much arguments to use a
  774. * function) */
  775. int nb = (query[offset + 3] << 8) + query[offset + 4];
  776. if ((address + nb) > mb_mapping->nb_input_status) {
  777. printf("Illegal data address %0X in read_input_status\n",
  778. address + nb);
  779. resp_length = response_exception(mb_param, &sft,
  780. ILLEGAL_DATA_ADDRESS, response);
  781. } else {
  782. resp_length = build_response_basis(mb_param, &sft, response);
  783. response[resp_length++] = (nb / 8) + ((nb % 8) ? 1 : 0);
  784. resp_length = response_io_status(address, nb,
  785. mb_mapping->tab_input_status,
  786. response, resp_length);
  787. }
  788. }
  789. break;
  790. case FC_READ_HOLDING_REGISTERS: {
  791. int nb = (query[offset + 3] << 8) + query[offset + 4];
  792. if ((address + nb) > mb_mapping->nb_holding_registers) {
  793. printf("Illegal data address %0X in read_holding_registers\n",
  794. address + nb);
  795. resp_length = response_exception(mb_param, &sft,
  796. ILLEGAL_DATA_ADDRESS, response);
  797. } else {
  798. int i;
  799. resp_length = build_response_basis(mb_param, &sft, response);
  800. response[resp_length++] = nb << 1;
  801. for (i = address; i < address + nb; i++) {
  802. response[resp_length++] = mb_mapping->tab_holding_registers[i] >> 8;
  803. response[resp_length++] = mb_mapping->tab_holding_registers[i] & 0xFF;
  804. }
  805. }
  806. }
  807. break;
  808. case FC_READ_INPUT_REGISTERS: {
  809. /* Similar to holding registers (but too much arguments to use a
  810. * function) */
  811. int nb = (query[offset + 3] << 8) + query[offset + 4];
  812. if ((address + nb) > mb_mapping->nb_input_registers) {
  813. printf("Illegal data address %0X in read_input_registers\n",
  814. address + nb);
  815. resp_length = response_exception(mb_param, &sft,
  816. ILLEGAL_DATA_ADDRESS, response);
  817. } else {
  818. int i;
  819. resp_length = build_response_basis(mb_param, &sft, response);
  820. response[resp_length++] = nb << 1;
  821. for (i = address; i < address + nb; i++) {
  822. response[resp_length++] = mb_mapping->tab_input_registers[i] >> 8;
  823. response[resp_length++] = mb_mapping->tab_input_registers[i] & 0xFF;
  824. }
  825. }
  826. }
  827. break;
  828. case FC_FORCE_SINGLE_COIL:
  829. if (address >= mb_mapping->nb_coil_status) {
  830. printf("Illegal data address %0X in force_singe_coil\n", address);
  831. resp_length = response_exception(mb_param, &sft,
  832. ILLEGAL_DATA_ADDRESS, response);
  833. } else {
  834. int data = (query[offset + 3] << 8) + query[offset + 4];
  835. if (data == 0xFF00 || data == 0x0) {
  836. mb_mapping->tab_coil_status[address] = (data) ? ON : OFF;
  837. /* In RTU mode, the CRC is computed and added
  838. to the query by modbus_send, the computed
  839. CRC will be same and optimisation is
  840. possible here (FIXME). */
  841. memcpy(response, query, query_length);
  842. resp_length = query_length;
  843. } else {
  844. printf("Illegal data value %0X in force_single_coil request at address %0X\n",
  845. data, address);
  846. resp_length = response_exception(mb_param, &sft,
  847. ILLEGAL_DATA_VALUE, response);
  848. }
  849. }
  850. break;
  851. case FC_PRESET_SINGLE_REGISTER:
  852. if (address >= mb_mapping->nb_holding_registers) {
  853. printf("Illegal data address %0X in preset_holding_register\n", address);
  854. resp_length = response_exception(mb_param, &sft,
  855. ILLEGAL_DATA_ADDRESS, response);
  856. } else {
  857. int data = (query[offset + 3] << 8) + query[offset + 4];
  858. mb_mapping->tab_holding_registers[address] = data;
  859. memcpy(response, query, query_length);
  860. resp_length = query_length;
  861. }
  862. break;
  863. case FC_FORCE_MULTIPLE_COILS: {
  864. int nb = (query[offset + 3] << 8) + query[offset + 4];
  865. if ((address + nb) > mb_mapping->nb_coil_status) {
  866. printf("Illegal data address %0X in force_multiple_coils\n",
  867. address + nb);
  868. resp_length = response_exception(mb_param, &sft,
  869. ILLEGAL_DATA_ADDRESS, response);
  870. } else {
  871. /* 6 = byte count */
  872. set_bits_from_bytes(mb_mapping->tab_coil_status, address, nb, &query[offset + 6]);
  873. resp_length = build_response_basis(mb_param, &sft, response);
  874. /* 4 to copy the coil address (2) and the quantity of coils */
  875. memcpy(response + resp_length, query + resp_length, 4);
  876. resp_length += 4;
  877. }
  878. }
  879. break;
  880. case FC_PRESET_MULTIPLE_REGISTERS: {
  881. int nb = (query[offset + 3] << 8) + query[offset + 4];
  882. if ((address + nb) > mb_mapping->nb_holding_registers) {
  883. printf("Illegal data address %0X in preset_multiple_registers\n",
  884. address + nb);
  885. resp_length = response_exception(mb_param, &sft,
  886. ILLEGAL_DATA_ADDRESS, response);
  887. } else {
  888. int i, j;
  889. for (i = address, j = 6; i < address + nb; i++, j += 2) {
  890. /* 6 and 7 = first value */
  891. mb_mapping->tab_holding_registers[i] =
  892. (query[offset + j] << 8) + query[offset + j + 1];
  893. }
  894. resp_length = build_response_basis(mb_param, &sft, response);
  895. /* 4 to copy the address (2) and the no. of registers */
  896. memcpy(response + resp_length, query + resp_length, 4);
  897. resp_length += 4;
  898. }
  899. }
  900. break;
  901. case FC_READ_EXCEPTION_STATUS:
  902. case FC_REPORT_SLAVE_ID:
  903. printf("Not implemented\n");
  904. break;
  905. }
  906. modbus_send(mb_param, response, resp_length);
  907. }
  908. /* Reads IO status */
  909. static int read_io_status(modbus_param_t *mb_param, int function,
  910. int start_addr, int nb, uint8_t *data_dest)
  911. {
  912. int ret;
  913. int query_length;
  914. uint8_t query[MIN_QUERY_LENGTH];
  915. uint8_t response[MAX_MESSAGE_LENGTH];
  916. query_length = build_query_basis(mb_param, function,
  917. start_addr, nb, query);
  918. ret = modbus_send(mb_param, query, query_length);
  919. if (ret > 0) {
  920. int i, temp, bit;
  921. int pos = 0;
  922. int offset;
  923. int offset_end;
  924. ret = modbus_receive(mb_param, query, response);
  925. if (ret < 0)
  926. return ret;
  927. offset = TAB_HEADER_LENGTH[mb_param->type_com];
  928. offset_end = offset + ret;
  929. for (i = offset; i < offset_end; i++) {
  930. /* Shift reg hi_byte to temp */
  931. temp = response[i + 2];
  932. for (bit = 0x01; (bit & 0xff) && (pos < nb);) {
  933. data_dest[pos++] = (temp & bit) ? TRUE : FALSE;
  934. bit = bit << 1;
  935. }
  936. }
  937. }
  938. return ret;
  939. }
  940. /* Reads the boolean status of coils and sets the array elements
  941. in the destination to TRUE or FALSE. */
  942. int read_coil_status(modbus_param_t *mb_param, int start_addr,
  943. int nb, uint8_t *data_dest)
  944. {
  945. int status;
  946. if (nb > MAX_STATUS) {
  947. printf("ERROR Too many coils status requested (%d > %d)\n",
  948. nb, MAX_STATUS);
  949. return INVALID_DATA;
  950. }
  951. status = read_io_status(mb_param, FC_READ_COIL_STATUS,
  952. start_addr, nb, data_dest);
  953. if (status > 0)
  954. status = nb;
  955. return status;
  956. }
  957. /* Same as read_coil_status but reads the slaves input table */
  958. int read_input_status(modbus_param_t *mb_param, int start_addr,
  959. int nb, uint8_t *data_dest)
  960. {
  961. int status;
  962. if (nb > MAX_STATUS) {
  963. printf("ERROR Too many input status requested (%d > %d)\n",
  964. nb, MAX_STATUS);
  965. return INVALID_DATA;
  966. }
  967. status = read_io_status(mb_param, FC_READ_INPUT_STATUS,
  968. start_addr, nb, data_dest);
  969. if (status > 0)
  970. status = nb;
  971. return status;
  972. }
  973. /* Reads the data from a modbus slave and put that data into an array */
  974. static int read_registers(modbus_param_t *mb_param, int function,
  975. int start_addr, int nb, uint16_t *data_dest)
  976. {
  977. int ret;
  978. int query_length;
  979. uint8_t query[MIN_QUERY_LENGTH];
  980. uint8_t response[MAX_MESSAGE_LENGTH];
  981. if (nb > MAX_REGISTERS) {
  982. printf("ERROR Too many holding registers requested (%d > %d)\n",
  983. nb, MAX_REGISTERS);
  984. return INVALID_DATA;
  985. }
  986. query_length = build_query_basis(mb_param, function,
  987. start_addr, nb, query);
  988. ret = modbus_send(mb_param, query, query_length);
  989. if (ret > 0) {
  990. int offset;
  991. int i;
  992. ret = modbus_receive(mb_param, query, response);
  993. offset = TAB_HEADER_LENGTH[mb_param->type_com];
  994. /* If ret is negative, the loop is jumped ! */
  995. for (i = 0; i < ret; i++) {
  996. /* shift reg hi_byte to temp OR with lo_byte */
  997. data_dest[i] = (response[offset + 2 + (i << 1)] << 8) |
  998. response[offset + 3 + (i << 1)];
  999. }
  1000. }
  1001. return ret;
  1002. }
  1003. /* Reads the holding registers in a slave and put the data into an
  1004. array */
  1005. int read_holding_registers(modbus_param_t *mb_param,
  1006. int start_addr, int nb, uint16_t *data_dest)
  1007. {
  1008. int status;
  1009. if (nb > MAX_REGISTERS) {
  1010. printf("ERROR Too many holding registers requested (%d > %d)\n",
  1011. nb, MAX_REGISTERS);
  1012. return INVALID_DATA;
  1013. }
  1014. status = read_registers(mb_param, FC_READ_HOLDING_REGISTERS,
  1015. start_addr, nb, data_dest);
  1016. return status;
  1017. }
  1018. /* Reads the input registers in a slave and put the data into
  1019. an array */
  1020. int read_input_registers(modbus_param_t *mb_param, int start_addr, int nb,
  1021. uint16_t *data_dest)
  1022. {
  1023. int status;
  1024. if (nb > MAX_REGISTERS) {
  1025. printf("ERROR Too many input registers requested (%d > %d)\n",
  1026. nb, MAX_REGISTERS);
  1027. return INVALID_DATA;
  1028. }
  1029. status = read_registers(mb_param, FC_READ_INPUT_REGISTERS,
  1030. start_addr, nb, data_dest);
  1031. return status;
  1032. }
  1033. /* Sends a value to a register in a slave.
  1034. Used by force_single_coil and preset_single_register */
  1035. static int set_single(modbus_param_t *mb_param, int function,
  1036. int addr, int value)
  1037. {
  1038. int ret;
  1039. int query_length;
  1040. uint8_t query[MIN_QUERY_LENGTH];
  1041. query_length = build_query_basis(mb_param, function,
  1042. addr, value, query);
  1043. ret = modbus_send(mb_param, query, query_length);
  1044. if (ret > 0) {
  1045. /* Used by force_single_coil and
  1046. * preset_single_register */
  1047. uint8_t response[MIN_QUERY_LENGTH];
  1048. ret = modbus_receive(mb_param, query, response);
  1049. }
  1050. return ret;
  1051. }
  1052. /* Turns ON or OFF a single coil in the slave device */
  1053. int force_single_coil(modbus_param_t *mb_param, int coil_addr, int state)
  1054. {
  1055. int status;
  1056. if (state)
  1057. state = 0xFF00;
  1058. status = set_single(mb_param, FC_FORCE_SINGLE_COIL,
  1059. coil_addr, state);
  1060. return status;
  1061. }
  1062. /* Sets a value in one holding register in the slave device */
  1063. int preset_single_register(modbus_param_t *mb_param, int reg_addr, int value)
  1064. {
  1065. int status;
  1066. status = set_single(mb_param, FC_PRESET_SINGLE_REGISTER,
  1067. reg_addr, value);
  1068. return status;
  1069. }
  1070. /* Sets/resets the coils in the slave from an array in argument */
  1071. int force_multiple_coils(modbus_param_t *mb_param, int start_addr, int nb,
  1072. const uint8_t *data_src)
  1073. {
  1074. int ret;
  1075. int i;
  1076. int byte_count;
  1077. int query_length;
  1078. int coil_check = 0;
  1079. int pos = 0;
  1080. uint8_t query[MAX_MESSAGE_LENGTH];
  1081. if (nb > MAX_STATUS) {
  1082. printf("ERROR Writing to too many coils (%d > %d)\n",
  1083. nb, MAX_STATUS);
  1084. return INVALID_DATA;
  1085. }
  1086. query_length = build_query_basis(mb_param, FC_FORCE_MULTIPLE_COILS,
  1087. start_addr, nb, query);
  1088. byte_count = (nb / 8) + ((nb % 8) ? 1 : 0);
  1089. query[query_length++] = byte_count;
  1090. for (i = 0; i < byte_count; i++) {
  1091. int bit;
  1092. bit = 0x01;
  1093. query[query_length] = 0;
  1094. while ((bit & 0xFF) && (coil_check++ < nb)) {
  1095. if (data_src[pos++])
  1096. query[query_length] |= bit;
  1097. else
  1098. query[query_length] &=~ bit;
  1099. bit = bit << 1;
  1100. }
  1101. query_length++;
  1102. }
  1103. ret = modbus_send(mb_param, query, query_length);
  1104. if (ret > 0) {
  1105. uint8_t response[MAX_MESSAGE_LENGTH];
  1106. ret = modbus_receive(mb_param, query, response);
  1107. }
  1108. return ret;
  1109. }
  1110. /* Copies the values in the slave from the array given in argument */
  1111. int preset_multiple_registers(modbus_param_t *mb_param, int start_addr, int nb,
  1112. const uint16_t *data_src)
  1113. {
  1114. int ret;
  1115. int i;
  1116. int query_length;
  1117. int byte_count;
  1118. uint8_t query[MAX_MESSAGE_LENGTH];
  1119. if (nb > MAX_REGISTERS) {
  1120. printf("ERROR Trying to write to too many registers (%d > %d)\n",
  1121. nb, MAX_REGISTERS);
  1122. return INVALID_DATA;
  1123. }
  1124. query_length = build_query_basis(mb_param, FC_PRESET_MULTIPLE_REGISTERS,
  1125. start_addr, nb, query);
  1126. byte_count = nb * 2;
  1127. query[query_length++] = byte_count;
  1128. for (i = 0; i < nb; i++) {
  1129. query[query_length++] = data_src[i] >> 8;
  1130. query[query_length++] = data_src[i] & 0x00FF;
  1131. }
  1132. ret = modbus_send(mb_param, query, query_length);
  1133. if (ret > 0) {
  1134. uint8_t response[MAX_MESSAGE_LENGTH];
  1135. ret = modbus_receive(mb_param, query, response);
  1136. }
  1137. return ret;
  1138. }
  1139. /* Returns the slave id! */
  1140. int report_slave_id(modbus_param_t *mb_param, uint8_t *data_dest)
  1141. {
  1142. int ret;
  1143. int query_length;
  1144. uint8_t query[MIN_QUERY_LENGTH];
  1145. query_length = build_query_basis(mb_param, FC_REPORT_SLAVE_ID, 0, 0, query);
  1146. /* HACKISH, start_addr and count are not used */
  1147. query_length -= 4;
  1148. ret = modbus_send(mb_param, query, query_length);
  1149. if (ret > 0) {
  1150. int i;
  1151. int offset;
  1152. int offset_end;
  1153. uint8_t response[MAX_MESSAGE_LENGTH];
  1154. /* Byte count, slave id, run indicator status,
  1155. additional data */
  1156. ret = modbus_receive(mb_param, query, response);
  1157. if (ret < 0)
  1158. return ret;
  1159. offset = TAB_HEADER_LENGTH[mb_param->type_com] - 1;
  1160. offset_end = offset + ret;
  1161. for (i = offset; i < offset_end; i++)
  1162. data_dest[i] = response[i];
  1163. }
  1164. return ret;
  1165. }
  1166. /* Initializes the modbus_param_t structure for RTU
  1167. - device: "/dev/ttyS0"
  1168. - baud: 9600, 19200, 57600, 115200, etc
  1169. - parity: "even", "odd" or "none"
  1170. - data_bits: 5, 6, 7, 8
  1171. - stop_bits: 1, 2
  1172. */
  1173. void modbus_init_rtu(modbus_param_t *mb_param, const char *device,
  1174. int baud, const char *parity, int data_bit,
  1175. int stop_bit, int slave)
  1176. {
  1177. memset(mb_param, 0, sizeof(modbus_param_t));
  1178. strcpy(mb_param->device, device);
  1179. mb_param->baud = baud;
  1180. strcpy(mb_param->parity, parity);
  1181. mb_param->debug = FALSE;
  1182. mb_param->data_bit = data_bit;
  1183. mb_param->stop_bit = stop_bit;
  1184. mb_param->type_com = RTU;
  1185. mb_param->error_handling = FLUSH_OR_CONNECT_ON_ERROR;
  1186. mb_param->slave = slave;
  1187. }
  1188. /* Initializes the modbus_param_t structure for TCP.
  1189. - ip : "192.168.0.5"
  1190. - port : 1099
  1191. Set the port to MODBUS_TCP_DEFAULT_PORT to use the default one
  1192. (502). It's convenient to use a port number greater than or equal
  1193. to 1024 because it's not necessary to be root to use this port
  1194. number.
  1195. */
  1196. void modbus_init_tcp(modbus_param_t *mb_param, const char *ip, int port, int slave)
  1197. {
  1198. memset(mb_param, 0, sizeof(modbus_param_t));
  1199. strncpy(mb_param->ip, ip, sizeof(char)*16);
  1200. mb_param->port = port;
  1201. mb_param->type_com = TCP;
  1202. mb_param->error_handling = FLUSH_OR_CONNECT_ON_ERROR;
  1203. mb_param->slave = slave;
  1204. }
  1205. /* By default, the error handling mode used is FLUSH_OR_CONNECT_ON_ERROR.
  1206. With FLUSH_OR_CONNECT_ON_ERROR, the library will attempt an immediate
  1207. reconnection which may hang for several seconds if the network to
  1208. the remote target unit is down.
  1209. With NOP_ON_ERROR, it is expected that the application will
  1210. check for error returns and deal with them as necessary.
  1211. */
  1212. void modbus_set_error_handling(modbus_param_t *mb_param,
  1213. error_handling_t error_handling)
  1214. {
  1215. if (error_handling == FLUSH_OR_CONNECT_ON_ERROR ||
  1216. error_handling == NOP_ON_ERROR) {
  1217. mb_param->error_handling = error_handling;
  1218. } else {
  1219. printf("Invalid setting for error handling (not changed)\n");
  1220. }
  1221. }
  1222. /* Sets up a serial port for RTU communications */
  1223. static int modbus_connect_rtu(modbus_param_t *mb_param)
  1224. {
  1225. struct termios tios;
  1226. speed_t speed;
  1227. if (mb_param->debug) {
  1228. printf("Opening %s at %d bauds (%s)\n",
  1229. mb_param->device, mb_param->baud, mb_param->parity);
  1230. }
  1231. /* The O_NOCTTY flag tells UNIX that this program doesn't want
  1232. to be the "controlling terminal" for that port. If you
  1233. don't specify this then any input (such as keyboard abort
  1234. signals and so forth) will affect your process
  1235. Timeouts are ignored in canonical input mode or when the
  1236. NDELAY option is set on the file via open or fcntl */
  1237. mb_param->fd = open(mb_param->device, O_RDWR | O_NOCTTY | O_NDELAY);
  1238. if (mb_param->fd < 0) {
  1239. perror("open");
  1240. printf("ERROR Can't open the device %s (%s)\n",
  1241. mb_param->device, strerror(errno));
  1242. return -1;
  1243. }
  1244. /* Save */
  1245. tcgetattr(mb_param->fd, &(mb_param->old_tios));
  1246. memset(&tios, 0, sizeof(struct termios));
  1247. /* C_ISPEED Input baud (new interface)
  1248. C_OSPEED Output baud (new interface)
  1249. */
  1250. switch (mb_param->baud) {
  1251. case 110:
  1252. speed = B110;
  1253. break;
  1254. case 300:
  1255. speed = B300;
  1256. break;
  1257. case 600:
  1258. speed = B600;
  1259. break;
  1260. case 1200:
  1261. speed = B1200;
  1262. break;
  1263. case 2400:
  1264. speed = B2400;
  1265. break;
  1266. case 4800:
  1267. speed = B4800;
  1268. break;
  1269. case 9600:
  1270. speed = B9600;
  1271. break;
  1272. case 19200:
  1273. speed = B19200;
  1274. break;
  1275. case 38400:
  1276. speed = B38400;
  1277. break;
  1278. case 57600:
  1279. speed = B57600;
  1280. break;
  1281. case 115200:
  1282. speed = B115200;
  1283. break;
  1284. default:
  1285. speed = B9600;
  1286. printf("WARNING Unknown baud rate %d for %s (B9600 used)\n",
  1287. mb_param->baud, mb_param->device);
  1288. }
  1289. /* Set the baud rate */
  1290. if ((cfsetispeed(&tios, speed) < 0) ||
  1291. (cfsetospeed(&tios, speed) < 0)) {
  1292. perror("cfsetispeed/cfsetospeed\n");
  1293. return -1;
  1294. }
  1295. /* C_CFLAG Control options
  1296. CLOCAL Local line - do not change "owner" of port
  1297. CREAD Enable receiver
  1298. */
  1299. tios.c_cflag |= (CREAD | CLOCAL);
  1300. /* CSIZE, HUPCL, CRTSCTS (hardware flow control) */
  1301. /* Set data bits (5, 6, 7, 8 bits)
  1302. CSIZE Bit mask for data bits
  1303. */
  1304. tios.c_cflag &= ~CSIZE;
  1305. switch (mb_param->data_bit) {
  1306. case 5:
  1307. tios.c_cflag |= CS5;
  1308. break;
  1309. case 6:
  1310. tios.c_cflag |= CS6;
  1311. break;
  1312. case 7:
  1313. tios.c_cflag |= CS7;
  1314. break;
  1315. case 8:
  1316. default:
  1317. tios.c_cflag |= CS8;
  1318. break;
  1319. }
  1320. /* Stop bit (1 or 2) */
  1321. if (mb_param->stop_bit == 1)
  1322. tios.c_cflag &=~ CSTOPB;
  1323. else /* 2 */
  1324. tios.c_cflag |= CSTOPB;
  1325. /* PARENB Enable parity bit
  1326. PARODD Use odd parity instead of even */
  1327. if (strncmp(mb_param->parity, "none", 4) == 0) {
  1328. tios.c_cflag &=~ PARENB;
  1329. } else if (strncmp(mb_param->parity, "even", 4) == 0) {
  1330. tios.c_cflag |= PARENB;
  1331. tios.c_cflag &=~ PARODD;
  1332. } else {
  1333. /* odd */
  1334. tios.c_cflag |= PARENB;
  1335. tios.c_cflag |= PARODD;
  1336. }
  1337. /* Read the man page of termios if you need more information. */
  1338. /* This field isn't used on POSIX systems
  1339. tios.c_line = 0;
  1340. */
  1341. /* C_LFLAG Line options
  1342. ISIG Enable SIGINTR, SIGSUSP, SIGDSUSP, and SIGQUIT signals
  1343. ICANON Enable canonical input (else raw)
  1344. XCASE Map uppercase \lowercase (obsolete)
  1345. ECHO Enable echoing of input characters
  1346. ECHOE Echo erase character as BS-SP-BS
  1347. ECHOK Echo NL after kill character
  1348. ECHONL Echo NL
  1349. NOFLSH Disable flushing of input buffers after
  1350. interrupt or quit characters
  1351. IEXTEN Enable extended functions
  1352. ECHOCTL Echo control characters as ^char and delete as ~?
  1353. ECHOPRT Echo erased character as character erased
  1354. ECHOKE BS-SP-BS entire line on line kill
  1355. FLUSHO Output being flushed
  1356. PENDIN Retype pending input at next read or input char
  1357. TOSTOP Send SIGTTOU for background output
  1358. Canonical input is line-oriented. Input characters are put
  1359. into a buffer which can be edited interactively by the user
  1360. until a CR (carriage return) or LF (line feed) character is
  1361. received.
  1362. Raw input is unprocessed. Input characters are passed
  1363. through exactly as they are received, when they are
  1364. received. Generally you'll deselect the ICANON, ECHO,
  1365. ECHOE, and ISIG options when using raw input
  1366. */
  1367. /* Raw input */
  1368. tios.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
  1369. /* C_IFLAG Input options
  1370. Constant Description
  1371. INPCK Enable parity check
  1372. IGNPAR Ignore parity errors
  1373. PARMRK Mark parity errors
  1374. ISTRIP Strip parity bits
  1375. IXON Enable software flow control (outgoing)
  1376. IXOFF Enable software flow control (incoming)
  1377. IXANY Allow any character to start flow again
  1378. IGNBRK Ignore break condition
  1379. BRKINT Send a SIGINT when a break condition is detected
  1380. INLCR Map NL to CR
  1381. IGNCR Ignore CR
  1382. ICRNL Map CR to NL
  1383. IUCLC Map uppercase to lowercase
  1384. IMAXBEL Echo BEL on input line too long
  1385. */
  1386. if (strncmp(mb_param->parity, "none", 4) == 0) {
  1387. tios.c_iflag &= ~INPCK;
  1388. } else {
  1389. tios.c_iflag |= INPCK;
  1390. }
  1391. /* Software flow control is disabled */
  1392. tios.c_iflag &= ~(IXON | IXOFF | IXANY);
  1393. /* C_OFLAG Output options
  1394. OPOST Postprocess output (not set = raw output)
  1395. ONLCR Map NL to CR-NL
  1396. ONCLR ant others needs OPOST to be enabled
  1397. */
  1398. /* Raw ouput */
  1399. tios.c_oflag &=~ OPOST;
  1400. /* C_CC Control characters
  1401. VMIN Minimum number of characters to read
  1402. VTIME Time to wait for data (tenths of seconds)
  1403. UNIX serial interface drivers provide the ability to
  1404. specify character and packet timeouts. Two elements of the
  1405. c_cc array are used for timeouts: VMIN and VTIME. Timeouts
  1406. are ignored in canonical input mode or when the NDELAY
  1407. option is set on the file via open or fcntl.
  1408. VMIN specifies the minimum number of characters to read. If
  1409. it is set to 0, then the VTIME value specifies the time to
  1410. wait for every character read. Note that this does not mean
  1411. that a read call for N bytes will wait for N characters to
  1412. come in. Rather, the timeout will apply to the first
  1413. character and the read call will return the number of
  1414. characters immediately available (up to the number you
  1415. request).
  1416. If VMIN is non-zero, VTIME specifies the time to wait for
  1417. the first character read. If a character is read within the
  1418. time given, any read will block (wait) until all VMIN
  1419. characters are read. That is, once the first character is
  1420. read, the serial interface driver expects to receive an
  1421. entire packet of characters (VMIN bytes total). If no
  1422. character is read within the time allowed, then the call to
  1423. read returns 0. This method allows you to tell the serial
  1424. driver you need exactly N bytes and any read call will
  1425. return 0 or N bytes. However, the timeout only applies to
  1426. the first character read, so if for some reason the driver
  1427. misses one character inside the N byte packet then the read
  1428. call could block forever waiting for additional input
  1429. characters.
  1430. VTIME specifies the amount of time to wait for incoming
  1431. characters in tenths of seconds. If VTIME is set to 0 (the
  1432. default), reads will block (wait) indefinitely unless the
  1433. NDELAY option is set on the port with open or fcntl.
  1434. */
  1435. /* Unused because we use open with the NDELAY option */
  1436. tios.c_cc[VMIN] = 0;
  1437. tios.c_cc[VTIME] = 0;
  1438. if (tcsetattr(mb_param->fd, TCSANOW, &tios) < 0) {
  1439. perror("tcsetattr\n");
  1440. return -1;
  1441. }
  1442. return 0;
  1443. }
  1444. /* Establishes a modbus TCP connection with a modbus slave */
  1445. static int modbus_connect_tcp(modbus_param_t *mb_param)
  1446. {
  1447. int ret;
  1448. int option;
  1449. struct sockaddr_in addr;
  1450. mb_param->fd = socket(PF_INET, SOCK_STREAM, 0);
  1451. if (mb_param->fd < 0) {
  1452. return mb_param->fd;
  1453. }
  1454. /* Set the TCP no delay flag */
  1455. /* SOL_TCP = IPPROTO_TCP */
  1456. option = 1;
  1457. ret = setsockopt(mb_param->fd, IPPROTO_TCP, TCP_NODELAY,
  1458. (const void *)&option, sizeof(int));
  1459. if (ret < 0) {
  1460. perror("setsockopt");
  1461. close(mb_param->fd);
  1462. return ret;
  1463. }
  1464. #if (!HAVE_DECL___CYGWIN__)
  1465. /**
  1466. * Cygwin defines IPTOS_LOWDELAY but can't handle that flag so it's
  1467. * necessary to workaround that problem.
  1468. **/
  1469. /* Set the IP low delay option */
  1470. option = IPTOS_LOWDELAY;
  1471. ret = setsockopt(mb_param->fd, IPPROTO_TCP, IP_TOS,
  1472. (const void *)&option, sizeof(int));
  1473. if (ret < 0) {
  1474. perror("setsockopt");
  1475. close(mb_param->fd);
  1476. return ret;
  1477. }
  1478. #endif
  1479. if (mb_param->debug) {
  1480. printf("Connecting to %s\n", mb_param->ip);
  1481. }
  1482. addr.sin_family = AF_INET;
  1483. addr.sin_port = htons(mb_param->port);
  1484. addr.sin_addr.s_addr = inet_addr(mb_param->ip);
  1485. ret = connect(mb_param->fd, (struct sockaddr *)&addr,
  1486. sizeof(struct sockaddr_in));
  1487. if (ret < 0) {
  1488. perror("connect");
  1489. close(mb_param->fd);
  1490. return ret;
  1491. }
  1492. return 0;
  1493. }
  1494. /* Establishes a modbus connexion.
  1495. Returns 0 on success or -1 on failure. */
  1496. int modbus_connect(modbus_param_t *mb_param)
  1497. {
  1498. int ret;
  1499. if (mb_param->type_com == RTU)
  1500. ret = modbus_connect_rtu(mb_param);
  1501. else
  1502. ret = modbus_connect_tcp(mb_param);
  1503. return ret;
  1504. }
  1505. /* Closes the file descriptor in RTU mode */
  1506. static void modbus_close_rtu(modbus_param_t *mb_param)
  1507. {
  1508. if (tcsetattr(mb_param->fd, TCSANOW, &(mb_param->old_tios)) < 0)
  1509. perror("tcsetattr");
  1510. close(mb_param->fd);
  1511. }
  1512. /* Closes the network connection and socket in TCP mode */
  1513. static void modbus_close_tcp(modbus_param_t *mb_param)
  1514. {
  1515. shutdown(mb_param->fd, SHUT_RDWR);
  1516. close(mb_param->fd);
  1517. }
  1518. /* Closes a modbus connection */
  1519. void modbus_close(modbus_param_t *mb_param)
  1520. {
  1521. if (mb_param->type_com == RTU)
  1522. modbus_close_rtu(mb_param);
  1523. else
  1524. modbus_close_tcp(mb_param);
  1525. }
  1526. /* Activates the debug messages */
  1527. void modbus_set_debug(modbus_param_t *mb_param, int boolean)
  1528. {
  1529. mb_param->debug = boolean;
  1530. }
  1531. /* Allocates 4 arrays to store coils, input status, input registers and
  1532. holding registers. The pointers are stored in modbus_mapping structure.
  1533. Returns 0 on success and -1 on failure.
  1534. */
  1535. int modbus_mapping_new(modbus_mapping_t *mb_mapping,
  1536. int nb_coil_status, int nb_input_status,
  1537. int nb_holding_registers, int nb_input_registers)
  1538. {
  1539. /* 0X */
  1540. mb_mapping->nb_coil_status = nb_coil_status;
  1541. mb_mapping->tab_coil_status =
  1542. (uint8_t *) malloc(nb_coil_status * sizeof(uint8_t));
  1543. memset(mb_mapping->tab_coil_status, 0,
  1544. nb_coil_status * sizeof(uint8_t));
  1545. if (mb_mapping->tab_coil_status == NULL)
  1546. return -1;
  1547. /* 1X */
  1548. mb_mapping->nb_input_status = nb_input_status;
  1549. mb_mapping->tab_input_status =
  1550. (uint8_t *) malloc(nb_input_status * sizeof(uint8_t));
  1551. memset(mb_mapping->tab_input_status, 0,
  1552. nb_input_status * sizeof(uint8_t));
  1553. if (mb_mapping->tab_input_status == NULL) {
  1554. free(mb_mapping->tab_coil_status);
  1555. return -1;
  1556. }
  1557. /* 4X */
  1558. mb_mapping->nb_holding_registers = nb_holding_registers;
  1559. mb_mapping->tab_holding_registers =
  1560. (uint16_t *) malloc(nb_holding_registers * sizeof(uint16_t));
  1561. memset(mb_mapping->tab_holding_registers, 0,
  1562. nb_holding_registers * sizeof(uint16_t));
  1563. if (mb_mapping->tab_holding_registers == NULL) {
  1564. free(mb_mapping->tab_coil_status);
  1565. free(mb_mapping->tab_input_status);
  1566. return -1;
  1567. }
  1568. /* 3X */
  1569. mb_mapping->nb_input_registers = nb_input_registers;
  1570. mb_mapping->tab_input_registers =
  1571. (uint16_t *) malloc(nb_input_registers * sizeof(uint16_t));
  1572. memset(mb_mapping->tab_input_registers, 0,
  1573. nb_input_registers * sizeof(uint16_t));
  1574. if (mb_mapping->tab_input_registers == NULL) {
  1575. free(mb_mapping->tab_coil_status);
  1576. free(mb_mapping->tab_input_status);
  1577. free(mb_mapping->tab_holding_registers);
  1578. return -1;
  1579. }
  1580. return 0;
  1581. }
  1582. /* Frees the 4 arrays */
  1583. void modbus_mapping_free(modbus_mapping_t *mb_mapping)
  1584. {
  1585. free(mb_mapping->tab_coil_status);
  1586. free(mb_mapping->tab_input_status);
  1587. free(mb_mapping->tab_holding_registers);
  1588. free(mb_mapping->tab_input_registers);
  1589. }
  1590. /* Listens for any query from one or many modbus masters in TCP */
  1591. int modbus_slave_listen_tcp(modbus_param_t *mb_param, int nb_connection)
  1592. {
  1593. int new_socket;
  1594. int yes;
  1595. struct sockaddr_in addr;
  1596. new_socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
  1597. if (new_socket < 0) {
  1598. perror("socket");
  1599. return -1;
  1600. }
  1601. yes = 1;
  1602. if (setsockopt(new_socket, SOL_SOCKET, SO_REUSEADDR,
  1603. (char *) &yes, sizeof(yes)) < 0) {
  1604. perror("setsockopt");
  1605. close(new_socket);
  1606. return -1;
  1607. }
  1608. memset(&addr, 0, sizeof(addr));
  1609. addr.sin_family = AF_INET;
  1610. /* If the modbus port is < to 1024, we need the setuid root. */
  1611. addr.sin_port = htons(mb_param->port);
  1612. addr.sin_addr.s_addr = INADDR_ANY;
  1613. if (bind(new_socket, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
  1614. perror("bind");
  1615. close(new_socket);
  1616. return -1;
  1617. }
  1618. if (listen(new_socket, nb_connection) < 0) {
  1619. perror("listen");
  1620. close(new_socket);
  1621. return -1;
  1622. }
  1623. return new_socket;
  1624. }
  1625. int modbus_slave_accept_tcp(modbus_param_t *mb_param, int *socket)
  1626. {
  1627. struct sockaddr_in addr;
  1628. socklen_t addrlen;
  1629. addrlen = sizeof(struct sockaddr_in);
  1630. mb_param->fd = accept(*socket, (struct sockaddr *)&addr, &addrlen);
  1631. if (mb_param->fd < 0) {
  1632. perror("accept");
  1633. close(*socket);
  1634. *socket = 0;
  1635. } else {
  1636. printf("The client %s is connected\n",
  1637. inet_ntoa(addr.sin_addr));
  1638. }
  1639. return mb_param->fd;
  1640. }
  1641. /** Utils **/
  1642. /* Sets many input/coil status from a single byte value (all 8 bits of
  1643. the byte value are set) */
  1644. void set_bits_from_byte(uint8_t *dest, int address, const uint8_t value)
  1645. {
  1646. int i;
  1647. for (i=0; i<8; i++) {
  1648. dest[address+i] = (value & (1 << i)) ? ON : OFF;
  1649. }
  1650. }
  1651. /* Sets many input/coil status from a table of bytes (only the bits
  1652. between address and address + nb_bits are set) */
  1653. void set_bits_from_bytes(uint8_t *dest, int address, int nb_bits,
  1654. const uint8_t tab_byte[])
  1655. {
  1656. int i;
  1657. int shift = 0;
  1658. for (i = address; i < address + nb_bits; i++) {
  1659. dest[i] = tab_byte[(i - address) / 8] & (1 << shift) ? ON : OFF;
  1660. /* gcc doesn't like: shift = (++shift) % 8; */
  1661. shift++;
  1662. shift %= 8;
  1663. }
  1664. }
  1665. /* Gets the byte value from many input/coil status.
  1666. To obtain a full byte, set nb_bits to 8. */
  1667. uint8_t get_byte_from_bits(const uint8_t *src, int address, int nb_bits)
  1668. {
  1669. int i;
  1670. uint8_t value = 0;
  1671. if (nb_bits > 8) {
  1672. printf("Error: nb_bits is too big\n");
  1673. nb_bits = 8;
  1674. }
  1675. for (i=0; i < nb_bits; i++) {
  1676. value |= (src[address+i] << i);
  1677. }
  1678. return value;
  1679. }