modbus.c 66 KB

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