modbus.c 72 KB

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